diff --git a/media/editors/codemirror/addon/edit/closebrackets.js b/media/editors/codemirror/addon/edit/closebrackets.js index af7fce2a82222..7c47bcd096e66 100644 --- a/media/editors/codemirror/addon/edit/closebrackets.js +++ b/media/editors/codemirror/addon/edit/closebrackets.js @@ -116,7 +116,9 @@ if (opening && !range.empty()) { curType = "surround"; } else if ((identical || !opening) && next == ch) { - if (triples.indexOf(ch) >= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch) + if (identical && stringStartsAfter(cm, cur)) + curType = "both"; + else if (triples.indexOf(ch) >= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch) curType = "skipThree"; else curType = "skip"; @@ -192,4 +194,9 @@ stream.start = stream.pos; } } + + function stringStartsAfter(cm, pos) { + var token = cm.getTokenAt(Pos(pos.line, pos.ch + 1)) + return /\bstring/.test(token.type) && token.start == pos.ch + } }); diff --git a/media/editors/codemirror/addon/edit/closebrackets.min.js b/media/editors/codemirror/addon/edit/closebrackets.min.js index 67d29255c6148..af00768a7c92b 100644 --- a/media/editors/codemirror/addon/edit/closebrackets.min.js +++ b/media/editors/codemirror/addon/edit/closebrackets.min.js @@ -1 +1 @@ -!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){function b(a,b){return"pairs"==b&&"string"==typeof a?a:"object"==typeof a&&null!=a[b]?a[b]:l[b]}function c(a){return function(b){return h(b,a)}}function d(a){var b=a.state.closeBrackets;if(!b)return null;var c=a.getModeAt(a.getCursor());return c.closeBrackets||b}function e(c){var e=d(c);if(!e||c.getOption("disableInput"))return a.Pass;for(var f=b(e,"pairs"),g=c.listSelections(),h=0;h=0;h--){var k=g[h].head;c.replaceRange("",m(k.line,k.ch-1),m(k.line,k.ch+1),"+delete")}}function f(c){var e=d(c),f=e&&b(e,"explode");if(!f||c.getOption("disableInput"))return a.Pass;for(var g=c.listSelections(),h=0;h0;return{anchor:new m(b.anchor.line,b.anchor.ch+(c?-1:1)),head:new m(b.head.line,b.head.ch+(c?1:-1))}}function h(c,e){var f=d(c);if(!f||c.getOption("disableInput"))return a.Pass;var h=b(f,"pairs"),j=h.indexOf(e);if(j==-1)return a.Pass;for(var l,n=b(f,"triples"),o=h.charAt(j+1)==e,p=c.listSelections(),q=j%2==0,r=0;r1&&n.indexOf(e)>=0&&c.getRange(m(u.line,u.ch-2),u)==e+e&&(u.ch<=2||c.getRange(m(u.line,u.ch-3),m(u.line,u.ch-2))!=e))s="addFour";else if(o){if(a.isWordChar(v)||!k(c,u,e))return a.Pass;s="both"}else{if(!q||c.getLine(u.line).length!=u.ch&&!i(v,h)&&!/\s/.test(v))return a.Pass;s="both"}else s=n.indexOf(e)>=0&&c.getRange(u,m(u.line,u.ch+3))==e+e+e?"skipThree":"skip";if(l){if(l!=s)return a.Pass}else l=s}var w=j%2?h.charAt(j-1):e,x=j%2?e:h.charAt(j+1);c.operation((function(){if("skip"==l)c.execCommand("goCharRight");else if("skipThree"==l)for(var a=0;a<3;a++)c.execCommand("goCharRight");else if("surround"==l){for(var b=c.getSelections(),a=0;a-1&&c%2==1}function j(a,b){var c=a.getRange(m(b.line,b.ch-1),m(b.line,b.ch+1));return 2==c.length?c:null}function k(b,c,d){var e=b.getLine(c.line),f=b.getTokenAt(c);if(/\bstring2?\b/.test(f.type))return!1;var g=new a.StringStream(e.slice(0,c.ch)+d+e.slice(c.ch),4);for(g.pos=g.start=f.start;;){var h=b.getMode().token(g,f.state);if(g.pos>=c.ch+1)return/\bstring2?\b/.test(h);g.start=g.pos}}var l={pairs:"()[]{}''\"\"",triples:"",explode:"[]{}"},m=a.Pos;a.defineOption("autoCloseBrackets",!1,(function(b,c,d){d&&d!=a.Init&&(b.removeKeyMap(o),b.state.closeBrackets=null),c&&(b.state.closeBrackets=c,b.addKeyMap(o))}));for(var n=l.pairs+"`",o={Backspace:e,Enter:f},p=0;p=0;h--){var k=g[h].head;c.replaceRange("",n(k.line,k.ch-1),n(k.line,k.ch+1),"+delete")}}function f(c){var e=d(c),f=e&&b(e,"explode");if(!f||c.getOption("disableInput"))return a.Pass;for(var g=c.listSelections(),h=0;h0;return{anchor:new n(b.anchor.line,b.anchor.ch+(c?-1:1)),head:new n(b.head.line,b.head.ch+(c?1:-1))}}function h(c,e){var f=d(c);if(!f||c.getOption("disableInput"))return a.Pass;var h=b(f,"pairs"),j=h.indexOf(e);if(j==-1)return a.Pass;for(var m,o=b(f,"triples"),p=h.charAt(j+1)==e,q=c.listSelections(),r=j%2==0,s=0;s1&&o.indexOf(e)>=0&&c.getRange(n(v.line,v.ch-2),v)==e+e&&(v.ch<=2||c.getRange(n(v.line,v.ch-3),n(v.line,v.ch-2))!=e))t="addFour";else if(p){if(a.isWordChar(w)||!k(c,v,e))return a.Pass;t="both"}else{if(!r||c.getLine(v.line).length!=v.ch&&!i(w,h)&&!/\s/.test(w))return a.Pass;t="both"}else t=p&&l(c,v)?"both":o.indexOf(e)>=0&&c.getRange(v,n(v.line,v.ch+3))==e+e+e?"skipThree":"skip";if(m){if(m!=t)return a.Pass}else m=t}var x=j%2?h.charAt(j-1):e,y=j%2?e:h.charAt(j+1);c.operation((function(){if("skip"==m)c.execCommand("goCharRight");else if("skipThree"==m)for(var a=0;a<3;a++)c.execCommand("goCharRight");else if("surround"==m){for(var b=c.getSelections(),a=0;a-1&&c%2==1}function j(a,b){var c=a.getRange(n(b.line,b.ch-1),n(b.line,b.ch+1));return 2==c.length?c:null}function k(b,c,d){var e=b.getLine(c.line),f=b.getTokenAt(c);if(/\bstring2?\b/.test(f.type))return!1;var g=new a.StringStream(e.slice(0,c.ch)+d+e.slice(c.ch),4);for(g.pos=g.start=f.start;;){var h=b.getMode().token(g,f.state);if(g.pos>=c.ch+1)return/\bstring2?\b/.test(h);g.start=g.pos}}function l(a,b){var c=a.getTokenAt(n(b.line,b.ch+1));return/\bstring/.test(c.type)&&c.start==b.ch}var m={pairs:"()[]{}''\"\"",triples:"",explode:"[]{}"},n=a.Pos;a.defineOption("autoCloseBrackets",!1,(function(b,c,d){d&&d!=a.Init&&(b.removeKeyMap(p),b.state.closeBrackets=null),c&&(b.state.closeBrackets=c,b.addKeyMap(p))}));for(var o=m.pairs+"`",p={Backspace:e,Enter:f},q=0;q[> ]*|[*+-]\s|(\d+)([.)]))(\s*)/, - emptyListRE = /^(\s*)(>[> ]*|[*+-]|(\d+)[.)])(\s*)$/, + var listRE = /^(\s*)(>[> ]*|- \[[x ]\]\s|[*+-]\s|(\d+)([.)]))(\s*)/, + emptyListRE = /^(\s*)(>[> ]*|- \[[x ]\]|[*+-]|(\d+)[.)])(\s*)$/, unorderedListRE = /[*+-]\s/; CodeMirror.commands.newlineAndIndentContinueMarkdownList = function(cm) { @@ -39,7 +39,7 @@ } else { var indent = match[1], after = match[5]; var bullet = unorderedListRE.test(match[2]) || match[2].indexOf(">") >= 0 - ? match[2] + ? match[2].replace("x", " ") : (parseInt(match[3], 10) + 1) + match[4]; replacements[i] = "\n" + indent + bullet + after; diff --git a/media/editors/codemirror/addon/edit/continuelist.min.js b/media/editors/codemirror/addon/edit/continuelist.min.js index 04f5f8190b132..fb0f66d51d167 100644 --- a/media/editors/codemirror/addon/edit/continuelist.min.js +++ b/media/editors/codemirror/addon/edit/continuelist.min.js @@ -1 +1 @@ -!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";var b=/^(\s*)(>[> ]*|[*+-]\s|(\d+)([.)]))(\s*)/,c=/^(\s*)(>[> ]*|[*+-]|(\d+)[.)])(\s*)$/,d=/[*+-]\s/;a.commands.newlineAndIndentContinueMarkdownList=function(e){if(e.getOption("disableInput"))return a.Pass;for(var f=e.listSelections(),g=[],h=0;h")>=0?n[2]:parseInt(n[3],10)+1+n[4];g[h]="\n"+o+q+p}}e.replaceSelections(g)}})); \ No newline at end of file +!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";var b=/^(\s*)(>[> ]*|- \[[x ]\]\s|[*+-]\s|(\d+)([.)]))(\s*)/,c=/^(\s*)(>[> ]*|- \[[x ]\]|[*+-]|(\d+)[.)])(\s*)$/,d=/[*+-]\s/;a.commands.newlineAndIndentContinueMarkdownList=function(e){if(e.getOption("disableInput"))return a.Pass;for(var f=e.listSelections(),g=[],h=0;h")>=0?n[2].replace("x"," "):parseInt(n[3],10)+1+n[4];g[h]="\n"+o+q+p}}e.replaceSelections(g)}})); \ No newline at end of file diff --git a/media/editors/codemirror/addon/lint/lint.js b/media/editors/codemirror/addon/lint/lint.js index e3a452766d313..c1f1702f92152 100644 --- a/media/editors/codemirror/addon/lint/lint.js +++ b/media/editors/codemirror/addon/lint/lint.js @@ -226,7 +226,7 @@ var state = cm.state.lint = new LintState(cm, parseOptions(cm, val), hasLintGutter); if (state.options.lintOnChange !== false) cm.on("change", onChange); - if (state.options.tooltips != false) + if (state.options.tooltips != false && state.options.tooltips != "gutter") CodeMirror.on(cm.getWrapperElement(), "mouseover", state.onMouseOver); startLinting(cm); diff --git a/media/editors/codemirror/addon/lint/lint.min.js b/media/editors/codemirror/addon/lint/lint.min.js index c1715f8cceeae..3ad0b3474d55b 100644 --- a/media/editors/codemirror/addon/lint/lint.min.js +++ b/media/editors/codemirror/addon/lint/lint.min.js @@ -1 +1 @@ -!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";function b(b,c){function d(b){return e.parentNode?(e.style.top=Math.max(0,b.clientY-e.offsetHeight-5)+"px",void(e.style.left=b.clientX+5+"px")):a.off(document,"mousemove",d)}var e=document.createElement("div");return e.className="CodeMirror-lint-tooltip",e.appendChild(c.cloneNode(!0)),document.body.appendChild(e),a.on(document,"mousemove",d),d(b),null!=e.style.opacity&&(e.style.opacity=1),e}function c(a){a.parentNode&&a.parentNode.removeChild(a)}function d(a){a.parentNode&&(null==a.style.opacity&&c(a),a.style.opacity=0,setTimeout((function(){c(a)}),600))}function e(c,e,f){function g(){a.off(f,"mouseout",g),h&&(d(h),h=null)}var h=b(c,e),i=setInterval((function(){if(h)for(var a=f;;a=a.parentNode){if(a&&11==a.nodeType&&(a=a.host),a==document.body)return;if(!a){g();break}}if(!h)return clearInterval(i)}),400);a.on(f,"mouseout",g)}function f(a,b,c){this.marked=[],this.options=b,this.timeout=null,this.hasGutter=c,this.onMouseOver=function(b){r(a,b)},this.waitingFor=0}function g(a,b){return b instanceof Function?{getAnnotations:b}:(b&&b!==!0||(b={}),b)}function h(a){var b=a.state.lint;b.hasGutter&&a.clearGutter(s);for(var c=0;c1,c.options.tooltips))}}d.onUpdateLinting&&d.onUpdateLinting(b,e,a)}function p(a){var b=a.state.lint;b&&(clearTimeout(b.timeout),b.timeout=setTimeout((function(){n(a)}),b.options.delay||500))}function q(a,b){for(var c=b.target||b.srcElement,d=document.createDocumentFragment(),f=0;f1,c.options.tooltips))}}d.onUpdateLinting&&d.onUpdateLinting(b,e,a)}function p(a){var b=a.state.lint;b&&(clearTimeout(b.timeout),b.timeout=setTimeout((function(){n(a)}),b.options.delay||500))}function q(a,b){for(var c=b.target||b.srcElement,d=document.createDocumentFragment(),f=0;fe)return!1;var f=c.getScrollInfo();if("align"==a.mv.options.connect)q=f.top;else{var h,i,j=.5*f.clientHeight,k=f.top+j,l=c.lineAtHeight(k,"local"),m=z(a.chunks,l,b==DIFF_INSERT),n=g(c,b==DIFF_INSERT?m.edit:m.orig),o=g(d,b==DIFF_INSERT?m.orig:m.edit),p=(k-n.top)/(n.bot-n.top),q=o.top-j+p*(o.bot-o.top);if(q>f.top&&(i=f.top/j)<1)q=q*i+f.top*(1-i);else if((h=f.height-f.clientHeight-f.top)h&&(i=h/j)<1&&(q=q*i+(r.height-r.clientHeight-h)*(1-i))}}return d.scrollTo(f.left,q),d.state.scrollSetAt=e,d.state.scrollSetBy=a,!0}function g(a,b){var c=b.after;return null==c&&(c=a.lastLine()+1),{top:a.heightAtLine(b.before||0,"local"),bot:a.heightAtLine(c,"local")}}function h(a,b,c){a.lockScroll=b,b&&0!=c&&f(a,DIFF_INSERT)&&l(a),a.lockButton.innerHTML=b?"⇛⇚":"⇛  ⇚"}function i(b,c,d){for(var e=0;e20||c.from-f.to>20?(i(a,c.marked,e),k(a,b,d,c.marked,f.from,f.to,e),c.from=f.from,c.to=f.to):(f.fromc.to&&(k(a,b,d,c.marked,c.to,f.to,e),c.to=f.to))}))}function k(a,b,c,d,e,f,g){function h(b,c){for(var h=Math.max(e,b),i=Math.min(f,c),j=h;jr&&(n&&h(m,r),m=s)}else if(p==c){var t=I(i,q,!0),u=K(j,i),v=J(k,t);L(u,v)||d.push(a.markText(u,v,{className:l})),i=t}}m<=i.line&&h(m,i.line+1)}function l(a){if(a.showDifferences){if(a.svg){F(a.svg);var b=a.gap.offsetWidth;G(a.svg,"width",b,"height",a.gap.offsetHeight)}a.copyButtons&&F(a.copyButtons);for(var c=a.edit.getViewport(),d=a.orig.getViewport(),e=a.mv.wrap.getBoundingClientRect().top,f=e-a.edit.getScrollerElement().getBoundingClientRect().top+a.edit.getScrollInfo().top,g=e-a.orig.getScrollerElement().getBoundingClientRect().top+a.orig.getScrollInfo().top,h=0;h=c.from&&i.origFrom<=d.to&&i.origTo>=d.from&&r(a,i,g,f,b)}}}function m(a,b){for(var c=0,d=0,e=0;ea&&f.editFrom<=a)return null;if(f.editFrom>a)break;c=f.editTo,d=f.origTo}return d+(a-c)}function n(a,b){for(var c=[],d=0;de.editTo)break}f>-1&&c.splice(f-1,0,[m(e.editTo,a.chunks),e.editTo,e.origTo])}return c}function o(a,b){if(a.dealigned||b){if(!a.orig.curOp)return a.orig.operation((function(){o(a,b)}));a.dealigned=!1;var d=a.mv.left==a?a.mv.right:a.mv.left;d&&(c(d),d.dealigned=!1);for(var e=n(a,d),f=a.mv.aligners,g=0;g1&&c.push(q(a[f],b[f],h))}}function q(a,b,c){var d=!0;b>a.lastLine()&&(b--,d=!1);var e=document.createElement("div");return e.className="CodeMirror-merge-spacer",e.style.height=c+"px",e.style.minWidth="1px",a.addLineWidget(b,e,{height:c,above:d})}function r(a,b,c,d,e){var f="left"==a.type,g=a.orig.heightAtLine(b.origFrom,"local")-c;if(a.svg){var h=g,i=a.edit.heightAtLine(b.editFrom,"local")-d;if(f){var j=h;h=i,i=j}var k=a.orig.heightAtLine(b.origTo,"local")-c,l=a.edit.heightAtLine(b.editTo,"local")-d;if(f){var j=k;k=l,l=j}var m=" C "+e/2+" "+i+" "+e/2+" "+h+" "+(e+2)+" "+h,n=" C "+e/2+" "+k+" "+e/2+" "+l+" -1 "+l;G(a.svg.appendChild(document.createElementNS(Q,"path")),"d","M -1 "+i+m+" L "+(e+2)+" "+k+n+" z","class",a.classes.connect)}if(a.copyButtons){var o=a.copyButtons.appendChild(E("div","left"==a.type?"⇝":"⇜","CodeMirror-merge-copy")),p=a.mv.options.allowEditingOriginals;if(o.title=p?"Push to left":"Revert chunk",o.chunk=b,o.style.top=g+"px",p){var q=a.orig.heightAtLine(b.editFrom,"local")-d,r=a.copyButtons.appendChild(E("div","right"==a.type?"⇝":"⇜","CodeMirror-merge-copy-reverse"));r.title="Push to right",r.chunk={editFrom:b.origFrom,editTo:b.origTo,origFrom:b.editFrom,origTo:b.editTo},r.style.top=q+"px","right"==a.type?r.style.left="2px":r.style.right="2px"}}}function s(a,b,c,d){if(!a.diffOutOfDate){var e=d.editTo>b.lastLine()?P(d.editFrom-1):P(d.editFrom,0),f=d.origTo>c.lastLine()?P(d.origFrom-1):P(d.origFrom,0);b.replaceRange(c.getRange(f,P(d.origTo,0)),e,P(d.editTo,0))}}function t(b){var c=b.lockButton=E("div",null,"CodeMirror-merge-scrolllock");c.title="Toggle locked scrolling";var d=E("div",[c],"CodeMirror-merge-scrolllock-wrap");a.on(c,"click",(function(){h(b,!b.lockScroll)}));var e=[d];if(b.mv.options.revertButtons!==!1&&(b.copyButtons=E("div",null,"CodeMirror-merge-copybuttons-"+b.type),a.on(b.copyButtons,"click",(function(a){var c=a.target||a.srcElement;if(c.chunk)return"CodeMirror-merge-copy-reverse"==c.className?void s(b,b.orig,b.edit,c.chunk):void s(b,b.edit,b.orig,c.chunk)})),e.unshift(b.copyButtons)),"align"!=b.mv.options.connect){var f=document.createElementNS&&document.createElementNS(Q,"svg");f&&!f.createSVGRect&&(f=null),b.svg=f,f&&e.push(f)}return b.gap=E("div",e,"CodeMirror-merge-gap")}function u(a){return"string"==typeof a?a:a.getValue()}function v(a,b){var c=T.diff_main(a,b);T.diff_cleanupSemantic(c);for(var d=0;dk&&(g&&b.push({origFrom:d,origTo:l,editFrom:c,editTo:k}),c=n,d=o)}else I(i==DIFF_INSERT?e:f,h[1])}return(c<=e.line||d<=f.line)&&b.push({origFrom:d,origTo:f.line+1,editFrom:c,editTo:e.line+1}),b}function x(a,b){if(b==a.length-1)return!0;var c=a[b+1][1];return 1!=c.length&&10==c.charCodeAt(0)&&(b==a.length-2||(c=a[b+2][1],c.length>1&&10==c.charCodeAt(0)))}function y(a,b){if(0==b)return!0;var c=a[b-1][1];return 10==c.charCodeAt(c.length-1)&&(1==b||(c=a[b-2][1],10==c.charCodeAt(c.length-1)))}function z(a,b,c){for(var d,e,f,g,h=0;hb?(e=i.editFrom,g=i.origFrom):k>b&&(e=i.editTo,g=i.origTo)),k<=b?(d=i.editTo,f=i.origTo):j<=b&&(d=i.editFrom,f=i.origFrom)}return{edit:{before:d,after:e},orig:{before:f,after:g}}}function A(b,c,d){function e(){g.clear(),b.removeLineClass(c,"wrap","CodeMirror-merge-collapsed-line")}b.addLineClass(c,"wrap","CodeMirror-merge-collapsed-line");var f=document.createElement("span");f.className="CodeMirror-merge-collapsed-widget",f.title="Identical text collapsed. Click to expand.";var g=b.markText(P(c,0),P(d-1),{inclusiveLeft:!0,inclusiveRight:!0,replacedWith:f,clearOnEnter:!0});return a.on(f,"click",e),{mark:g,clear:e}}function B(a,b){function c(){for(var a=0;a=0&&hb){var k=[{line:i,cm:d}];a.left&&k.push({line:m(i,a.left.chunks),cm:a.left.orig}),a.right&&k.push({line:m(i,a.right.chunks),cm:a.right.orig});var l=B(j,k);a.options.onCollapse&&a.options.onCollapse(a,i,j,l)}}}function E(a,b,c,d){var e=document.createElement(a);if(c&&(e.className=c),d&&(e.style.cssText=d),"string"==typeof b)e.appendChild(document.createTextNode(b));else if(b)for(var f=0;f0;--b)a.removeChild(a.firstChild)}function G(a){for(var b=1;b0?a:b}function L(a,b){return a.line==b.line&&a.ch==b.ch}function M(a,b,c){for(var d=a.length-1;d>=0;d--){var e=a[d],f=(c?e.origTo:e.editTo)-1;if(fb)return f}}function O(b,d){var e=null,f=b.state.diffViews,g=b.getCursor().line;if(f)for(var h=0;he:ke)return!1;var f=c.getScrollInfo();if("align"==a.mv.options.connect)q=f.top;else{var h,i,j=.5*f.clientHeight,k=f.top+j,l=c.lineAtHeight(k,"local"),m=B(a.chunks,l,b==DIFF_INSERT),n=g(c,b==DIFF_INSERT?m.edit:m.orig),o=g(d,b==DIFF_INSERT?m.orig:m.edit),p=(k-n.top)/(n.bot-n.top),q=o.top-j+p*(o.bot-o.top);if(q>f.top&&(i=f.top/j)<1)q=q*i+f.top*(1-i);else if((h=f.height-f.clientHeight-f.top)h&&(i=h/j)<1&&(q=q*i+(r.height-r.clientHeight-h)*(1-i))}}return d.scrollTo(f.left,q),d.state.scrollSetAt=e,d.state.scrollSetBy=a,!0}function g(a,b){var c=b.after;return null==c&&(c=a.lastLine()+1),{top:a.heightAtLine(b.before||0,"local"),bot:a.heightAtLine(c,"local")}}function h(a,b,c){a.lockScroll=b,b&&0!=c&&f(a,DIFF_INSERT)&&n(a),a.lockButton.innerHTML=b?"⇛⇚":"⇛  ⇚"}function i(a,b,c){for(var d=c.classLocation,e=0;e20||c.from-f.to>20?(j(a,c.marked,e),m(a,b,d,c.marked,f.from,f.to,e),c.from=f.from,c.to=f.to):(f.fromc.to&&(m(a,b,d,c.marked,c.to,f.to,e),c.to=f.to))}))}function l(a,b,c,d,e,f){for(var g=c.classLocation,h=a.getLineHandle(b),i=0;is&&(o&&h(n,s),n=t)}else if(q==c){var u=K(i,r,!0),v=M(j,i),w=L(k,u);N(v,w)||d.push(a.markText(v,w,{className:m})),i=u}}n<=i.line&&h(n,i.line+1)}function n(a){if(a.showDifferences){if(a.svg){H(a.svg);var b=a.gap.offsetWidth;I(a.svg,"width",b,"height",a.gap.offsetHeight)}a.copyButtons&&H(a.copyButtons);for(var c=a.edit.getViewport(),d=a.orig.getViewport(),e=a.mv.wrap.getBoundingClientRect().top,f=e-a.edit.getScrollerElement().getBoundingClientRect().top+a.edit.getScrollInfo().top,g=e-a.orig.getScrollerElement().getBoundingClientRect().top+a.orig.getScrollInfo().top,h=0;h=c.from&&i.origFrom<=d.to&&i.origTo>=d.from&&t(a,i,g,f,b)}}}function o(a,b){for(var c=0,d=0,e=0;ea&&f.editFrom<=a)return null;if(f.editFrom>a)break;c=f.editTo,d=f.origTo}return d+(a-c)}function p(a,b){for(var c=[],d=0;de.editTo)break}f>-1&&c.splice(f-1,0,[o(e.editTo,a.chunks),e.editTo,e.origTo])}return c}function q(a,b){if(a.dealigned||b){if(!a.orig.curOp)return a.orig.operation((function(){q(a,b)}));a.dealigned=!1;var d=a.mv.left==a?a.mv.right:a.mv.left;d&&(c(d),d.dealigned=!1);for(var e=p(a,d),f=a.mv.aligners,g=0;g1&&c.push(s(a[f],b[f],h))}}function s(a,b,c){var d=!0;b>a.lastLine()&&(b--,d=!1);var e=document.createElement("div");return e.className="CodeMirror-merge-spacer",e.style.height=c+"px",e.style.minWidth="1px",a.addLineWidget(b,e,{height:c,above:d})}function t(a,b,c,d,e){var f="left"==a.type,g=a.orig.heightAtLine(b.origFrom,"local")-c;if(a.svg){var h=g,i=a.edit.heightAtLine(b.editFrom,"local")-d;if(f){var j=h;h=i,i=j}var k=a.orig.heightAtLine(b.origTo,"local")-c,l=a.edit.heightAtLine(b.editTo,"local")-d;if(f){var j=k;k=l,l=j}var m=" C "+e/2+" "+i+" "+e/2+" "+h+" "+(e+2)+" "+h,n=" C "+e/2+" "+k+" "+e/2+" "+l+" -1 "+l;I(a.svg.appendChild(document.createElementNS(S,"path")),"d","M -1 "+i+m+" L "+(e+2)+" "+k+n+" z","class",a.classes.connect)}if(a.copyButtons){var o=a.copyButtons.appendChild(G("div","left"==a.type?"⇝":"⇜","CodeMirror-merge-copy")),p=a.mv.options.allowEditingOriginals;if(o.title=p?"Push to left":"Revert chunk",o.chunk=b,o.style.top=g+"px",p){var q=a.orig.heightAtLine(b.editFrom,"local")-d,r=a.copyButtons.appendChild(G("div","right"==a.type?"⇝":"⇜","CodeMirror-merge-copy-reverse"));r.title="Push to right",r.chunk={editFrom:b.origFrom,editTo:b.origTo,origFrom:b.editFrom,origTo:b.editTo},r.style.top=q+"px","right"==a.type?r.style.left="2px":r.style.right="2px"}}}function u(a,b,c,d){if(!a.diffOutOfDate){var e=d.editTo>b.lastLine()?R(d.editFrom-1):R(d.editFrom,0),f=d.origTo>c.lastLine()?R(d.origFrom-1):R(d.origFrom,0);b.replaceRange(c.getRange(f,R(d.origTo,0)),e,R(d.editTo,0))}}function v(b){var c=b.lockButton=G("div",null,"CodeMirror-merge-scrolllock");c.title="Toggle locked scrolling";var d=G("div",[c],"CodeMirror-merge-scrolllock-wrap");a.on(c,"click",(function(){h(b,!b.lockScroll)}));var e=[d];if(b.mv.options.revertButtons!==!1&&(b.copyButtons=G("div",null,"CodeMirror-merge-copybuttons-"+b.type),a.on(b.copyButtons,"click",(function(a){var c=a.target||a.srcElement;if(c.chunk)return"CodeMirror-merge-copy-reverse"==c.className?void u(b,b.orig,b.edit,c.chunk):void u(b,b.edit,b.orig,c.chunk)})),e.unshift(b.copyButtons)),"align"!=b.mv.options.connect){var f=document.createElementNS&&document.createElementNS(S,"svg");f&&!f.createSVGRect&&(f=null),b.svg=f,f&&e.push(f)}return b.gap=G("div",e,"CodeMirror-merge-gap")}function w(a){return"string"==typeof a?a:a.getValue()}function x(a,b){var c=V.diff_main(a,b);V.diff_cleanupSemantic(c);for(var d=0;dk&&(g&&b.push({origFrom:d,origTo:l,editFrom:c,editTo:k}),c=n,d=o)}else K(i==DIFF_INSERT?e:f,h[1])}return(c<=e.line||d<=f.line)&&b.push({origFrom:d,origTo:f.line+1,editFrom:c,editTo:e.line+1}),b}function z(a,b){if(b==a.length-1)return!0;var c=a[b+1][1];return 1!=c.length&&10==c.charCodeAt(0)&&(b==a.length-2||(c=a[b+2][1],c.length>1&&10==c.charCodeAt(0)))}function A(a,b){if(0==b)return!0;var c=a[b-1][1];return 10==c.charCodeAt(c.length-1)&&(1==b||(c=a[b-2][1],10==c.charCodeAt(c.length-1)))}function B(a,b,c){for(var d,e,f,g,h=0;hb?(e=i.editFrom,g=i.origFrom):k>b&&(e=i.editTo,g=i.origTo)),k<=b?(d=i.editTo,f=i.origTo):j<=b&&(d=i.editFrom,f=i.origFrom)}return{edit:{before:d,after:e},orig:{before:f,after:g}}}function C(b,c,d){function e(){g.clear(),b.removeLineClass(c,"wrap","CodeMirror-merge-collapsed-line")}b.addLineClass(c,"wrap","CodeMirror-merge-collapsed-line");var f=document.createElement("span");f.className="CodeMirror-merge-collapsed-widget",f.title="Identical text collapsed. Click to expand.";var g=b.markText(R(c,0),R(d-1),{inclusiveLeft:!0,inclusiveRight:!0,replacedWith:f,clearOnEnter:!0});return a.on(f,"click",e),{mark:g,clear:e}}function D(a,b){function c(){for(var a=0;a=0&&hb){var k=[{line:i,cm:d}];a.left&&k.push({line:o(i,a.left.chunks),cm:a.left.orig}),a.right&&k.push({line:o(i,a.right.chunks),cm:a.right.orig});var l=D(j,k);a.options.onCollapse&&a.options.onCollapse(a,i,j,l)}}}function G(a,b,c,d){var e=document.createElement(a);if(c&&(e.className=c),d&&(e.style.cssText=d),"string"==typeof b)e.appendChild(document.createTextNode(b));else if(b)for(var f=0;f0;--b)a.removeChild(a.firstChild)}function I(a){for(var b=1;b0?a:b}function N(a,b){return a.line==b.line&&a.ch==b.ch}function O(a,b,c){for(var d=a.length-1;d>=0;d--){var e=a[d],f=(c?e.origTo:e.editTo)-1;if(fb)return f}}function Q(b,d){var e=null,f=b.state.diffViews,g=b.getCursor().line;if(f)for(var h=0;he:k0&&c.ch>=e.length)return b.clipPos(m(c.line+1,0));for(var f,g="start",h=c.ch,i=d<0?0:e.length,j=0;h!=i;h+=d,j++){var k=e.charAt(d<0?h-1:h),l="_"!=k&&a.isWordChar(k)?"w":"o";if("w"==l&&k.toUpperCase()==k&&(l="W"),"start"==g)"o"!=l&&(g="in",f=l);else if("in"==g&&f!=l){if("w"==f&&"W"==l&&d<0&&h--,"W"==f&&"w"==l&&d>0){f="w";continue}break}}return m(c.line,h)}function c(a,c){a.extendSelectionsBy((function(d){return a.display.shift||a.doc.extend||d.empty()?b(a.doc,d.head,c):c<0?d.from():d.to()}))}function d(b,c){return b.isReadOnly()?a.Pass:(b.operation((function(){for(var a=b.listSelections().length,d=[],e=-1,f=0;f=0;h--){var i=d[f[h]];if(!(j&&a.cmpPos(i.head,j)>0)){var k=e(b,i.head);j=k.from,b.replaceRange(c(k.word),k.from,k.to)}}}))}function i(b){var c=b.getCursor("from"),d=b.getCursor("to");if(0==a.cmpPos(c,d)){var f=e(b,c);if(!f.word)return;c=f.from,d=f.to}return{from:c,to:d,query:b.getRange(c,d),word:f}}function j(a,b){var c=i(a);if(c){var d=c.query,e=a.getSearchCursor(d,b?c.to:c.from);(b?e.findNext():e.findPrevious())?a.setSelection(e.from(),e.to()):(e=a.getSearchCursor(d,b?m(a.firstLine(),0):a.clipPos(m(a.lastLine()))),(b?e.findNext():e.findPrevious())?a.setSelection(e.from(),e.to()):c.word&&a.setSelection(c.from,c.to))}}var k=a.keyMap.sublime={fallthrough:"default"},l=a.commands,m=a.Pos,n=a.keyMap.default==a.keyMap.macDefault,o=n?"Cmd-":"Ctrl-",p=n?"Ctrl-":"Alt-";l[k[p+"Left"]="goSubwordLeft"]=function(a){c(a,-1)},l[k[p+"Right"]="goSubwordRight"]=function(a){c(a,1)},n&&(k["Cmd-Left"]="goLineStartSmart");var q=n?"Ctrl-Alt-":"Ctrl-";l[k[q+"Up"]="scrollLineUp"]=function(a){var b=a.getScrollInfo();if(!a.somethingSelected()){var c=a.lineAtHeight(b.top+b.clientHeight,"local");a.getCursor().line>=c&&a.execCommand("goLineUp")}a.scrollTo(null,b.top-a.defaultTextHeight())},l[k[q+"Down"]="scrollLineDown"]=function(a){var b=a.getScrollInfo();if(!a.somethingSelected()){var c=a.lineAtHeight(b.top,"local")+1;a.getCursor().line<=c&&a.execCommand("goLineDown")}a.scrollTo(null,b.top+a.defaultTextHeight())},l[k["Shift-"+o+"L"]="splitSelectionByLine"]=function(a){for(var b=a.listSelections(),c=[],d=0;de.line&&g==f.line&&0==f.ch||c.push({anchor:g==e.line?e:m(g,0),head:g==f.line?f:m(g)});a.setSelections(c,0)},k["Shift-Tab"]="indentLess",l[k.Esc="singleSelectionTop"]=function(a){var b=a.listSelections()[0];a.setSelection(b.anchor,b.head,{scroll:!1})},l[k[o+"L"]="selectLine"]=function(a){for(var b=a.listSelections(),c=[],d=0;de?d.push(i,j):d.length&&(d[d.length-1]=j),e=j}b.operation((function(){for(var a=0;ab.lastLine()?b.replaceRange("\n"+g,m(b.lastLine()),null,"+swapLine"):b.replaceRange(g+"\n",m(e,0),null,"+swapLine")}b.setSelections(f),b.scrollIntoView()}))},l[k[s+"Down"]="swapLineDown"]=function(b){if(b.isReadOnly())return a.Pass;for(var c=b.listSelections(),d=[],e=b.lastLine()+1,f=c.length-1;f>=0;f--){var g=c[f],h=g.to().line+1,i=g.from().line;0!=g.to().ch||g.empty()||h--,h=0;a-=2){var c=d[a],e=d[a+1],f=b.getLine(c);c==b.lastLine()?b.replaceRange("",m(c-1),m(c),"+swapLine"):b.replaceRange("",m(c,0),m(c+1,0),"+swapLine"),b.replaceRange(f+"\n",m(e,0),null,"+swapLine")}b.scrollIntoView()}))},l[k[o+"/"]="toggleCommentIndented"]=function(a){a.toggleComment({indent:!0})},l[k[o+"J"]="joinLines"]=function(a){for(var b=a.listSelections(),c=[],d=0;d=0;e--){var f=c[e].head,g=b.getRange({line:f.line,ch:0},f),h=a.countColumn(g,null,b.getOption("tabSize")),i=b.findPosH(f,-1,"char",!1);if(g&&!/\S/.test(g)&&h%d==0){var j=new m(f.line,a.findColumn(g,h-d,d));j.ch!=f.ch&&(i=j)}b.replaceRange("",i,f,"+delete")}}))},l[k[t+o+"K"]="delLineRight"]=function(a){a.operation((function(){for(var b=a.listSelections(),c=b.length-1;c>=0;c--)a.replaceRange("",b[c].anchor,m(b[c].to().line),"+delete");a.scrollIntoView()}))},l[k[t+o+"U"]="upcaseAtCursor"]=function(a){h(a,(function(a){return a.toUpperCase()}))},l[k[t+o+"L"]="downcaseAtCursor"]=function(a){h(a,(function(a){return a.toLowerCase()}))},l[k[t+o+"Space"]="setSublimeMark"]=function(a){a.state.sublimeMark&&a.state.sublimeMark.clear(),a.state.sublimeMark=a.setBookmark(a.getCursor())},l[k[t+o+"A"]="selectToSublimeMark"]=function(a){var b=a.state.sublimeMark&&a.state.sublimeMark.find();b&&a.setSelection(a.getCursor(),b)},l[k[t+o+"W"]="deleteToSublimeMark"]=function(b){var c=b.state.sublimeMark&&b.state.sublimeMark.find();if(c){var d=b.getCursor(),e=c;if(a.cmpPos(d,e)>0){var f=e;e=d,d=f}b.state.sublimeKilled=b.getRange(d,e),b.replaceRange("",d,e)}},l[k[t+o+"X"]="swapWithSublimeMark"]=function(a){var b=a.state.sublimeMark&&a.state.sublimeMark.find();b&&(a.state.sublimeMark.clear(),a.state.sublimeMark=a.setBookmark(a.getCursor()),a.setCursor(b))},l[k[t+o+"Y"]="sublimeYank"]=function(a){null!=a.state.sublimeKilled&&a.replaceSelection(a.state.sublimeKilled,null,"paste")},k[t+o+"G"]="clearBookmarks",l[k[t+o+"C"]="showInCenter"]=function(a){var b=a.cursorCoords(null,"local");a.scrollTo(null,(b.top+b.bottom)/2-a.getScrollInfo().clientHeight/2)};var u=n?"Ctrl-Shift-":"Ctrl-Alt-";l[k[u+"Up"]="selectLinesUpward"]=function(a){a.operation((function(){for(var b=a.listSelections(),c=0;ca.firstLine()&&a.addSelection(m(d.head.line-1,d.head.ch))}}))},l[k[u+"Down"]="selectLinesDownward"]=function(a){a.operation((function(){for(var b=a.listSelections(),c=0;c0&&c.ch>=e.length)return b.clipPos(m(c.line+1,0));for(var f,g="start",h=c.ch,i=d<0?0:e.length,j=0;h!=i;h+=d,j++){var k=e.charAt(d<0?h-1:h),l="_"!=k&&a.isWordChar(k)?"w":"o";if("w"==l&&k.toUpperCase()==k&&(l="W"),"start"==g)"o"!=l&&(g="in",f=l);else if("in"==g&&f!=l){if("w"==f&&"W"==l&&d<0&&h--,"W"==f&&"w"==l&&d>0){f="w";continue}break}}return m(c.line,h)}function c(a,c){a.extendSelectionsBy((function(d){return a.display.shift||a.doc.extend||d.empty()?b(a.doc,d.head,c):c<0?d.from():d.to()}))}function d(b,c){return b.isReadOnly()?a.Pass:(b.operation((function(){for(var a=b.listSelections().length,d=[],e=-1,f=0;f=0;h--){var i=d[f[h]];if(!(j&&a.cmpPos(i.head,j)>0)){var k=e(b,i.head);j=k.from,b.replaceRange(c(k.word),k.from,k.to)}}}))}function i(b){var c=b.getCursor("from"),d=b.getCursor("to");if(0==a.cmpPos(c,d)){var f=e(b,c);if(!f.word)return;c=f.from,d=f.to}return{from:c,to:d,query:b.getRange(c,d),word:f}}function j(a,b){var c=i(a);if(c){var d=c.query,e=a.getSearchCursor(d,b?c.to:c.from);(b?e.findNext():e.findPrevious())?a.setSelection(e.from(),e.to()):(e=a.getSearchCursor(d,b?m(a.firstLine(),0):a.clipPos(m(a.lastLine()))),(b?e.findNext():e.findPrevious())?a.setSelection(e.from(),e.to()):c.word&&a.setSelection(c.from,c.to))}}var k=a.keyMap.sublime={fallthrough:"default"},l=a.commands,m=a.Pos,n=a.keyMap.default==a.keyMap.macDefault,o=n?"Cmd-":"Ctrl-",p=n?"Ctrl-":"Alt-";l[k[p+"Left"]="goSubwordLeft"]=function(a){c(a,-1)},l[k[p+"Right"]="goSubwordRight"]=function(a){c(a,1)},n&&(k["Cmd-Left"]="goLineStartSmart");var q=n?"Ctrl-Alt-":"Ctrl-";l[k[q+"Up"]="scrollLineUp"]=function(a){var b=a.getScrollInfo();if(!a.somethingSelected()){var c=a.lineAtHeight(b.top+b.clientHeight,"local");a.getCursor().line>=c&&a.execCommand("goLineUp")}a.scrollTo(null,b.top-a.defaultTextHeight())},l[k[q+"Down"]="scrollLineDown"]=function(a){var b=a.getScrollInfo();if(!a.somethingSelected()){var c=a.lineAtHeight(b.top,"local")+1;a.getCursor().line<=c&&a.execCommand("goLineDown")}a.scrollTo(null,b.top+a.defaultTextHeight())},l[k["Shift-"+o+"L"]="splitSelectionByLine"]=function(a){for(var b=a.listSelections(),c=[],d=0;de.line&&g==f.line&&0==f.ch||c.push({anchor:g==e.line?e:m(g,0),head:g==f.line?f:m(g)});a.setSelections(c,0)},k["Shift-Tab"]="indentLess",l[k.Esc="singleSelectionTop"]=function(a){var b=a.listSelections()[0];a.setSelection(b.anchor,b.head,{scroll:!1})},l[k[o+"L"]="selectLine"]=function(a){for(var b=a.listSelections(),c=[],d=0;de?d.push(i,j):d.length&&(d[d.length-1]=j),e=j}b.operation((function(){for(var a=0;ab.lastLine()?b.replaceRange("\n"+g,m(b.lastLine()),null,"+swapLine"):b.replaceRange(g+"\n",m(e,0),null,"+swapLine")}b.setSelections(f),b.scrollIntoView()}))},l[k[s+"Down"]="swapLineDown"]=function(b){if(b.isReadOnly())return a.Pass;for(var c=b.listSelections(),d=[],e=b.lastLine()+1,f=c.length-1;f>=0;f--){var g=c[f],h=g.to().line+1,i=g.from().line;0!=g.to().ch||g.empty()||h--,h=0;a-=2){var c=d[a],e=d[a+1],f=b.getLine(c);c==b.lastLine()?b.replaceRange("",m(c-1),m(c),"+swapLine"):b.replaceRange("",m(c,0),m(c+1,0),"+swapLine"),b.replaceRange(f+"\n",m(e,0),null,"+swapLine")}b.scrollIntoView()}))},l[k[o+"/"]="toggleCommentIndented"]=function(a){a.toggleComment({indent:!0})},l[k[o+"J"]="joinLines"]=function(a){for(var b=a.listSelections(),c=[],d=0;d=0;e--){var f=c[e].head,g=b.getRange({line:f.line,ch:0},f),h=a.countColumn(g,null,b.getOption("tabSize")),i=b.findPosH(f,-1,"char",!1);if(g&&!/\S/.test(g)&&h%d==0){var j=new m(f.line,a.findColumn(g,h-d,d));j.ch!=f.ch&&(i=j)}b.replaceRange("",i,f,"+delete")}}))},l[k[t+o+"K"]="delLineRight"]=function(a){a.operation((function(){for(var b=a.listSelections(),c=b.length-1;c>=0;c--)a.replaceRange("",b[c].anchor,m(b[c].to().line),"+delete");a.scrollIntoView()}))},l[k[t+o+"U"]="upcaseAtCursor"]=function(a){h(a,(function(a){return a.toUpperCase()}))},l[k[t+o+"L"]="downcaseAtCursor"]=function(a){h(a,(function(a){return a.toLowerCase()}))},l[k[t+o+"Space"]="setSublimeMark"]=function(a){a.state.sublimeMark&&a.state.sublimeMark.clear(),a.state.sublimeMark=a.setBookmark(a.getCursor())},l[k[t+o+"A"]="selectToSublimeMark"]=function(a){var b=a.state.sublimeMark&&a.state.sublimeMark.find();b&&a.setSelection(a.getCursor(),b)},l[k[t+o+"W"]="deleteToSublimeMark"]=function(b){var c=b.state.sublimeMark&&b.state.sublimeMark.find();if(c){var d=b.getCursor(),e=c;if(a.cmpPos(d,e)>0){var f=e;e=d,d=f}b.state.sublimeKilled=b.getRange(d,e),b.replaceRange("",d,e)}},l[k[t+o+"X"]="swapWithSublimeMark"]=function(a){var b=a.state.sublimeMark&&a.state.sublimeMark.find();b&&(a.state.sublimeMark.clear(),a.state.sublimeMark=a.setBookmark(a.getCursor()),a.setCursor(b))},l[k[t+o+"Y"]="sublimeYank"]=function(a){null!=a.state.sublimeKilled&&a.replaceSelection(a.state.sublimeKilled,null,"paste")},k[t+o+"G"]="clearBookmarks",l[k[t+o+"C"]="showInCenter"]=function(a){var b=a.cursorCoords(null,"local");a.scrollTo(null,(b.top+b.bottom)/2-a.getScrollInfo().clientHeight/2)};var u=n?"Ctrl-Shift-":"Ctrl-Alt-";l[k[u+"Up"]="selectLinesUpward"]=function(a){a.operation((function(){for(var b=a.listSelections(),c=0;ca.firstLine()&&a.addSelection(m(d.head.line-1,d.head.ch))}}))},l[k[u+"Down"]="selectLinesDownward"]=function(a){a.operation((function(){for(var b=a.listSelections(),c=0;c= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch) + if (identical && stringStartsAfter(cm, cur)) + curType = "both"; + else if (triples.indexOf(ch) >= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch) curType = "skipThree"; else curType = "skip"; @@ -347,6 +349,11 @@ stream.start = stream.pos; } } + + function stringStartsAfter(cm, pos) { + var token = cm.getTokenAt(Pos(pos.line, pos.ch + 1)) + return /\bstring/.test(token.type) && token.start == pos.ch + } }); // CodeMirror, copyright (c) by Marijn Haverbeke and others diff --git a/media/editors/codemirror/lib/addons.min.js b/media/editors/codemirror/lib/addons.min.js index ea15a0a77566c..beaae8d690a1b 100644 --- a/media/editors/codemirror/lib/addons.min.js +++ b/media/editors/codemirror/lib/addons.min.js @@ -1,4 +1,4 @@ -!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";function b(a){var b=a.getWrapperElement();a.state.fullScreenRestore={scrollTop:window.pageYOffset,scrollLeft:window.pageXOffset,width:b.style.width,height:b.style.height},b.style.width="",b.style.height="auto",b.className+=" CodeMirror-fullscreen",document.documentElement.style.overflow="hidden",a.refresh()}function c(a){var b=a.getWrapperElement();b.className=b.className.replace(/\s*CodeMirror-fullscreen\b/,""),document.documentElement.style.overflow="";var c=a.state.fullScreenRestore;b.style.width=c.width,b.style.height=c.height,window.scrollTo(c.scrollLeft,c.scrollTop),a.refresh()}a.defineOption("fullScreen",!1,(function(d,e,f){f==a.Init&&(f=!1),!f!=!e&&(e?b(d):c(d))}))})),(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){function b(a,b,c,d){this.cm=a,this.node=b,this.options=c,this.height=d,this.cleared=!1}function c(a){var b=a.getWrapperElement(),c=window.getComputedStyle?window.getComputedStyle(b):b.currentStyle,d=parseInt(c.height),e=a.state.panels={setHeight:b.style.height,heightLeft:d,panels:0,wrapper:document.createElement("div")};b.parentNode.insertBefore(e.wrapper,b);var f=a.hasFocus();e.wrapper.appendChild(b),f&&a.focus(),a._setSize=a.setSize,null!=d&&(a.setSize=function(b,c){if(null==c)return this._setSize(b,c);if(e.setHeight=c,"number"!=typeof c){var f=/^(\d+\.?\d*)px$/.exec(c);f?c=Number(f[1]):(e.wrapper.style.height=c,c=e.wrapper.offsetHeight,e.wrapper.style.height="")}a._setSize(b,e.heightLeft+=c-d),d=c})}function d(a){var b=a.state.panels;a.state.panels=null;var c=a.getWrapperElement();b.wrapper.parentNode.replaceChild(c,b.wrapper),c.style.height=b.setHeight,a.setSize=a._setSize,a.setSize()}a.defineExtension("addPanel",(function(a,d){d=d||{},this.state.panels||c(this);var e=this.state.panels,f=e.wrapper,g=this.getWrapperElement();d.after instanceof b&&!d.after.cleared?f.insertBefore(a,d.before.node.nextSibling):d.before instanceof b&&!d.before.cleared?f.insertBefore(a,d.before.node):d.replace instanceof b&&!d.replace.cleared?(f.insertBefore(a,d.replace.node),d.replace.clear()):"bottom"==d.position?f.appendChild(a):"before-bottom"==d.position?f.insertBefore(a,g.nextSibling):"after-top"==d.position?f.insertBefore(a,g):f.insertBefore(a,f.firstChild);var h=d&&d.height||a.offsetHeight;return this._setSize(null,e.heightLeft-=h),e.panels++,new b(this,a,d,h)})),b.prototype.clear=function(){if(!this.cleared){this.cleared=!0;var a=this.cm.state.panels;this.cm._setSize(null,a.heightLeft+=this.height),a.wrapper.removeChild(this.node),0==--a.panels&&d(this.cm)}},b.prototype.changed=function(a){var b=null==a?this.node.offsetHeight:a,c=this.cm.state.panels;this.cm._setSize(null,c.height+=b-this.height),this.height=b}})),(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){function b(a,b){return"pairs"==b&&"string"==typeof a?a:"object"==typeof a&&null!=a[b]?a[b]:l[b]}function c(a){return function(b){return h(b,a)}}function d(a){var b=a.state.closeBrackets;if(!b)return null;var c=a.getModeAt(a.getCursor());return c.closeBrackets||b}function e(c){var e=d(c);if(!e||c.getOption("disableInput"))return a.Pass;for(var f=b(e,"pairs"),g=c.listSelections(),h=0;h=0;h--){var k=g[h].head;c.replaceRange("",m(k.line,k.ch-1),m(k.line,k.ch+1),"+delete")}}function f(c){var e=d(c),f=e&&b(e,"explode");if(!f||c.getOption("disableInput"))return a.Pass;for(var g=c.listSelections(),h=0;h0;return{anchor:new m(b.anchor.line,b.anchor.ch+(c?-1:1)),head:new m(b.head.line,b.head.ch+(c?1:-1))}}function h(c,e){var f=d(c);if(!f||c.getOption("disableInput"))return a.Pass;var h=b(f,"pairs"),j=h.indexOf(e);if(j==-1)return a.Pass;for(var l,n=b(f,"triples"),o=h.charAt(j+1)==e,p=c.listSelections(),q=j%2==0,r=0;r1&&n.indexOf(e)>=0&&c.getRange(m(u.line,u.ch-2),u)==e+e&&(u.ch<=2||c.getRange(m(u.line,u.ch-3),m(u.line,u.ch-2))!=e))s="addFour";else if(o){if(a.isWordChar(v)||!k(c,u,e))return a.Pass;s="both"}else{if(!q||c.getLine(u.line).length!=u.ch&&!i(v,h)&&!/\s/.test(v))return a.Pass;s="both"}else s=n.indexOf(e)>=0&&c.getRange(u,m(u.line,u.ch+3))==e+e+e?"skipThree":"skip";if(l){if(l!=s)return a.Pass}else l=s}var w=j%2?h.charAt(j-1):e,x=j%2?e:h.charAt(j+1);c.operation((function(){if("skip"==l)c.execCommand("goCharRight");else if("skipThree"==l)for(var a=0;a<3;a++)c.execCommand("goCharRight");else if("surround"==l){for(var b=c.getSelections(),a=0;a-1&&c%2==1}function j(a,b){var c=a.getRange(m(b.line,b.ch-1),m(b.line,b.ch+1));return 2==c.length?c:null}function k(b,c,d){var e=b.getLine(c.line),f=b.getTokenAt(c);if(/\bstring2?\b/.test(f.type))return!1;var g=new a.StringStream(e.slice(0,c.ch)+d+e.slice(c.ch),4);for(g.pos=g.start=f.start;;){var h=b.getMode().token(g,f.state);if(g.pos>=c.ch+1)return/\bstring2?\b/.test(h);g.start=g.pos}}var l={pairs:"()[]{}''\"\"",triples:"",explode:"[]{}"},m=a.Pos;a.defineOption("autoCloseBrackets",!1,(function(b,c,d){d&&d!=a.Init&&(b.removeKeyMap(o),b.state.closeBrackets=null),c&&(b.state.closeBrackets=c,b.addKeyMap(o))}));for(var n=l.pairs+"`",o={Backspace:e,Enter:f},p=0;pj.ch&&(r=r.slice(0,r.length-k.end+j.ch));var s=r.toLowerCase();if(!r||"string"==k.type&&(k.end!=j.ch||!/[\"\']/.test(k.string.charAt(k.string.length-1))||1==k.string.length)||"tag"==k.type&&"closeTag"==m.type||k.string.indexOf("/")==k.string.length-1||p&&e(p,s)>-1||f(b,r,j,m,!0))return a.Pass;var t=q&&e(q,s)>-1;d[i]={indent:t,text:">"+(t?"\n\n":"")+"",newPos:t?a.Pos(j.line+1,0):a.Pos(j.line,j.ch+1)}}for(var i=c.length-1;i>=0;i--){var u=d[i];b.replaceRange(u.text,c[i].head,c[i].anchor,"+insert");var v=b.listSelections().slice(0);v[i]={head:u.newPos,anchor:u.newPos},b.setSelections(v),u.indent&&(b.indentLine(u.newPos.line,null,!0),b.indentLine(u.newPos.line+1,null,!0))}}function c(b,c){for(var d=b.listSelections(),e=[],g=c?"/":""!=b.getLine(i.line).charAt(j.end)&&(m+=">"),e[h]=m}b.replaceSelections(e),d=b.listSelections();for(var h=0;h'"]=function(a){return b(a)}),c.addKeyMap(g)}}));var g=["area","base","br","col","command","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"],h=["applet","blockquote","body","button","div","dl","fieldset","form","frameset","h1","h2","h3","h4","h5","h6","head","html","iframe","layer","legend","object","ol","p","select","table","ul"];a.commands.closeTag=function(a){return c(a)}})),(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){function b(a,b,d,e){var f=a.getLineHandle(b.line),i=b.ch-1,j=i>=0&&h[f.text.charAt(i)]||h[f.text.charAt(++i)];if(!j)return null;var k=">"==j.charAt(1)?1:-1;if(d&&k>0!=(i==b.ch))return null;var l=a.getTokenTypeAt(g(b.line,i+1)),m=c(a,g(b.line,i+(k>0?1:0)),k,l||null,e);return null==m?null:{from:g(b.line,i),to:m&&m.pos,match:m&&m.ch==j.charAt(0),forward:k>0}}function c(a,b,c,d,e){for(var f=e&&e.maxScanLineLength||1e4,i=e&&e.maxScanLines||1e3,j=[],k=e&&e.bracketRegex?e.bracketRegex:/[(){}[\]]/,l=c>0?Math.min(b.line+i,a.lastLine()+1):Math.max(a.firstLine()-1,b.line-i),m=b.line;m!=l;m+=c){var n=a.getLine(m);if(n){var o=c>0?0:n.length-1,p=c>0?n.length:-1;if(!(n.length>f))for(m==b.line&&(o=b.ch-(c<0?1:0));o!=p;o+=c){var q=n.charAt(o);if(k.test(q)&&(void 0===d||a.getTokenTypeAt(g(m,o+1))==d)){var r=h[q];if(">"==r.charAt(1)==c>0)j.push(q);else{if(!j.length)return{pos:g(m,o),ch:q};j.pop()}}}}}return m-c!=(c>0?a.lastLine():a.firstLine())&&null}function d(a,c,d){for(var e=a.state.matchBrackets.maxHighlightLineLength||1e3,h=[],i=a.listSelections(),j=0;j",")":"(<","[":"]>","]":"[<","{":"}>","}":"{<"},i=null;a.defineOption("matchBrackets",!1,(function(b,c,d){d&&d!=a.Init&&(b.off("cursorActivity",e),i&&(i(),i=null)),c&&(b.state.matchBrackets="object"==typeof c?c:{},b.on("cursorActivity",e))})),a.defineExtension("matchBrackets",(function(){d(this,!0)})),a.defineExtension("findMatchingBracket",(function(a,c,d){return b(this,a,c,d)})),a.defineExtension("scanForBracket",(function(a,b,d,e){return c(this,a,b,d,e)}))})),(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror"),require("../fold/xml-fold")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","../fold/xml-fold"],a):a(CodeMirror)})((function(a){"use strict";function b(a){a.state.tagHit&&a.state.tagHit.clear(),a.state.tagOther&&a.state.tagOther.clear(),a.state.tagHit=a.state.tagOther=null}function c(c){c.state.failedTagMatch=!1,c.operation((function(){if(b(c),!c.somethingSelected()){var d=c.getCursor(),e=c.getViewport();e.from=Math.min(e.from,d.line),e.to=Math.max(d.line+1,e.to);var f=a.findMatchingTag(c,d,e);if(f){if(c.state.matchBothTags){var g="open"==f.at?f.open:f.close;g&&(c.state.tagHit=c.markText(g.from,g.to,{className:"CodeMirror-matchingtag"}))}var h="close"==f.at?f.open:f.close;h?c.state.tagOther=c.markText(h.from,h.to,{className:"CodeMirror-matchingtag"}):c.state.failedTagMatch=!0}}}))}function d(a){a.state.failedTagMatch&&c(a)}a.defineOption("matchTags",!1,(function(e,f,g){g&&g!=a.Init&&(e.off("cursorActivity",c),e.off("viewportChange",d),b(e)),f&&(e.state.matchBothTags="object"==typeof f&&f.bothTags,e.on("cursorActivity",c),e.on("viewportChange",d),c(e))})),a.commands.toMatchingTag=function(b){var c=a.findMatchingTag(b,b.getCursor());if(c){var d="close"==c.at?c.open:c.close;d&&b.extendSelection(d.to,d.from)}}})),(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";a.registerHelper("fold","brace",(function(b,c){function d(d){for(var h=c.ch,i=0;;){var j=h<=0?-1:g.lastIndexOf(d,h-1);if(j!=-1){if(1==i&&jb.lastLine())return null;var d=b.getTokenAt(a.Pos(c,1));if(/\S/.test(d.string)||(d=b.getTokenAt(a.Pos(c,d.end+1))),"keyword"!=d.type||"import"!=d.string)return null;for(var e=c,f=Math.min(b.lastLine(),c+10);e<=f;++e){var g=b.getLine(e),h=g.indexOf(";");if(h!=-1)return{startCh:d.end,end:a.Pos(e,h)}}}var e,f=c.line,g=d(f);if(!g||d(f-1)||(e=d(f-2))&&e.end.line==f-1)return null;for(var h=g.end;;){var i=d(h.line+1);if(null==i)break;h=i.end}return{from:b.clipPos(a.Pos(f,g.startCh+1)),to:h}})),a.registerHelper("fold","include",(function(b,c){function d(c){if(cb.lastLine())return null;var d=b.getTokenAt(a.Pos(c,1));return/\S/.test(d.string)||(d=b.getTokenAt(a.Pos(c,d.end+1))),"meta"==d.type&&"#include"==d.string.slice(0,8)?d.start+8:void 0}var e=c.line,f=d(e);if(null==f||null!=d(e-1))return null;for(var g=e;;){var h=d(g+1);if(null==h)break;++g}return{from:a.Pos(e,f+1),to:b.clipPos(a.Pos(g))}}))})),(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";function b(b,e,f,g){function h(a){var c=i(b,e);if(!c||c.to.line-c.from.lineb.firstLine();)e=a.Pos(e.line-1,0),k=h(!1);if(k&&!k.cleared&&"unfold"!==g){var l=c(b,f);a.on(l,"mousedown",(function(b){m.clear(),a.e_preventDefault(b)}));var m=b.markText(k.from,k.to,{replacedWith:l,clearOnEnter:d(b,f,"clearOnEnter"),__isFold:!0});m.on("clear",(function(c,d){a.signal(b,"unfold",b,c,d)})),a.signal(b,"fold",b,k.from,k.to)}}function c(a,b){var c=d(a,b,"widget");if("string"==typeof c){var e=document.createTextNode(c);c=document.createElement("span"),c.appendChild(e),c.className="CodeMirror-foldmarker"}return c}function d(a,b,c){if(b&&void 0!==b[c])return b[c];var d=a.options.foldOptions;return d&&void 0!==d[c]?d[c]:e[c]}a.newFoldFunction=function(a,c){return function(d,e){b(d,e,{rangeFinder:a,widget:c})}},a.defineExtension("foldCode",(function(a,c,d){b(this,a,c,d)})),a.defineExtension("isFolded",(function(a){for(var b=this.findMarksAt(a),c=0;c=h&&(c=e(f.indicatorOpen))}a.setGutterMarker(b,f.gutter,c),++g}))}function g(a){var b=a.getViewport(),c=a.state.foldGutter;c&&(a.operation((function(){f(a,b.from,b.to)})),c.from=b.from,c.to=b.to)}function h(a,b,c){var e=a.state.foldGutter;if(e){var f=e.options;if(c==f.gutter){var g=d(a,b);g?g.clear():a.foldCode(l(b,0),f.rangeFinder)}}}function i(a){var b=a.state.foldGutter;if(b){var c=b.options;b.from=b.to=0,clearTimeout(b.changeUpdate),b.changeUpdate=setTimeout((function(){g(a)}),c.foldOnChangeTimeSpan||600)}}function j(a){var b=a.state.foldGutter;if(b){var c=b.options;clearTimeout(b.changeUpdate),b.changeUpdate=setTimeout((function(){var c=a.getViewport();b.from==b.to||c.from-b.to>20||b.from-c.to>20?g(a):a.operation((function(){c.fromb.to&&(f(a,b.to,c.to),b.to=c.to)}))}),c.updateViewportTimeSpan||400)}}function k(a,b){var c=a.state.foldGutter;if(c){var d=b.line;d>=c.from&&d=a.max))return a.ch=0,a.text=a.cm.getLine(++a.line),!0}function f(a){if(!(a.line<=a.min))return a.text=a.cm.getLine(--a.line),a.ch=a.text.length,!0}function g(a){for(;;){var b=a.text.indexOf(">",a.ch);if(b==-1){if(e(a))continue;return}{if(d(a,b+1)){var c=a.text.lastIndexOf("/",b),f=c>-1&&!/\S/.test(a.text.slice(c+1,b));return a.ch=b+1,f?"selfClose":"regular"}a.ch=b+1}}}function h(a){for(;;){var b=a.ch?a.text.lastIndexOf("<",a.ch-1):-1;if(b==-1){if(f(a))continue;return}if(d(a,b+1)){p.lastIndex=b,a.ch=b;var c=p.exec(a.text);if(c&&c.index==b)return c}else a.ch=b}}function i(a){for(;;){p.lastIndex=a.ch;var b=p.exec(a.text);if(!b){if(e(a))continue;return}{if(d(a,b.index+1))return a.ch=b.index+b[0].length,b;a.ch=b.index+1}}}function j(a){for(;;){var b=a.ch?a.text.lastIndexOf(">",a.ch-1):-1;if(b==-1){if(f(a))continue;return}{if(d(a,b+1)){var c=a.text.lastIndexOf("/",b),e=c>-1&&!/\S/.test(a.text.slice(c+1,b));return a.ch=b+1,e?"selfClose":"regular"}a.ch=b}}}function k(a,b){for(var c=[];;){var d,e=i(a),f=a.line,h=a.ch-(e?e[0].length:0);if(!e||!(d=g(a)))return;if("selfClose"!=d)if(e[1]){for(var j=c.length-1;j>=0;--j)if(c[j]==e[2]){c.length=j;break}if(j<0&&(!b||b==e[2]))return{tag:e[2],from:m(f,h),to:m(a.line,a.ch)}}else c.push(e[2])}}function l(a,b){for(var c=[];;){var d=j(a);if(!d)return;if("selfClose"!=d){var e=a.line,f=a.ch,g=h(a);if(!g)return;if(g[1])c.push(g[2]);else{for(var i=c.length-1;i>=0;--i)if(c[i]==g[2]){c.length=i;break}if(i<0&&(!b||b==g[2]))return{tag:g[2],from:m(a.line,a.ch),to:m(e,f)}}}else h(a)}}var m=a.Pos,n="A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",o=n+"-:.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040",p=new RegExp("<(/?)(["+n+"]["+o+"]*)","g");a.registerHelper("fold","xml",(function(a,b){for(var d=new c(a,b.line,0);;){var e,f=i(d);if(!f||d.line!=b.line||!(e=g(d)))return;if(!f[1]&&"selfClose"!=e){var h=m(d.line,d.ch),j=k(d,f[2]);return j&&{from:h,to:j.from}}}})),a.findMatchingTag=function(a,d,e){var f=new c(a,d.line,d.ch,e);if(f.text.indexOf(">")!=-1||f.text.indexOf("<")!=-1){var i=g(f),j=i&&m(f.line,f.ch),n=i&&h(f);if(i&&n&&!(b(f,d)>0)){var o={from:m(f.line,f.ch),to:j,tag:n[2]};return"selfClose"==i?{open:o,close:null,at:"open"}:n[1]?{open:l(f,n[2]),close:o,at:"close"}:(f=new c(a,j.line,j.ch,e),{open:o,close:k(f,n[2]),at:"open"})}}},a.findEnclosingTag=function(a,b,d){for(var e=new c(a,b.line,b.ch,d);;){var f=l(e);if(!f)break;var g=new c(a,b.line,b.ch,d),h=k(g,f.tag);if(h)return{open:f,close:h}}},a.scanForClosingTag=function(a,b,d,e){var f=new c(a,b.line,b.ch,e?{from:0,to:e}:null);return k(f,d)}})),(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror"),"cjs"):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],(function(b){a(b,"amd")})):a(CodeMirror,"plain")})((function(a,b){function c(a,b){var c=b;return function(){0==--c&&a()}}function d(b,d){var e=a.modes[b].dependencies;if(!e)return d();for(var f=[],g=0;g-1?e+b.length:e}var f=b.exec(c?a.slice(c):a);return f?f.index+c+(d?f[0].length:0):-1}var d=Array.prototype.slice.call(arguments,1);return{startState:function(){return{outer:a.startState(b),innerActive:null,inner:null}},copyState:function(c){return{outer:a.copyState(b,c.outer),innerActive:c.innerActive,inner:c.innerActive&&a.copyState(c.innerActive.mode,c.inner)}},token:function(e,f){if(f.innerActive){var g=f.innerActive,h=e.string;if(!g.close&&e.sol())return f.innerActive=f.inner=null,this.token(e,f);var i=g.close?c(h,g.close,e.pos,g.parseDelimiters):-1;if(i==e.pos&&!g.parseDelimiters)return e.match(g.close),f.innerActive=f.inner=null,g.delimStyle&&g.delimStyle+" "+g.delimStyle+"-close";i>-1&&(e.string=h.slice(0,i));var j=g.mode.token(e,f.inner);return i>-1&&(e.string=h),i==e.pos&&g.parseDelimiters&&(f.innerActive=f.inner=null),g.innerStyle&&(j=j?j+" "+g.innerStyle:g.innerStyle),j}for(var k=1/0,h=e.string,l=0;lh)return c.charCoords(a,"local")[b?"top":"bottom"];var d=c.heightAtLine(j,"local");return d+(b?0:j.height)}a!==!1&&this.computeScale();var c=this.cm,d=this.hScale,e=document.createDocumentFragment(),f=this.annotations,g=c.getOption("lineWrapping"),h=g&&1.5*c.defaultTextHeight(),i=null,j=null;if(c.display.barWidth)for(var k,l=0;lo+.9));)m=f[++l],o=b(m.to,!1)*d;if(o!=n){var p=Math.max(o-n,3),q=e.appendChild(document.createElement("div"));q.style.cssText="position: absolute; right: 0px; width: "+Math.max(c.display.barWidth-1,2)+"px; top: "+(n+this.buttonHeight)+"px; height: "+p+"px",q.className=this.options.className,m.id&&q.setAttribute("annotation-id",m.id)}}this.div.textContent="",this.div.appendChild(e)},b.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("change",this.changeHandler),this.div.parentNode.removeChild(this.div)}})),(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";function b(b,c,d){function e(b){var c=a.wheelEventPixels(b)["horizontal"==f.orientation?"x":"y"],d=f.pos;f.moveTo(f.pos+c),f.pos!=d&&a.e_preventDefault(b)}this.orientation=c,this.scroll=d,this.screen=this.total=this.size=1,this.pos=0,this.node=document.createElement("div"),this.node.className=b+"-"+c,this.inner=this.node.appendChild(document.createElement("div"));var f=this;a.on(this.inner,"mousedown",(function(b){function c(){a.off(document,"mousemove",d),a.off(document,"mouseup",c)}function d(a){return 1!=a.which?c():void f.moveTo(h+(a[e]-g)*(f.total/f.size))}if(1==b.which){a.e_preventDefault(b);var e="horizontal"==f.orientation?"pageX":"pageY",g=b[e],h=f.pos;a.on(document,"mousemove",d),a.on(document,"mouseup",c)}})),a.on(this.node,"click",(function(b){a.e_preventDefault(b);var c,d=f.inner.getBoundingClientRect();c="horizontal"==f.orientation?b.clientXd.right?1:0:b.clientYd.bottom?1:0,f.moveTo(f.pos+c*f.screen)})),a.on(this.node,"mousewheel",e),a.on(this.node,"DOMMouseScroll",e)}function c(a,c,d){this.addClass=a,this.horiz=new b(a,"horizontal",d),c(this.horiz.node),this.vert=new b(a,"vertical",d),c(this.vert.node),this.width=null}b.prototype.setPos=function(a,b){return a<0&&(a=0),a>this.total-this.screen&&(a=this.total-this.screen),!(!b&&a==this.pos)&&(this.pos=a,this.inner.style["horizontal"==this.orientation?"left":"top"]=a*(this.size/this.total)+"px",!0)},b.prototype.moveTo=function(a){this.setPos(a)&&this.scroll(a,this.orientation)};var d=10;b.prototype.update=function(a,b,c){var e=this.screen!=b||this.total!=a||this.size!=c;e&&(this.screen=b,this.total=a,this.size=c);var f=this.screen*(this.size/this.total);fa.clientWidth+1,e=a.scrollHeight>a.clientHeight+1;return this.vert.node.style.display=e?"block":"none",this.horiz.node.style.display=d?"block":"none",e&&(this.vert.update(a.scrollHeight,a.clientHeight,a.viewHeight-(d?c:0)),this.vert.node.style.bottom=d?c+"px":"0"), -d&&(this.horiz.update(a.scrollWidth,a.clientWidth,a.viewWidth-(e?c:0)-a.barLeft),this.horiz.node.style.right=e?c+"px":"0",this.horiz.node.style.left=a.barLeft+"px"),{right:e?c:0,bottom:d?c:0}},c.prototype.setScrollTop=function(a){this.vert.setPos(a)},c.prototype.setScrollLeft=function(a){this.horiz.setPos(a)},c.prototype.clear=function(){var a=this.horiz.node.parentNode;a.removeChild(this.horiz.node),a.removeChild(this.vert.node)},a.scrollbarModel.simple=function(a,b){return new c("CodeMirror-simplescroll",a,b)},a.scrollbarModel.overlay=function(a,b){return new c("CodeMirror-overlayscroll",a,b)}})),(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror"),require("./searchcursor"),require("../scroll/annotatescrollbar")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","./searchcursor","../scroll/annotatescrollbar"],a):a(CodeMirror)})((function(a){"use strict";function b(a,b,c,d){this.cm=a,this.options=d;var e={listenForChanges:!1};for(var f in d)e[f]=d[f];e.className||(e.className="CodeMirror-search-match"),this.annotation=a.annotateScrollbar(e),this.query=b,this.caseFold=c,this.gap={from:a.firstLine(),to:a.lastLine()+1},this.matches=[],this.update=null,this.findMatches(),this.annotation.update(this.matches);var g=this;a.on("change",this.changeHandler=function(a,b){g.onChange(b)})}function c(a,b,c){return a<=b?a:Math.max(b,a+c)}a.defineExtension("showMatchesOnScrollbar",(function(a,c,d){return"string"==typeof d&&(d={className:d}),d||(d={}),new b(this,a,c,d)}));var d=1e3;b.prototype.findMatches=function(){if(this.gap){for(var b=0;b=this.gap.to)break;c.to.line>=this.gap.from&&this.matches.splice(b--,1)}for(var e=this.cm.getSearchCursor(this.query,a.Pos(this.gap.from,0),this.caseFold),f=this.options&&this.options.maxMatches||d;e.findNext();){var c={from:e.from(),to:e.to()};if(c.from.line>=this.gap.to)break;if(this.matches.splice(b++,0,c),this.matches.length>f)break}this.gap=null}},b.prototype.onChange=function(b){var d=b.from.line,e=a.changeEnd(b).line,f=e-b.to.line;if(this.gap?(this.gap.from=Math.min(c(this.gap.from,d,f),b.from.line),this.gap.to=Math.max(c(this.gap.to,d,f),b.from.line)):this.gap={from:b.from.line,to:e+1},f)for(var g=0;g=b.options.minChars&&f(a,m,!1,b.options.style)}}))}function i(a,b,c){var d=a.getRange(b,c);if(null!==d.match(/^\w+$/)){if(b.ch>0){var e={line:b.line,ch:b.ch-1},f=a.getRange(e,b);if(null===f.match(/\W/))return!1}if(c.ch-1)return k=c(i,j,k),{from:d(f.line,k),to:d(f.line,k+g.length)}}else{var i=a.getLine(f.line).slice(f.ch),j=h(i),k=j.indexOf(b);if(k>-1)return k=c(i,j,k)+f.ch,{from:d(f.line,k),to:d(f.line,k+g.length)}}}:this.matches=function(){};else{var j=g.split("\n");this.matches=function(b,c){var e=i.length-1;if(b){if(c.line-(i.length-1)=1;--k,--g)if(i[k]!=h(a.getLine(g)))return;var l=a.getLine(g),m=l.length-j[0].length;if(h(l.slice(m))!=i[0])return;return{from:d(g,m),to:f}}if(!(c.line+(i.length-1)>a.lastLine())){var l=a.getLine(c.line),m=l.length-j[0].length;if(h(l.slice(m))==i[0]){for(var n=d(c.line,m),g=c.line+1,k=1;kc))return d;--d}}}var d=a.Pos;b.prototype={findNext:function(){return this.find(!1)},findPrevious:function(){return this.find(!0)},find:function(a){function b(a){var b=d(a,0);return c.pos={from:b,to:b},c.atOccurrence=!1,!1}for(var c=this,e=this.doc.clipPos(a?this.pos.from:this.pos.to);;){if(this.pos=this.matches(a,e))return this.atOccurrence=!0,this.pos.match||!0;if(a){if(!e.line)return b(0);e=d(e.line-1,this.doc.getLine(e.line-1).length)}else{var f=this.doc.lineCount();if(e.line==f-1)return b(f);e=d(e.line+1,0)}}},from:function(){if(this.atOccurrence)return this.pos.from},to:function(){if(this.atOccurrence)return this.pos.to},replace:function(b,c){if(this.atOccurrence){var e=a.splitLines(b);this.doc.replaceRange(e,this.pos.from,this.pos.to,c),this.pos.to=d(this.pos.from.line+e.length-1,e[e.length-1].length+(1==e.length?this.pos.from.ch:0))}}},a.defineExtension("getSearchCursor",(function(a,c,d){return new b(this.doc,a,c,d)})),a.defineDocExtension("getSearchCursor",(function(a,c,d){return new b(this,a,c,d)})),a.defineExtension("selectMatches",(function(b,c){for(var d=[],e=this.getSearchCursor(b,this.getCursor("from"),c);e.findNext()&&!(a.cmpPos(e.to(),this.getCursor("to"))>0);)d.push({anchor:e.from(),head:e.to()});d.length&&this.setSelections(d,0)}))})),(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";function b(a){for(var b=0;b",type:"keyToKey",toKeys:"h"},{keys:"",type:"keyToKey",toKeys:"l"},{keys:"",type:"keyToKey",toKeys:"k"},{keys:"",type:"keyToKey",toKeys:"j"},{keys:"",type:"keyToKey",toKeys:"l"},{keys:"",type:"keyToKey",toKeys:"h",context:"normal"},{keys:"",type:"keyToKey",toKeys:"W"},{keys:"",type:"keyToKey",toKeys:"B",context:"normal"},{keys:"",type:"keyToKey",toKeys:"w"},{keys:"",type:"keyToKey",toKeys:"b",context:"normal"},{keys:"",type:"keyToKey",toKeys:"j"},{keys:"",type:"keyToKey",toKeys:"k"},{keys:"",type:"keyToKey",toKeys:""},{keys:"",type:"keyToKey",toKeys:""},{keys:"",type:"keyToKey",toKeys:"",context:"insert"},{keys:"",type:"keyToKey",toKeys:"",context:"insert"},{keys:"s",type:"keyToKey",toKeys:"cl",context:"normal"},{keys:"s",type:"keyToKey",toKeys:"c",context:"visual"},{keys:"S",type:"keyToKey",toKeys:"cc",context:"normal"},{keys:"S",type:"keyToKey",toKeys:"VdO",context:"visual"},{keys:"",type:"keyToKey",toKeys:"0"},{keys:"",type:"keyToKey",toKeys:"$"},{keys:"",type:"keyToKey",toKeys:""},{keys:"",type:"keyToKey",toKeys:""},{keys:"",type:"keyToKey",toKeys:"j^",context:"normal"},{keys:"",type:"action",action:"toggleOverwrite",context:"insert"},{keys:"H",type:"motion",motion:"moveToTopLine",motionArgs:{linewise:!0,toJumplist:!0}},{keys:"M",type:"motion",motion:"moveToMiddleLine",motionArgs:{linewise:!0,toJumplist:!0}},{keys:"L",type:"motion",motion:"moveToBottomLine",motionArgs:{linewise:!0,toJumplist:!0}},{keys:"h",type:"motion",motion:"moveByCharacters",motionArgs:{forward:!1}},{keys:"l",type:"motion",motion:"moveByCharacters",motionArgs:{forward:!0}},{keys:"j",type:"motion",motion:"moveByLines",motionArgs:{forward:!0,linewise:!0}},{keys:"k",type:"motion",motion:"moveByLines",motionArgs:{forward:!1,linewise:!0}},{keys:"gj",type:"motion",motion:"moveByDisplayLines",motionArgs:{forward:!0}},{keys:"gk",type:"motion",motion:"moveByDisplayLines",motionArgs:{forward:!1}},{keys:"w",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!1}},{keys:"W",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!1,bigWord:!0}},{keys:"e",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!0,inclusive:!0}},{keys:"E",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!0,bigWord:!0,inclusive:!0}},{keys:"b",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!1}},{keys:"B",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!1,bigWord:!0}},{keys:"ge",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!0,inclusive:!0}},{keys:"gE",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!0,bigWord:!0,inclusive:!0}},{keys:"{",type:"motion",motion:"moveByParagraph",motionArgs:{forward:!1,toJumplist:!0}},{keys:"}",type:"motion",motion:"moveByParagraph",motionArgs:{forward:!0,toJumplist:!0}},{keys:"",type:"motion",motion:"moveByPage",motionArgs:{forward:!0}},{keys:"",type:"motion",motion:"moveByPage",motionArgs:{forward:!1}},{keys:"",type:"motion",motion:"moveByScroll",motionArgs:{forward:!0,explicitRepeat:!0}},{keys:"",type:"motion",motion:"moveByScroll",motionArgs:{forward:!1,explicitRepeat:!0}},{keys:"gg",type:"motion",motion:"moveToLineOrEdgeOfDocument",motionArgs:{forward:!1,explicitRepeat:!0,linewise:!0,toJumplist:!0}},{keys:"G",type:"motion",motion:"moveToLineOrEdgeOfDocument",motionArgs:{forward:!0,explicitRepeat:!0,linewise:!0,toJumplist:!0}},{keys:"0",type:"motion",motion:"moveToStartOfLine"},{keys:"^",type:"motion",motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:"+",type:"motion",motion:"moveByLines",motionArgs:{forward:!0,toFirstChar:!0}},{keys:"-",type:"motion",motion:"moveByLines",motionArgs:{forward:!1,toFirstChar:!0}},{keys:"_",type:"motion",motion:"moveByLines",motionArgs:{forward:!0,toFirstChar:!0,repeatOffset:-1}},{keys:"$",type:"motion",motion:"moveToEol",motionArgs:{inclusive:!0}},{keys:"%",type:"motion",motion:"moveToMatchedSymbol",motionArgs:{inclusive:!0,toJumplist:!0}},{keys:"f",type:"motion",motion:"moveToCharacter",motionArgs:{forward:!0,inclusive:!0}},{keys:"F",type:"motion",motion:"moveToCharacter",motionArgs:{forward:!1}},{keys:"t",type:"motion",motion:"moveTillCharacter",motionArgs:{forward:!0,inclusive:!0}},{keys:"T",type:"motion",motion:"moveTillCharacter",motionArgs:{forward:!1}},{keys:";",type:"motion",motion:"repeatLastCharacterSearch",motionArgs:{forward:!0}},{keys:",",type:"motion",motion:"repeatLastCharacterSearch",motionArgs:{forward:!1}},{keys:"'",type:"motion",motion:"goToMark",motionArgs:{toJumplist:!0,linewise:!0}},{keys:"`",type:"motion",motion:"goToMark",motionArgs:{toJumplist:!0}},{keys:"]`",type:"motion",motion:"jumpToMark",motionArgs:{forward:!0}},{keys:"[`",type:"motion",motion:"jumpToMark",motionArgs:{forward:!1}},{keys:"]'",type:"motion",motion:"jumpToMark",motionArgs:{forward:!0,linewise:!0}},{keys:"['",type:"motion",motion:"jumpToMark",motionArgs:{forward:!1,linewise:!0}},{keys:"]p",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!0,isEdit:!0,matchIndent:!0}},{keys:"[p",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!1,isEdit:!0,matchIndent:!0}},{keys:"]",type:"motion",motion:"moveToSymbol",motionArgs:{forward:!0,toJumplist:!0}},{keys:"[",type:"motion",motion:"moveToSymbol",motionArgs:{forward:!1,toJumplist:!0}},{keys:"|",type:"motion",motion:"moveToColumn"},{keys:"o",type:"motion",motion:"moveToOtherHighlightedEnd",context:"visual"},{keys:"O",type:"motion",motion:"moveToOtherHighlightedEnd",motionArgs:{sameLine:!0},context:"visual"},{keys:"d",type:"operator",operator:"delete"},{keys:"y",type:"operator",operator:"yank"},{keys:"c",type:"operator",operator:"change"},{keys:">",type:"operator",operator:"indent",operatorArgs:{indentRight:!0}},{keys:"<",type:"operator",operator:"indent",operatorArgs:{indentRight:!1}},{keys:"g~",type:"operator",operator:"changeCase"},{keys:"gu",type:"operator",operator:"changeCase",operatorArgs:{toLower:!0},isEdit:!0},{keys:"gU",type:"operator",operator:"changeCase",operatorArgs:{toLower:!1},isEdit:!0},{keys:"n",type:"motion",motion:"findNext",motionArgs:{forward:!0,toJumplist:!0}},{keys:"N",type:"motion",motion:"findNext",motionArgs:{forward:!1,toJumplist:!0}},{keys:"x",type:"operatorMotion",operator:"delete",motion:"moveByCharacters",motionArgs:{forward:!0},operatorMotionArgs:{visualLine:!1}},{keys:"X",type:"operatorMotion",operator:"delete",motion:"moveByCharacters",motionArgs:{forward:!1},operatorMotionArgs:{visualLine:!0}},{keys:"D",type:"operatorMotion",operator:"delete",motion:"moveToEol",motionArgs:{inclusive:!0},context:"normal"},{keys:"D",type:"operator",operator:"delete",operatorArgs:{linewise:!0},context:"visual"},{keys:"Y",type:"operatorMotion",operator:"yank",motion:"moveToEol",motionArgs:{inclusive:!0},context:"normal"},{keys:"Y",type:"operator",operator:"yank",operatorArgs:{linewise:!0},context:"visual"},{keys:"C",type:"operatorMotion",operator:"change",motion:"moveToEol",motionArgs:{inclusive:!0},context:"normal"},{keys:"C",type:"operator",operator:"change",operatorArgs:{linewise:!0},context:"visual"},{keys:"~",type:"operatorMotion",operator:"changeCase",motion:"moveByCharacters",motionArgs:{forward:!0},operatorArgs:{shouldMoveCursor:!0},context:"normal"},{keys:"~",type:"operator",operator:"changeCase",context:"visual"},{keys:"",type:"operatorMotion",operator:"delete",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!1},context:"insert"},{keys:"",type:"action",action:"jumpListWalk",actionArgs:{forward:!0}},{keys:"",type:"action",action:"jumpListWalk",actionArgs:{forward:!1}},{keys:"",type:"action",action:"scroll",actionArgs:{forward:!0,linewise:!0}},{keys:"",type:"action",action:"scroll",actionArgs:{forward:!1,linewise:!0}},{keys:"a",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"charAfter"},context:"normal"},{keys:"A",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"eol"},context:"normal"},{keys:"A",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"endOfSelectedArea"},context:"visual"},{keys:"i",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"inplace"},context:"normal"},{keys:"I",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"firstNonBlank"},context:"normal"},{keys:"I",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"startOfSelectedArea"},context:"visual"},{keys:"o",type:"action",action:"newLineAndEnterInsertMode",isEdit:!0,interlaceInsertRepeat:!0,actionArgs:{after:!0},context:"normal"},{keys:"O",type:"action",action:"newLineAndEnterInsertMode",isEdit:!0,interlaceInsertRepeat:!0,actionArgs:{after:!1},context:"normal"},{keys:"v",type:"action",action:"toggleVisualMode"},{keys:"V",type:"action",action:"toggleVisualMode",actionArgs:{linewise:!0}},{keys:"",type:"action",action:"toggleVisualMode",actionArgs:{blockwise:!0}},{keys:"",type:"action",action:"toggleVisualMode",actionArgs:{blockwise:!0}},{keys:"gv",type:"action",action:"reselectLastSelection"},{keys:"J",type:"action",action:"joinLines",isEdit:!0},{keys:"p",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!0,isEdit:!0}},{keys:"P",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!1,isEdit:!0}},{keys:"r",type:"action",action:"replace",isEdit:!0},{keys:"@",type:"action",action:"replayMacro"},{keys:"q",type:"action",action:"enterMacroRecordMode"},{keys:"R",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{replace:!0}},{keys:"u",type:"action",action:"undo",context:"normal"},{keys:"u",type:"operator",operator:"changeCase",operatorArgs:{toLower:!0},context:"visual",isEdit:!0},{keys:"U",type:"operator",operator:"changeCase",operatorArgs:{toLower:!1},context:"visual",isEdit:!0},{keys:"",type:"action",action:"redo"},{keys:"m",type:"action",action:"setMark"},{keys:'"',type:"action",action:"setRegister"},{keys:"zz",type:"action",action:"scrollToCursor",actionArgs:{position:"center"}},{keys:"z.",type:"action",action:"scrollToCursor",actionArgs:{position:"center"},motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:"zt",type:"action",action:"scrollToCursor",actionArgs:{position:"top"}},{keys:"z",type:"action",action:"scrollToCursor",actionArgs:{position:"top"},motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:"z-",type:"action",action:"scrollToCursor",actionArgs:{position:"bottom"}},{keys:"zb",type:"action",action:"scrollToCursor",actionArgs:{position:"bottom"},motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:".",type:"action",action:"repeatLastEdit"},{keys:"",type:"action",action:"incrementNumberToken",isEdit:!0,actionArgs:{increase:!0,backtrack:!1}},{keys:"",type:"action",action:"incrementNumberToken",isEdit:!0,actionArgs:{increase:!1,backtrack:!1}},{keys:"a",type:"motion",motion:"textObjectManipulation"},{keys:"i",type:"motion",motion:"textObjectManipulation",motionArgs:{textObjectInner:!0}},{keys:"/",type:"search",searchArgs:{forward:!0,querySrc:"prompt",toJumplist:!0}},{keys:"?",type:"search",searchArgs:{forward:!1,querySrc:"prompt",toJumplist:!0}},{keys:"*",type:"search",searchArgs:{forward:!0,querySrc:"wordUnderCursor",wholeWordOnly:!0,toJumplist:!0}},{keys:"#",type:"search",searchArgs:{forward:!1,querySrc:"wordUnderCursor",wholeWordOnly:!0,toJumplist:!0}},{keys:"g*",type:"search",searchArgs:{forward:!0,querySrc:"wordUnderCursor",toJumplist:!0}},{keys:"g#",type:"search",searchArgs:{forward:!1,querySrc:"wordUnderCursor",toJumplist:!0}},{keys:":",type:"ex"}],c=[{name:"colorscheme",shortName:"colo"},{name:"map"},{name:"imap",shortName:"im"},{name:"nmap",shortName:"nm"},{name:"vmap",shortName:"vm"},{name:"unmap"},{name:"write",shortName:"w"},{name:"undo",shortName:"u"},{name:"redo",shortName:"red"},{name:"set",shortName:"se"},{name:"set",shortName:"se"},{name:"setlocal",shortName:"setl"},{name:"setglobal",shortName:"setg"},{name:"sort",shortName:"sor"},{name:"substitute",shortName:"s",possiblyAsync:!0},{name:"nohlsearch",shortName:"noh"},{name:"yank",shortName:"y"},{name:"delmarks",shortName:"delm"},{name:"registers",shortName:"reg",excludeFromCommandHistory:!0},{name:"global",shortName:"g"}],d=a.Pos,e=function(){function e(b){b.setOption("disableInput",!0),b.setOption("showCursorWhenSelecting",!1),a.signal(b,"vim-mode-change",{mode:"normal"}),b.on("cursorActivity",ab),x(b),a.on(b.getInputField(),"paste",k(b))}function f(b){b.setOption("disableInput",!1),b.off("cursorActivity",ab),a.off(b.getInputField(),"paste",k(b)),b.state.vim=null}function g(b,c){this==a.keyMap.vim&&a.rmClass(b.getWrapperElement(),"cm-fat-cursor"),c&&c.attach==h||f(b,!1)}function h(b,c){this==a.keyMap.vim&&a.addClass(b.getWrapperElement(),"cm-fat-cursor"),c&&c.attach==h||e(b)}function i(b,c){if(c){if(this[b])return this[b];var d=j(b);if(!d)return!1;var e=a.Vim.findKey(c,d);return"function"==typeof e&&a.signal(c,"vim-keypress",d),e}}function j(a){if("'"==a.charAt(0))return a.charAt(1);var b=a.split(/-(?!$)/),c=b[b.length-1];if(1==b.length&&1==b[0].length)return!1;if(2==b.length&&"Shift"==b[0]&&1==c.length)return!1;for(var d=!1,e=0;e")}function k(a){var b=a.state.vim;return b.onPasteFn||(b.onPasteFn=function(){b.insertMode||(a.setCursor(L(a.getCursor(),0,1)),Ab.enterInsertMode(a,{},b))}),b.onPasteFn}function l(a,b){for(var c=[],d=a;d=a.firstLine()&&b<=a.lastLine()}function n(a){return/^[a-z]$/.test(a)}function o(a){return"()[]{}".indexOf(a)!=-1}function p(a){return jb.test(a)}function q(a){return/^[A-Z]$/.test(a)}function r(a){return/^\s*$/.test(a)}function s(a,b){for(var c=0;c"==b.slice(-11)){var c=b.length-11,d=a.slice(0,c),e=b.slice(0,c);return d==e&&a.length>c?"full":0==e.indexOf(d)&&"partial"}return a==b?"full":0==b.indexOf(a)&&"partial"}function P(a){var b=/^.*(<[\w\-]+>)$/.exec(a),c=b?b[1]:a.slice(-1);if(c.length>1)switch(c){case"":c="\n";break;case"":c=" "}return c}function Q(a,b,c){return function(){for(var d=0;d2&&(b=U.apply(void 0,Array.prototype.slice.call(arguments,1))),T(a,b)?a:b}function V(a,b){return arguments.length>2&&(b=V.apply(void 0,Array.prototype.slice.call(arguments,1))),T(a,b)?b:a}function W(a,b,c){var d=T(a,b),e=T(b,c);return d&&e}function X(a,b){return a.getLine(b).length}function Y(a){return a.trim?a.trim():a.replace(/^\s+|\s+$/g,"")}function Z(a){return a.replace(/([.?*+$\[\]\/\\(){}|\-])/g,"\\$1")}function $(a,b,c){var e=X(a,b),f=new Array(c-e+1).join(" ");a.setCursor(d(b,e)),a.replaceRange(f,a.getCursor())}function _(a,b){var c=[],e=a.listSelections(),f=R(a.clipPos(b)),g=!S(b,f),h=a.getCursor("head"),i=ba(e,h),j=S(e[i].head,e[i].anchor),k=e.length-1,l=k-i>i?k:0,m=e[l].anchor,n=Math.min(m.line,f.line),o=Math.max(m.line,f.line),p=m.ch,q=f.ch,r=e[l].head.ch-p,s=q-p;r>0&&s<=0?(p++,g||q--):r<0&&s>=0?(p--,j||q++):r<0&&s==-1&&(p--,q++);for(var t=n;t<=o;t++){var u={anchor:new d(t,p),head:new d(t,q)};c.push(u)}return i=f.line==o?c.length-1:0,a.setSelections(c),b.ch=q,m.ch=p,m}function aa(a,b,c){for(var d=[],e=0;ej&&(f.line=j),f.ch=X(a,f.line)}return{ranges:[{anchor:g,head:f}],primary:0}}if("block"==c){for(var k=Math.min(g.line,f.line),l=Math.min(g.ch,f.ch),m=Math.max(g.line,f.line),n=Math.max(g.ch,f.ch)+1,o=m-k+1,p=f.line==k?0:o-1,q=[],r=0;r0&&f&&r(f);f=e.pop())c.line--,c.ch=0;f?(c.line--,c.ch=X(a,c.line)):c.ch=0}}function ka(a,b,c){b.ch=0,c.ch=0,c.line++}function la(a){if(!a)return 0;var b=a.search(/\S/);return b==-1?a.length:b}function ma(a,b,c,e,f){for(var g=ha(a),h=a.getLine(g.line),i=g.ch,j=f?kb[0]:lb[0];!j(h.charAt(i));)if(i++,i>=h.length)return null;e?j=lb[0]:(j=kb[0],j(h.charAt(i))||(j=kb[1]));for(var k=i,l=i;j(h.charAt(k))&&k=0;)l--;if(l++,b){for(var m=k;/\s/.test(h.charAt(k))&&k0;)l--;l||(l=n)}}return{start:d(g.line,l),end:d(g.line,k)}}function na(a,b,c){S(b,c)||ub.jumpList.add(a,b,c)}function oa(a,b){ub.lastCharacterSearch.increment=a,ub.lastCharacterSearch.forward=b.forward,ub.lastCharacterSearch.selectedCharacter=b.selectedCharacter}function pa(a,b,c,e){var f=R(a.getCursor()),g=c?1:-1,h=c?a.lineCount():-1,i=f.ch,j=f.line,k=a.getLine(j),l={lineText:k,nextCh:k.charAt(i),lastCh:null,index:i,symb:e,reverseSymb:(c?{")":"(","}":"{"}:{"(":")","{":"}"})[e],forward:c,depth:0,curMoveThrough:!1},m=Bb[e];if(!m)return f;var n=Cb[m].init,o=Cb[m].isComplete;for(n&&n(l);j!==h&&b;){if(l.index+=g,l.nextCh=l.lineText.charAt(l.index),!l.nextCh){if(j+=g,l.lineText=a.getLine(j)||"",g>0)l.index=0;else{var p=l.lineText.length;l.index=p>0?p-1:0}l.nextCh=l.lineText.charAt(l.index)}o(l)&&(f.line=j,f.ch=l.index,b--)}return l.nextCh||l.curMoveThrough?d(j,l.index):f}function qa(a,b,c,d,e){var f=b.line,g=b.ch,h=a.getLine(f),i=c?1:-1,j=d?lb:kb;if(e&&""==h){if(f+=i,h=a.getLine(f),!m(a,f))return null;g=c?0:h.length}for(;;){if(e&&""==h)return{from:0,to:0,line:f};for(var k=i>0?h.length:-1,l=k,n=k;g!=k;){for(var o=!1,p=0;p0?0:h.length}}function ra(a,b,c,e,f,g){var h=R(b),i=[];(e&&!f||!e&&f)&&c++;for(var j=!(e&&f),k=0;k0;)h(n,e)&&c--,n+=e;return new d(n,0)}var o=a.state.vim;if(o.visualLine&&h(k,1,!0)){var p=o.sel.anchor;h(p.line,-1,!0)&&(f&&p.line==k||(k+=1))}var q=g(k);for(n=k;n<=m&&c;n++)h(n,1,!0)&&(f&&g(n)==q||c--);for(j=new d(n,0),n>m&&!q?q=!0:f=!1,n=k;n>l&&(f&&g(n)!=q&&n!=k||!h(n,-1,!0));n--);return i=new d(n,0),{start:i,end:j}}function xa(a,b,c,e){var f,g,h=b,i={"(":/[()]/,")":/[()]/,"[":/[[\]]/,"]":/[[\]]/,"{":/[{}]/,"}":/[{}]/}[c],j={"(":"(",")":"(","[":"[","]":"[","{":"{","}":"{"}[c],k=a.getLine(h.line).charAt(h.ch),l=k===j?1:0;if(f=a.scanForBracket(d(h.line,h.ch+l),-1,null,{bracketRegex:i}),g=a.scanForBracket(d(h.line,h.ch+l),1,null,{bracketRegex:i}),!f||!g)return{start:h,end:h};if(f=f.pos,g=g.pos,f.line==g.line&&f.ch>g.ch||f.line>g.line){var m=f;f=g,g=m}return e?g.ch+=1:f.ch+=1,{start:f,end:g}}function ya(a,b,c,e){var f,g,h,i,j=R(b),k=a.getLine(j.line),l=k.split(""),m=l.indexOf(c);if(j.ch-1&&!f;h--)l[h]==c&&(f=h+1);else f=j.ch+1;if(f&&!g)for(h=f,i=l.length;h'+b+"",{bottom:!0,duration:5e3}):alert(b)}function Ja(a,b){var c=''+(a||"")+'';return b&&(c+=' '+b+""),c}function Ka(a,b){var c=(b.prefix||"")+" "+(b.desc||""),d=Ja(b.prefix,b.desc);Ba(a,d,c,b.onClose,b)}function La(a,b){if(a instanceof RegExp&&b instanceof RegExp){for(var c=["global","multiline","ignoreCase","source"],d=0;d=b&&a<=c:a==b}function Sa(a){var b=a.getScrollInfo(),c=6,d=10,e=a.coordsChar({left:0,top:c+b.top},"local"),f=b.clientHeight-d+b.top,g=a.coordsChar({left:0,top:f},"local");return{top:e.line,bottom:g.line}}function Ta(b,c,d,e,f,g,h,i,j){function k(){b.operation((function(){for(;!p;)l(),m();n()}))}function l(){var a=b.getRange(g.from(),g.to()),c=a.replace(h,i);g.replace(c)}function m(){for(;g.findNext()&&Ra(g.from(),e,f);)if(d||!q||g.from().line!=q.line)return b.scrollIntoView(g.from(),30),b.setSelection(g.from(),g.to()),q=g.from(),void(p=!1);p=!0}function n(a){if(a&&a(),b.focus(),q){b.setCursor(q);var c=b.state.vim;c.exMode=!1,c.lastHPos=c.lastHSPos=q.ch}j&&j()}function o(c,d,e){a.e_stop(c);var f=a.keyName(c);switch(f){case"Y":l(),m();break;case"N":m();break;case"A":var g=j;j=void 0,b.operation(k),j=g;break;case"L":l();case"Q":case"Esc":case"Ctrl-C":case"Ctrl-[":n(e)}return p&&n(e),!0}b.state.vim.exMode=!0;var p=!1,q=g.from();return m(),p?void Ia(b,"No matches for "+h.source):c?void Ka(b,{prefix:"replace with "+i+" (y/n/a/q/l)",onKeyDown:o}):(k(),void(j&&j()))}function Ua(b){var c=b.state.vim,d=ub.macroModeState,e=ub.registerController.getRegister("."),f=d.isPlaying,g=d.lastInsertModeChanges,h=[];if(!f){for(var i=g.inVisualBlock?c.lastSelection.visualBlock.height:1,j=g.changes,h=[],k=0;k1&&(fb(b,c,c.insertModeRepeat-1,!0),c.lastEditInputState.repeatOverride=c.insertModeRepeat),delete c.insertModeRepeat,c.insertMode=!1,b.setCursor(b.getCursor().line,b.getCursor().ch-1),b.setOption("keyMap","vim"),b.setOption("disableInput",!0),b.toggleOverwrite(!1),e.setText(g.changes.join("")),a.signal(b,"vim-mode-change",{mode:"normal"}),d.isRecording&&Za(d)}function Va(a){b.unshift(a)}function Wa(a,b,c,d,e){var f={keys:a,type:b};f[b]=c,f[b+"Args"]=d;for(var g in e)f[g]=e[g];Va(f)}function Xa(b,c,d,e){var f=ub.registerController.getRegister(e);if(":"==e)return f.keyBuffer[0]&&Ib.processCommand(b,f.keyBuffer[0]),void(d.isPlaying=!1);var g=f.keyBuffer,h=0;d.isPlaying=!0,d.replaySearchQueries=f.searchQueries.slice(0);for(var i=0;i|<\w+>|./.exec(l),k=j[0],l=l.substring(j.index+k.length),a.Vim.handleKey(b,k,"macro"),c.insertMode){var m=f.insertModeChanges[h++].changes;ub.macroModeState.lastInsertModeChanges.changes=m,gb(b,m,1),Ua(b)}d.isPlaying=!1}function Ya(a,b){if(!a.isPlaying){var c=a.latestRegister,d=ub.registerController.getRegister(c);d&&d.pushText(b)}}function Za(a){if(!a.isPlaying){var b=a.latestRegister,c=ub.registerController.getRegister(b);c&&c.pushInsertModeChanges&&c.pushInsertModeChanges(a.lastInsertModeChanges)}}function $a(a,b){if(!a.isPlaying){var c=a.latestRegister,d=ub.registerController.getRegister(c);d&&d.pushSearchQuery&&d.pushSearchQuery(b)}}function _a(a,b){var c=ub.macroModeState,d=c.lastInsertModeChanges;if(!c.isPlaying)for(;b;){if(d.expectCursorActivityForChange=!0,"+input"==b.origin||"paste"==b.origin||void 0===b.origin){var e=b.text.join("\n");d.maybeReset&&(d.changes=[],d.maybeReset=!1),d.changes.push(e)}b=b.next}}function ab(a){var b=a.state.vim;if(b.insertMode){var c=ub.macroModeState;if(c.isPlaying)return;var d=c.lastInsertModeChanges;d.expectCursorActivityForChange?d.expectCursorActivityForChange=!1:d.maybeReset=!0}else a.curOp.isVimOp||cb(a,b);b.visualMode&&bb(a)}function bb(a){var b=a.state.vim,c=J(a,R(b.sel.head)),d=L(c,0,1);b.fakeCursor&&b.fakeCursor.clear(),b.fakeCursor=a.markText(c,d,{className:"cm-animate-fat-cursor"})}function cb(b,c){var d=b.getCursor("anchor"),e=b.getCursor("head");if(c.visualMode&&!b.somethingSelected()?ia(b,!1):c.visualMode||c.insertMode||!b.somethingSelected()||(c.visualMode=!0,c.visualLine=!1,a.signal(b,"vim-mode-change",{mode:"visual"})),c.visualMode){var f=T(e,d)?0:-1,g=T(e,d)?-1:0;e=L(e,0,f),d=L(d,0,g),c.sel={anchor:d,head:e},ua(b,c,"<",U(e,d)),ua(b,c,">",V(e,d))}else c.insertMode||(c.lastHPos=b.getCursor().ch)}function db(a){this.keyName=a}function eb(b){function c(){return e.maybeReset&&(e.changes=[],e.maybeReset=!1),e.changes.push(new db(f)),!0}var d=ub.macroModeState,e=d.lastInsertModeChanges,f=a.keyName(b);f&&(f.indexOf("Delete")==-1&&f.indexOf("Backspace")==-1||a.lookupKey(f,"vim-insert",c))}function fb(a,b,c,d){function e(){h?xb.processAction(a,b,b.lastEditActionCommand):xb.evalInput(a,b)}function f(c){if(g.lastInsertModeChanges.changes.length>0){c=b.lastEditActionCommand?c:1;var d=g.lastInsertModeChanges;gb(a,d.changes,c)}}var g=ub.macroModeState;g.isPlaying=!0;var h=!!b.lastEditActionCommand,i=b.inputState;if(b.inputState=b.lastEditInputState,h&&b.lastEditActionCommand.interlaceInsertRepeat)for(var j=0;j"]),qb=[].concat(mb,nb,ob,["-",'"',".",":","/"]),rb={};t("filetype",void 0,"string",["ft"],(function(a,b){if(void 0!==b){if(void 0===a){var c=b.getOption("mode");return"null"==c?"":c}var c=""==a?"null":a;b.setOption("mode",c)}}));var sb=function(){function a(a,b,h){function i(b){var e=++d%c,f=g[e];f&&f.clear(),g[e]=a.setBookmark(b)}var j=d%c,k=g[j];if(k){var l=k.find();l&&!S(l,b)&&i(b)}else i(b);i(h),e=d,f=d-c+1,f<0&&(f=0)}function b(a,b){d+=b,d>e?d=e:d0?1:-1,k=a.getCursor();do if(d+=j,h=g[(c+d)%c],h&&(i=h.find())&&!S(k,i))break;while(df)}return h}var c=100,d=-1,e=0,f=0,g=new Array(c);return{cachedCursor:void 0,add:a,move:b}},tb=function(a){return a?{changes:a.changes,expectCursorActivityForChange:a.expectCursorActivityForChange}:{changes:[],expectCursorActivityForChange:!1}};w.prototype={exitMacroRecordMode:function(){var a=ub.macroModeState;a.onRecordingDone&&a.onRecordingDone(),a.onRecordingDone=void 0,a.isRecording=!1},enterMacroRecordMode:function(a,b){var c=ub.registerController.getRegister(b);c&&(c.clear(),this.latestRegister=b,a.openDialog&&(this.onRecordingDone=a.openDialog("(recording)["+b+"]",null,{bottom:!0})),this.isRecording=!0)}};var ub,vb,wb={buildKeyMap:function(){},getRegisterController:function(){return ub.registerController},resetVimGlobalState_:y,getVimGlobalState_:function(){return ub},maybeInitVimState_:x,suppressErrorLogging:!1,InsertModeKey:db,map:function(a,b,c){Ib.map(a,b,c)},unmap:function(a,b){Ib.unmap(a,b)},setOption:u,getOption:v,defineOption:t,defineEx:function(a,b,c){if(b){if(0!==a.indexOf(b))throw new Error('(Vim.defineEx) "'+b+'" is not a prefix of "'+a+'", command not registered')}else b=a;Hb[a]=c,Ib.commandMap_[b]={name:a,shortName:b,type:"api"}},handleKey:function(a,b,c){var d=this.findKey(a,b,c);if("function"==typeof d)return d()},findKey:function(c,d,e){function f(){var a=ub.macroModeState;if(a.isRecording){if("q"==d)return a.exitMacroRecordMode(),A(c),!0;"mapping"!=e&&Ya(a,d)}}function g(){if(""==d)return A(c),l.visualMode?ia(c):l.insertMode&&Ua(c),!0}function h(b){for(var e;b;)e=/<\w+-.+?>|<\w+>|./.exec(b),d=e[0],b=b.substring(e.index+d.length),a.Vim.handleKey(c,d,"mapping")}function i(){if(g())return!0;for(var a=l.inputState.keyBuffer=l.inputState.keyBuffer+d,e=1==d.length,f=xb.matchCommand(a,b,l.inputState,"insert");a.length>1&&"full"!=f.type;){var a=l.inputState.keyBuffer=a.slice(1),h=xb.matchCommand(a,b,l.inputState,"insert");"none"!=h.type&&(f=h)}if("none"==f.type)return A(c),!1;if("partial"==f.type)return vb&&window.clearTimeout(vb),vb=window.setTimeout((function(){l.insertMode&&l.inputState.keyBuffer&&A(c)}),v("insertModeEscKeysTimeout")),!e;if(vb&&window.clearTimeout(vb),e){for(var i=c.listSelections(),j=0;j0||this.motionRepeat.length>0)&&(a=1,this.prefixRepeat.length>0&&(a*=parseInt(this.prefixRepeat.join(""),10)),this.motionRepeat.length>0&&(a*=parseInt(this.motionRepeat.join(""),10))),a},B.prototype={setText:function(a,b,c){this.keyBuffer=[a||""],this.linewise=!!b,this.blockwise=!!c},pushText:function(a,b){b&&(this.linewise||this.keyBuffer.push("\n"),this.linewise=!0),this.keyBuffer.push(a)},pushInsertModeChanges:function(a){this.insertModeChanges.push(tb(a))},pushSearchQuery:function(a){this.searchQueries.push(a)},clear:function(){this.keyBuffer=[],this.insertModeChanges=[],this.searchQueries=[],this.linewise=!1},toString:function(){return this.keyBuffer.join("")}},D.prototype={pushText:function(a,b,c,d,e){d&&"\n"==c.charAt(0)&&(c=c.slice(1)+"\n"),d&&"\n"!==c.charAt(c.length-1)&&(c+="\n");var f=this.isValidRegister(a)?this.getRegister(a):null;if(!f){switch(b){case"yank":this.registers[0]=new B(c,d,e);break;case"delete":case"change":c.indexOf("\n")==-1?this.registers["-"]=new B(c,d):(this.shiftNumericRegisters_(),this.registers[1]=new B(c,d))}return void this.unnamedRegister.setText(c,d,e)}var g=q(a);g?f.pushText(c,d):f.setText(c,d,e),this.unnamedRegister.setText(f.toString(),d)},getRegister:function(a){return this.isValidRegister(a)?(a=a.toLowerCase(),this.registers[a]||(this.registers[a]=new B),this.registers[a]):this.unnamedRegister},isValidRegister:function(a){return a&&s(a,qb)},shiftNumericRegisters_:function(){for(var a=9;a>=2;a--)this.registers[a]=this.getRegister(""+(a-1))}},E.prototype={nextMatch:function(a,b){var c=this.historyBuffer,d=b?-1:1;null===this.initialPrefix&&(this.initialPrefix=a);for(var e=this.iterator+d;b?e>=0:e=c.length?(this.iterator=c.length,this.initialPrefix):e<0?a:void 0},pushInput:function(a){var b=this.historyBuffer.indexOf(a);b>-1&&this.historyBuffer.splice(b,1),a.length&&this.historyBuffer.push(a)},reset:function(){this.initialPrefix=null,this.iterator=this.historyBuffer.length}};var xb={matchCommand:function(a,b,c,d){var e=N(a,b,d,c);if(!e.full&&!e.partial)return{type:"none"};if(!e.full&&e.partial)return{type:"partial"};for(var f,g=0;g"==f.keys.slice(-11)&&(c.selectedCharacter=P(a)),{type:"full",command:f}},processCommand:function(a,b,c){switch(b.inputState.repeatOverride=c.repeatOverride,c.type){case"motion":this.processMotion(a,b,c);break;case"operator":this.processOperator(a,b,c);break;case"operatorMotion":this.processOperatorMotion(a,b,c);break;case"action":this.processAction(a,b,c);break;case"search":this.processSearch(a,b,c);break;case"ex":case"keyToEx":this.processEx(a,b,c)}},processMotion:function(a,b,c){b.inputState.motion=c.motion,b.inputState.motionArgs=K(c.motionArgs),this.evalInput(a,b)},processOperator:function(a,b,c){var d=b.inputState;if(d.operator){if(d.operator==c.operator)return d.motion="expandToLine",d.motionArgs={linewise:!0},void this.evalInput(a,b);A(a)}d.operator=c.operator,d.operatorArgs=K(c.operatorArgs),b.visualMode&&this.evalInput(a,b)},processOperatorMotion:function(a,b,c){var d=b.visualMode,e=K(c.operatorMotionArgs);e&&d&&e.visualLine&&(b.visualLine=!0),this.processOperator(a,b,c),d||this.processMotion(a,b,c)},processAction:function(a,b,c){var d=b.inputState,e=d.getRepeat(),f=!!e,g=K(c.actionArgs)||{};d.selectedCharacter&&(g.selectedCharacter=d.selectedCharacter),c.operator&&this.processOperator(a,b,c),c.motion&&this.processMotion(a,b,c),(c.motion||c.operator)&&this.evalInput(a,b),g.repeat=e||1,g.repeatIsExplicit=f,g.registerName=d.registerName,A(a),b.lastMotion=null,c.isEdit&&this.recordLastEdit(b,d,c),Ab[c.action](a,g,b)},processSearch:function(b,c,d){function e(a,e,f){ub.searchHistoryController.pushInput(a),ub.searchHistoryController.reset();try{Ma(b,a,e,f)}catch(c){return Ia(b,"Invalid regex: "+a),void A(b)}xb.processMotion(b,c,{type:"motion",motion:"findNext",motionArgs:{forward:!0,toJumplist:d.searchArgs.toJumplist}})}function f(a){b.scrollTo(m.left,m.top),e(a,!0,!0);var c=ub.macroModeState;c.isRecording&&$a(c,a)}function g(c,d,e){var f,g=a.keyName(c);"Up"==g||"Down"==g?(f="Up"==g,d=ub.searchHistoryController.nextMatch(d,f)||"",e(d)):"Left"!=g&&"Right"!=g&&"Ctrl"!=g&&"Alt"!=g&&"Shift"!=g&&ub.searchHistoryController.reset();var h;try{h=Ma(b,d,!0,!0)}catch(a){}h?b.scrollIntoView(Pa(b,!i,h),30):(Qa(b),b.scrollTo(m.left,m.top))}function h(c,d,e){var f=a.keyName(c);"Esc"==f||"Ctrl-C"==f||"Ctrl-["==f||"Backspace"==f&&""==d?(ub.searchHistoryController.pushInput(d),ub.searchHistoryController.reset(),Ma(b,l),Qa(b),b.scrollTo(m.left,m.top),a.e_stop(c),A(b),e(),b.focus()):"Ctrl-U"==f&&(a.e_stop(c),e(""))}if(b.getSearchCursor){var i=d.searchArgs.forward,j=d.searchArgs.wholeWordOnly;Aa(b).setReversed(!i);var k=i?"/":"?",l=Aa(b).getQuery(),m=b.getScrollInfo();switch(d.searchArgs.querySrc){case"prompt":var n=ub.macroModeState;if(n.isPlaying){var o=n.replaySearchQueries.shift();e(o,!0,!1)}else Ka(b,{onClose:f,prefix:k,desc:Fb,onKeyUp:g,onKeyDown:h});break;case"wordUnderCursor":var p=ma(b,!1,!0,!1,!0),q=!0;if(p||(p=ma(b,!1,!0,!1,!1),q=!1),!p)return;var o=b.getLine(p.start.line).substring(p.start.ch,p.end.ch);o=q&&j?"\\b"+o+"\\b":Z(o),ub.jumpList.cachedCursor=b.getCursor(),b.setCursor(p.start),e(o,!0,!1)}}},processEx:function(b,c,d){function e(a){ub.exCommandHistoryController.pushInput(a),ub.exCommandHistoryController.reset(),Ib.processCommand(b,a)}function f(c,d,e){var f,g=a.keyName(c);("Esc"==g||"Ctrl-C"==g||"Ctrl-["==g||"Backspace"==g&&""==d)&&(ub.exCommandHistoryController.pushInput(d),ub.exCommandHistoryController.reset(),a.e_stop(c),A(b),e(),b.focus()),"Up"==g||"Down"==g?(f="Up"==g,d=ub.exCommandHistoryController.nextMatch(d,f)||"",e(d)):"Ctrl-U"==g?(a.e_stop(c),e("")):"Left"!=g&&"Right"!=g&&"Ctrl"!=g&&"Alt"!=g&&"Shift"!=g&&ub.exCommandHistoryController.reset()}"keyToEx"==d.type?Ib.processCommand(b,d.exArgs.input):c.visualMode?Ka(b,{onClose:e,prefix:":",value:"'<,'>",onKeyDown:f}):Ka(b,{onClose:e,prefix:":",onKeyDown:f})},evalInput:function(a,b){var c,e,f,g=b.inputState,h=g.motion,i=g.motionArgs||{},j=g.operator,k=g.operatorArgs||{},l=g.registerName,m=b.sel,n=R(b.visualMode?J(a,m.head):a.getCursor("head")),o=R(b.visualMode?J(a,m.anchor):a.getCursor("anchor")),p=R(n),q=R(o);if(j&&this.recordLastEdit(b,g),f=void 0!==g.repeatOverride?g.repeatOverride:g.getRepeat(),f>0&&i.explicitRepeat?i.repeatIsExplicit=!0:(i.noRepeat||!i.explicitRepeat&&0===f)&&(f=1,i.repeatIsExplicit=!1),g.selectedCharacter&&(i.selectedCharacter=k.selectedCharacter=g.selectedCharacter),i.repeat=f,A(a),h){var r=yb[h](a,n,i,b);if(b.lastMotion=yb[h],!r)return;if(i.toJumplist){var s=ub.jumpList,t=s.cachedCursor;t?(na(a,t,r),delete s.cachedCursor):na(a,n,r)}r instanceof Array?(e=r[0],c=r[1]):c=r,c||(c=R(n)),b.visualMode?(b.visualBlock&&c.ch===1/0||(c=J(a,c,b.visualBlock)),e&&(e=J(a,e,!0)),e=e||q,m.anchor=e,m.head=c,fa(a),ua(a,b,"<",T(e,c)?e:c),ua(a,b,">",T(e,c)?c:e)):j||(c=J(a,c),a.setCursor(c.line,c.ch))}if(j){if(k.lastSel){e=q;var u=k.lastSel,v=Math.abs(u.head.line-u.anchor.line),w=Math.abs(u.head.ch-u.anchor.ch);c=u.visualLine?d(q.line+v,q.ch):u.visualBlock?d(q.line+v,q.ch+w):u.head.line==u.anchor.line?d(q.line,q.ch+w):d(q.line+v,q.ch),b.visualMode=!0,b.visualLine=u.visualLine,b.visualBlock=u.visualBlock,m=b.sel={anchor:e,head:c},fa(a)}else b.visualMode&&(k.lastSel={anchor:R(m.anchor),head:R(m.head),visualBlock:b.visualBlock,visualLine:b.visualLine});var x,y,z,B,C;if(b.visualMode){if(x=U(m.head,m.anchor),y=V(m.head,m.anchor),z=b.visualLine||k.linewise,B=b.visualBlock?"block":z?"line":"char",C=ga(a,{anchor:x,head:y},B),z){var D=C.ranges;if("block"==B)for(var E=0;Ek&&f.line==k?this.moveToEol(a,b,c,e):(c.toFirstChar&&(g=la(a.getLine(i)),e.lastHPos=g),e.lastHSPos=a.charCoords(d(i,g),"div").left,d(i,g))},moveByDisplayLines:function(a,b,c,e){var f=b;switch(e.lastMotion){case this.moveByDisplayLines:case this.moveByScroll:case this.moveByLines:case this.moveToColumn:case this.moveToEol:break;default:e.lastHSPos=a.charCoords(f,"div").left}var g=c.repeat,h=a.findPosV(f,c.forward?g:-g,"line",e.lastHSPos);if(h.hitSide)if(c.forward)var i=a.charCoords(h,"div"),j={top:i.top+8,left:e.lastHSPos},h=a.coordsChar(j,"div");else{var k=a.charCoords(d(a.firstLine(),0),"div");k.left=e.lastHSPos,h=a.coordsChar(k,"div")}return e.lastHPos=h.ch,h},moveByPage:function(a,b,c){var d=b,e=c.repeat;return a.findPosV(d,c.forward?e:-e,"page")},moveByParagraph:function(a,b,c){var d=c.forward?1:-1;return wa(a,b,c.repeat,d)},moveByScroll:function(a,b,c,d){var e=a.getScrollInfo(),f=null,g=c.repeat;g||(g=e.clientHeight/(2*a.defaultTextHeight()));var h=a.charCoords(b,"local");c.repeat=g;var f=yb.moveByDisplayLines(a,b,c,d);if(!f)return null;var i=a.charCoords(f,"local");return a.scrollTo(null,e.top+i.top-h.top),f},moveByWords:function(a,b,c){return ra(a,b,c.repeat,!!c.forward,!!c.wordEnd,!!c.bigWord)},moveTillCharacter:function(a,b,c){var d=c.repeat,e=sa(a,d,c.forward,c.selectedCharacter),f=c.forward?-1:1;return oa(f,c),e?(e.ch+=f,e):null},moveToCharacter:function(a,b,c){var d=c.repeat;return oa(0,c),sa(a,d,c.forward,c.selectedCharacter)||b},moveToSymbol:function(a,b,c){var d=c.repeat;return pa(a,d,c.forward,c.selectedCharacter)||b},moveToColumn:function(a,b,c,d){var e=c.repeat;return d.lastHPos=e-1,d.lastHSPos=a.charCoords(b,"div").left,ta(a,e)},moveToEol:function(a,b,c,e){var f=b;e.lastHPos=1/0;var g=d(f.line+c.repeat-1,1/0),h=a.clipPos(g);return h.ch--,e.lastHSPos=a.charCoords(h,"div").left,g},moveToFirstNonWhiteSpaceCharacter:function(a,b){var c=b;return d(c.line,la(a.getLine(c.line)))},moveToMatchedSymbol:function(a,b){var c,e=b,f=e.line,g=e.ch,h=a.getLine(f);do if(c=h.charAt(g++),c&&o(c)){var i=a.getTokenTypeAt(d(f,g));if("string"!==i&&"comment"!==i)break}while(c);if(c){var j=a.findMatchingBracket(d(f,g));return j.to}return e},moveToStartOfLine:function(a,b){return d(b.line,0)},moveToLineOrEdgeOfDocument:function(a,b,c){var e=c.forward?a.lastLine():a.firstLine();return c.repeatIsExplicit&&(e=c.repeat-a.getOption("firstLineNumber")),d(e,la(a.getLine(e)))},textObjectManipulation:function(a,b,c,d){var e={"(":")",")":"(","{":"}","}":"{","[":"]","]":"["},f={"'":!0,'"':!0},g=c.selectedCharacter;"b"==g?g="(":"B"==g&&(g="{");var h,i=!c.textObjectInner;if(e[g])h=xa(a,b,g,i);else if(f[g])h=ya(a,b,g,i);else if("W"===g)h=ma(a,i,!0,!0);else if("w"===g)h=ma(a,i,!0,!1);else{if("p"!==g)return null;if(h=wa(a,b,c.repeat,0,i),c.linewise=!0,d.visualMode)d.visualLine||(d.visualLine=!0);else{var j=d.inputState.operatorArgs;j&&(j.linewise=!0),h.end.line--}}return a.state.vim.visualMode?ea(a,h.start,h.end):[h.start,h.end]},repeatLastCharacterSearch:function(a,b,c){var d=ub.lastCharacterSearch,e=c.repeat,f=c.forward===d.forward,g=(d.increment?1:0)*(f?-1:1);a.moveH(-g,"char"),c.inclusive=!!f;var h=sa(a,e,f,d.selectedCharacter);return h?(h.ch+=g,h):(a.moveH(g,"char"),b)}},zb={change:function(b,c,e){var f,g,h=b.state.vim;if(ub.macroModeState.lastInsertModeChanges.inVisualBlock=h.visualBlock,h.visualMode){g=b.getSelection();var i=G("",e.length);b.replaceSelections(i),f=U(e[0].head,e[0].anchor)}else{var j=e[0].anchor,k=e[0].head;g=b.getRange(j,k);var l=h.lastEditInputState||{};if("moveByWords"==l.motion&&!r(g)){var m=/\s+$/.exec(g);m&&l.motionArgs&&l.motionArgs.forward&&(k=L(k,0,-m[0].length),g=g.slice(0,-m[0].length))}var n=new d(j.line-1,Number.MAX_VALUE),o=b.firstLine()==b.lastLine();k.line>b.lastLine()&&c.linewise&&!o?b.replaceRange("",n,k):b.replaceRange("",j,k),c.linewise&&(o||(b.setCursor(n),a.commands.newlineAndIndent(b)),j.ch=Number.MAX_VALUE),f=j}ub.registerController.pushText(c.registerName,"change",g,c.linewise,e.length>1),Ab.enterInsertMode(b,{head:f},b.state.vim)},delete:function(a,b,c){var e,f,g=a.state.vim;if(g.visualBlock){f=a.getSelection();var h=G("",c.length);a.replaceSelections(h),e=c[0].anchor}else{var i=c[0].anchor,j=c[0].head;b.linewise&&j.line!=a.firstLine()&&i.line==a.lastLine()&&i.line==j.line-1&&(i.line==a.firstLine()?i.ch=0:i=d(i.line-1,X(a,i.line-1))), +!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";function b(a){var b=a.getWrapperElement();a.state.fullScreenRestore={scrollTop:window.pageYOffset,scrollLeft:window.pageXOffset,width:b.style.width,height:b.style.height},b.style.width="",b.style.height="auto",b.className+=" CodeMirror-fullscreen",document.documentElement.style.overflow="hidden",a.refresh()}function c(a){var b=a.getWrapperElement();b.className=b.className.replace(/\s*CodeMirror-fullscreen\b/,""),document.documentElement.style.overflow="";var c=a.state.fullScreenRestore;b.style.width=c.width,b.style.height=c.height,window.scrollTo(c.scrollLeft,c.scrollTop),a.refresh()}a.defineOption("fullScreen",!1,(function(d,e,f){f==a.Init&&(f=!1),!f!=!e&&(e?b(d):c(d))}))})),(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){function b(a,b,c,d){this.cm=a,this.node=b,this.options=c,this.height=d,this.cleared=!1}function c(a){var b=a.getWrapperElement(),c=window.getComputedStyle?window.getComputedStyle(b):b.currentStyle,d=parseInt(c.height),e=a.state.panels={setHeight:b.style.height,heightLeft:d,panels:0,wrapper:document.createElement("div")};b.parentNode.insertBefore(e.wrapper,b);var f=a.hasFocus();e.wrapper.appendChild(b),f&&a.focus(),a._setSize=a.setSize,null!=d&&(a.setSize=function(b,c){if(null==c)return this._setSize(b,c);if(e.setHeight=c,"number"!=typeof c){var f=/^(\d+\.?\d*)px$/.exec(c);f?c=Number(f[1]):(e.wrapper.style.height=c,c=e.wrapper.offsetHeight,e.wrapper.style.height="")}a._setSize(b,e.heightLeft+=c-d),d=c})}function d(a){var b=a.state.panels;a.state.panels=null;var c=a.getWrapperElement();b.wrapper.parentNode.replaceChild(c,b.wrapper),c.style.height=b.setHeight,a.setSize=a._setSize,a.setSize()}a.defineExtension("addPanel",(function(a,d){d=d||{},this.state.panels||c(this);var e=this.state.panels,f=e.wrapper,g=this.getWrapperElement();d.after instanceof b&&!d.after.cleared?f.insertBefore(a,d.before.node.nextSibling):d.before instanceof b&&!d.before.cleared?f.insertBefore(a,d.before.node):d.replace instanceof b&&!d.replace.cleared?(f.insertBefore(a,d.replace.node),d.replace.clear()):"bottom"==d.position?f.appendChild(a):"before-bottom"==d.position?f.insertBefore(a,g.nextSibling):"after-top"==d.position?f.insertBefore(a,g):f.insertBefore(a,f.firstChild);var h=d&&d.height||a.offsetHeight;return this._setSize(null,e.heightLeft-=h),e.panels++,new b(this,a,d,h)})),b.prototype.clear=function(){if(!this.cleared){this.cleared=!0;var a=this.cm.state.panels;this.cm._setSize(null,a.heightLeft+=this.height),a.wrapper.removeChild(this.node),0==--a.panels&&d(this.cm)}},b.prototype.changed=function(a){var b=null==a?this.node.offsetHeight:a,c=this.cm.state.panels;this.cm._setSize(null,c.height+=b-this.height),this.height=b}})),(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){function b(a,b){return"pairs"==b&&"string"==typeof a?a:"object"==typeof a&&null!=a[b]?a[b]:m[b]}function c(a){return function(b){return h(b,a)}}function d(a){var b=a.state.closeBrackets;if(!b)return null;var c=a.getModeAt(a.getCursor());return c.closeBrackets||b}function e(c){var e=d(c);if(!e||c.getOption("disableInput"))return a.Pass;for(var f=b(e,"pairs"),g=c.listSelections(),h=0;h=0;h--){var k=g[h].head;c.replaceRange("",n(k.line,k.ch-1),n(k.line,k.ch+1),"+delete")}}function f(c){var e=d(c),f=e&&b(e,"explode");if(!f||c.getOption("disableInput"))return a.Pass;for(var g=c.listSelections(),h=0;h0;return{anchor:new n(b.anchor.line,b.anchor.ch+(c?-1:1)),head:new n(b.head.line,b.head.ch+(c?1:-1))}}function h(c,e){var f=d(c);if(!f||c.getOption("disableInput"))return a.Pass;var h=b(f,"pairs"),j=h.indexOf(e);if(j==-1)return a.Pass;for(var m,o=b(f,"triples"),p=h.charAt(j+1)==e,q=c.listSelections(),r=j%2==0,s=0;s1&&o.indexOf(e)>=0&&c.getRange(n(v.line,v.ch-2),v)==e+e&&(v.ch<=2||c.getRange(n(v.line,v.ch-3),n(v.line,v.ch-2))!=e))t="addFour";else if(p){if(a.isWordChar(w)||!k(c,v,e))return a.Pass;t="both"}else{if(!r||c.getLine(v.line).length!=v.ch&&!i(w,h)&&!/\s/.test(w))return a.Pass;t="both"}else t=p&&l(c,v)?"both":o.indexOf(e)>=0&&c.getRange(v,n(v.line,v.ch+3))==e+e+e?"skipThree":"skip";if(m){if(m!=t)return a.Pass}else m=t}var x=j%2?h.charAt(j-1):e,y=j%2?e:h.charAt(j+1);c.operation((function(){if("skip"==m)c.execCommand("goCharRight");else if("skipThree"==m)for(var a=0;a<3;a++)c.execCommand("goCharRight");else if("surround"==m){for(var b=c.getSelections(),a=0;a-1&&c%2==1}function j(a,b){var c=a.getRange(n(b.line,b.ch-1),n(b.line,b.ch+1));return 2==c.length?c:null}function k(b,c,d){var e=b.getLine(c.line),f=b.getTokenAt(c);if(/\bstring2?\b/.test(f.type))return!1;var g=new a.StringStream(e.slice(0,c.ch)+d+e.slice(c.ch),4);for(g.pos=g.start=f.start;;){var h=b.getMode().token(g,f.state);if(g.pos>=c.ch+1)return/\bstring2?\b/.test(h);g.start=g.pos}}function l(a,b){var c=a.getTokenAt(n(b.line,b.ch+1));return/\bstring/.test(c.type)&&c.start==b.ch}var m={pairs:"()[]{}''\"\"",triples:"",explode:"[]{}"},n=a.Pos;a.defineOption("autoCloseBrackets",!1,(function(b,c,d){d&&d!=a.Init&&(b.removeKeyMap(p),b.state.closeBrackets=null),c&&(b.state.closeBrackets=c,b.addKeyMap(p))}));for(var o=m.pairs+"`",p={Backspace:e,Enter:f},q=0;qj.ch&&(r=r.slice(0,r.length-k.end+j.ch));var s=r.toLowerCase();if(!r||"string"==k.type&&(k.end!=j.ch||!/[\"\']/.test(k.string.charAt(k.string.length-1))||1==k.string.length)||"tag"==k.type&&"closeTag"==m.type||k.string.indexOf("/")==k.string.length-1||p&&e(p,s)>-1||f(b,r,j,m,!0))return a.Pass;var t=q&&e(q,s)>-1;d[i]={indent:t,text:">"+(t?"\n\n":"")+"",newPos:t?a.Pos(j.line+1,0):a.Pos(j.line,j.ch+1)}}for(var i=c.length-1;i>=0;i--){var u=d[i];b.replaceRange(u.text,c[i].head,c[i].anchor,"+insert");var v=b.listSelections().slice(0);v[i]={head:u.newPos,anchor:u.newPos},b.setSelections(v),u.indent&&(b.indentLine(u.newPos.line,null,!0),b.indentLine(u.newPos.line+1,null,!0))}}function c(b,c){for(var d=b.listSelections(),e=[],g=c?"/":""!=b.getLine(i.line).charAt(j.end)&&(m+=">"),e[h]=m}b.replaceSelections(e),d=b.listSelections();for(var h=0;h'"]=function(a){return b(a)}),c.addKeyMap(g)}}));var g=["area","base","br","col","command","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"],h=["applet","blockquote","body","button","div","dl","fieldset","form","frameset","h1","h2","h3","h4","h5","h6","head","html","iframe","layer","legend","object","ol","p","select","table","ul"];a.commands.closeTag=function(a){return c(a)}})),(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){function b(a,b,d,e){var f=a.getLineHandle(b.line),i=b.ch-1,j=i>=0&&h[f.text.charAt(i)]||h[f.text.charAt(++i)];if(!j)return null;var k=">"==j.charAt(1)?1:-1;if(d&&k>0!=(i==b.ch))return null;var l=a.getTokenTypeAt(g(b.line,i+1)),m=c(a,g(b.line,i+(k>0?1:0)),k,l||null,e);return null==m?null:{from:g(b.line,i),to:m&&m.pos,match:m&&m.ch==j.charAt(0),forward:k>0}}function c(a,b,c,d,e){for(var f=e&&e.maxScanLineLength||1e4,i=e&&e.maxScanLines||1e3,j=[],k=e&&e.bracketRegex?e.bracketRegex:/[(){}[\]]/,l=c>0?Math.min(b.line+i,a.lastLine()+1):Math.max(a.firstLine()-1,b.line-i),m=b.line;m!=l;m+=c){var n=a.getLine(m);if(n){var o=c>0?0:n.length-1,p=c>0?n.length:-1;if(!(n.length>f))for(m==b.line&&(o=b.ch-(c<0?1:0));o!=p;o+=c){var q=n.charAt(o);if(k.test(q)&&(void 0===d||a.getTokenTypeAt(g(m,o+1))==d)){var r=h[q];if(">"==r.charAt(1)==c>0)j.push(q);else{if(!j.length)return{pos:g(m,o),ch:q};j.pop()}}}}}return m-c!=(c>0?a.lastLine():a.firstLine())&&null}function d(a,c,d){for(var e=a.state.matchBrackets.maxHighlightLineLength||1e3,h=[],i=a.listSelections(),j=0;j",")":"(<","[":"]>","]":"[<","{":"}>","}":"{<"},i=null;a.defineOption("matchBrackets",!1,(function(b,c,d){d&&d!=a.Init&&(b.off("cursorActivity",e),i&&(i(),i=null)),c&&(b.state.matchBrackets="object"==typeof c?c:{},b.on("cursorActivity",e))})),a.defineExtension("matchBrackets",(function(){d(this,!0)})),a.defineExtension("findMatchingBracket",(function(a,c,d){return b(this,a,c,d)})),a.defineExtension("scanForBracket",(function(a,b,d,e){return c(this,a,b,d,e)}))})),(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror"),require("../fold/xml-fold")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","../fold/xml-fold"],a):a(CodeMirror)})((function(a){"use strict";function b(a){a.state.tagHit&&a.state.tagHit.clear(),a.state.tagOther&&a.state.tagOther.clear(),a.state.tagHit=a.state.tagOther=null}function c(c){c.state.failedTagMatch=!1,c.operation((function(){if(b(c),!c.somethingSelected()){var d=c.getCursor(),e=c.getViewport();e.from=Math.min(e.from,d.line),e.to=Math.max(d.line+1,e.to);var f=a.findMatchingTag(c,d,e);if(f){if(c.state.matchBothTags){var g="open"==f.at?f.open:f.close;g&&(c.state.tagHit=c.markText(g.from,g.to,{className:"CodeMirror-matchingtag"}))}var h="close"==f.at?f.open:f.close;h?c.state.tagOther=c.markText(h.from,h.to,{className:"CodeMirror-matchingtag"}):c.state.failedTagMatch=!0}}}))}function d(a){a.state.failedTagMatch&&c(a)}a.defineOption("matchTags",!1,(function(e,f,g){g&&g!=a.Init&&(e.off("cursorActivity",c),e.off("viewportChange",d),b(e)),f&&(e.state.matchBothTags="object"==typeof f&&f.bothTags,e.on("cursorActivity",c),e.on("viewportChange",d),c(e))})),a.commands.toMatchingTag=function(b){var c=a.findMatchingTag(b,b.getCursor());if(c){var d="close"==c.at?c.open:c.close;d&&b.extendSelection(d.to,d.from)}}})),(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";a.registerHelper("fold","brace",(function(b,c){function d(d){for(var h=c.ch,i=0;;){var j=h<=0?-1:g.lastIndexOf(d,h-1);if(j!=-1){if(1==i&&jb.lastLine())return null;var d=b.getTokenAt(a.Pos(c,1));if(/\S/.test(d.string)||(d=b.getTokenAt(a.Pos(c,d.end+1))),"keyword"!=d.type||"import"!=d.string)return null;for(var e=c,f=Math.min(b.lastLine(),c+10);e<=f;++e){var g=b.getLine(e),h=g.indexOf(";");if(h!=-1)return{startCh:d.end,end:a.Pos(e,h)}}}var e,f=c.line,g=d(f);if(!g||d(f-1)||(e=d(f-2))&&e.end.line==f-1)return null;for(var h=g.end;;){var i=d(h.line+1);if(null==i)break;h=i.end}return{from:b.clipPos(a.Pos(f,g.startCh+1)),to:h}})),a.registerHelper("fold","include",(function(b,c){function d(c){if(cb.lastLine())return null;var d=b.getTokenAt(a.Pos(c,1));return/\S/.test(d.string)||(d=b.getTokenAt(a.Pos(c,d.end+1))),"meta"==d.type&&"#include"==d.string.slice(0,8)?d.start+8:void 0}var e=c.line,f=d(e);if(null==f||null!=d(e-1))return null;for(var g=e;;){var h=d(g+1);if(null==h)break;++g}return{from:a.Pos(e,f+1),to:b.clipPos(a.Pos(g))}}))})),(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";function b(b,e,f,g){function h(a){var c=i(b,e);if(!c||c.to.line-c.from.lineb.firstLine();)e=a.Pos(e.line-1,0),k=h(!1);if(k&&!k.cleared&&"unfold"!==g){var l=c(b,f);a.on(l,"mousedown",(function(b){m.clear(),a.e_preventDefault(b)}));var m=b.markText(k.from,k.to,{replacedWith:l,clearOnEnter:d(b,f,"clearOnEnter"),__isFold:!0});m.on("clear",(function(c,d){a.signal(b,"unfold",b,c,d)})),a.signal(b,"fold",b,k.from,k.to)}}function c(a,b){var c=d(a,b,"widget");if("string"==typeof c){var e=document.createTextNode(c);c=document.createElement("span"),c.appendChild(e),c.className="CodeMirror-foldmarker"}return c}function d(a,b,c){if(b&&void 0!==b[c])return b[c];var d=a.options.foldOptions;return d&&void 0!==d[c]?d[c]:e[c]}a.newFoldFunction=function(a,c){return function(d,e){b(d,e,{rangeFinder:a,widget:c})}},a.defineExtension("foldCode",(function(a,c,d){b(this,a,c,d)})),a.defineExtension("isFolded",(function(a){for(var b=this.findMarksAt(a),c=0;c=h&&(c=e(f.indicatorOpen))}a.setGutterMarker(b,f.gutter,c),++g}))}function g(a){var b=a.getViewport(),c=a.state.foldGutter;c&&(a.operation((function(){f(a,b.from,b.to)})),c.from=b.from,c.to=b.to)}function h(a,b,c){var e=a.state.foldGutter;if(e){var f=e.options;if(c==f.gutter){var g=d(a,b);g?g.clear():a.foldCode(l(b,0),f.rangeFinder)}}}function i(a){var b=a.state.foldGutter;if(b){var c=b.options;b.from=b.to=0,clearTimeout(b.changeUpdate),b.changeUpdate=setTimeout((function(){g(a)}),c.foldOnChangeTimeSpan||600)}}function j(a){var b=a.state.foldGutter;if(b){var c=b.options;clearTimeout(b.changeUpdate),b.changeUpdate=setTimeout((function(){var c=a.getViewport();b.from==b.to||c.from-b.to>20||b.from-c.to>20?g(a):a.operation((function(){c.fromb.to&&(f(a,b.to,c.to),b.to=c.to)}))}),c.updateViewportTimeSpan||400)}}function k(a,b){var c=a.state.foldGutter;if(c){var d=b.line;d>=c.from&&d=a.max))return a.ch=0,a.text=a.cm.getLine(++a.line),!0}function f(a){if(!(a.line<=a.min))return a.text=a.cm.getLine(--a.line),a.ch=a.text.length,!0}function g(a){for(;;){var b=a.text.indexOf(">",a.ch);if(b==-1){if(e(a))continue;return}{if(d(a,b+1)){var c=a.text.lastIndexOf("/",b),f=c>-1&&!/\S/.test(a.text.slice(c+1,b));return a.ch=b+1,f?"selfClose":"regular"}a.ch=b+1}}}function h(a){for(;;){var b=a.ch?a.text.lastIndexOf("<",a.ch-1):-1;if(b==-1){if(f(a))continue;return}if(d(a,b+1)){p.lastIndex=b,a.ch=b;var c=p.exec(a.text);if(c&&c.index==b)return c}else a.ch=b}}function i(a){for(;;){p.lastIndex=a.ch;var b=p.exec(a.text);if(!b){if(e(a))continue;return}{if(d(a,b.index+1))return a.ch=b.index+b[0].length,b;a.ch=b.index+1}}}function j(a){for(;;){var b=a.ch?a.text.lastIndexOf(">",a.ch-1):-1;if(b==-1){if(f(a))continue;return}{if(d(a,b+1)){var c=a.text.lastIndexOf("/",b),e=c>-1&&!/\S/.test(a.text.slice(c+1,b));return a.ch=b+1,e?"selfClose":"regular"}a.ch=b}}}function k(a,b){for(var c=[];;){var d,e=i(a),f=a.line,h=a.ch-(e?e[0].length:0);if(!e||!(d=g(a)))return;if("selfClose"!=d)if(e[1]){for(var j=c.length-1;j>=0;--j)if(c[j]==e[2]){c.length=j;break}if(j<0&&(!b||b==e[2]))return{tag:e[2],from:m(f,h),to:m(a.line,a.ch)}}else c.push(e[2])}}function l(a,b){for(var c=[];;){var d=j(a);if(!d)return;if("selfClose"!=d){var e=a.line,f=a.ch,g=h(a);if(!g)return;if(g[1])c.push(g[2]);else{for(var i=c.length-1;i>=0;--i)if(c[i]==g[2]){c.length=i;break}if(i<0&&(!b||b==g[2]))return{tag:g[2],from:m(a.line,a.ch),to:m(e,f)}}}else h(a)}}var m=a.Pos,n="A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",o=n+"-:.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040",p=new RegExp("<(/?)(["+n+"]["+o+"]*)","g");a.registerHelper("fold","xml",(function(a,b){for(var d=new c(a,b.line,0);;){var e,f=i(d);if(!f||d.line!=b.line||!(e=g(d)))return;if(!f[1]&&"selfClose"!=e){var h=m(d.line,d.ch),j=k(d,f[2]);return j&&{from:h,to:j.from}}}})),a.findMatchingTag=function(a,d,e){var f=new c(a,d.line,d.ch,e);if(f.text.indexOf(">")!=-1||f.text.indexOf("<")!=-1){var i=g(f),j=i&&m(f.line,f.ch),n=i&&h(f);if(i&&n&&!(b(f,d)>0)){var o={from:m(f.line,f.ch),to:j,tag:n[2]};return"selfClose"==i?{open:o,close:null,at:"open"}:n[1]?{open:l(f,n[2]),close:o,at:"close"}:(f=new c(a,j.line,j.ch,e),{open:o,close:k(f,n[2]),at:"open"})}}},a.findEnclosingTag=function(a,b,d){for(var e=new c(a,b.line,b.ch,d);;){var f=l(e);if(!f)break;var g=new c(a,b.line,b.ch,d),h=k(g,f.tag);if(h)return{open:f,close:h}}},a.scanForClosingTag=function(a,b,d,e){var f=new c(a,b.line,b.ch,e?{from:0,to:e}:null);return k(f,d)}})),(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror"),"cjs"):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],(function(b){a(b,"amd")})):a(CodeMirror,"plain")})((function(a,b){function c(a,b){var c=b;return function(){0==--c&&a()}}function d(b,d){var e=a.modes[b].dependencies;if(!e)return d();for(var f=[],g=0;g-1?e+b.length:e}var f=b.exec(c?a.slice(c):a);return f?f.index+c+(d?f[0].length:0):-1}var d=Array.prototype.slice.call(arguments,1);return{startState:function(){return{outer:a.startState(b),innerActive:null,inner:null}},copyState:function(c){return{outer:a.copyState(b,c.outer),innerActive:c.innerActive,inner:c.innerActive&&a.copyState(c.innerActive.mode,c.inner)}},token:function(e,f){if(f.innerActive){var g=f.innerActive,h=e.string;if(!g.close&&e.sol())return f.innerActive=f.inner=null,this.token(e,f);var i=g.close?c(h,g.close,e.pos,g.parseDelimiters):-1;if(i==e.pos&&!g.parseDelimiters)return e.match(g.close),f.innerActive=f.inner=null,g.delimStyle&&g.delimStyle+" "+g.delimStyle+"-close";i>-1&&(e.string=h.slice(0,i));var j=g.mode.token(e,f.inner);return i>-1&&(e.string=h),i==e.pos&&g.parseDelimiters&&(f.innerActive=f.inner=null),g.innerStyle&&(j=j?j+" "+g.innerStyle:g.innerStyle),j}for(var k=1/0,h=e.string,l=0;lh)return c.charCoords(a,"local")[b?"top":"bottom"];var d=c.heightAtLine(j,"local");return d+(b?0:j.height)}a!==!1&&this.computeScale();var c=this.cm,d=this.hScale,e=document.createDocumentFragment(),f=this.annotations,g=c.getOption("lineWrapping"),h=g&&1.5*c.defaultTextHeight(),i=null,j=null;if(c.display.barWidth)for(var k,l=0;lo+.9));)m=f[++l],o=b(m.to,!1)*d;if(o!=n){var p=Math.max(o-n,3),q=e.appendChild(document.createElement("div"));q.style.cssText="position: absolute; right: 0px; width: "+Math.max(c.display.barWidth-1,2)+"px; top: "+(n+this.buttonHeight)+"px; height: "+p+"px",q.className=this.options.className,m.id&&q.setAttribute("annotation-id",m.id)}}this.div.textContent="",this.div.appendChild(e)},b.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("change",this.changeHandler),this.div.parentNode.removeChild(this.div)}})),(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";function b(b,c,d){function e(b){var c=a.wheelEventPixels(b)["horizontal"==f.orientation?"x":"y"],d=f.pos;f.moveTo(f.pos+c),f.pos!=d&&a.e_preventDefault(b)}this.orientation=c,this.scroll=d,this.screen=this.total=this.size=1,this.pos=0,this.node=document.createElement("div"),this.node.className=b+"-"+c,this.inner=this.node.appendChild(document.createElement("div"));var f=this;a.on(this.inner,"mousedown",(function(b){function c(){a.off(document,"mousemove",d),a.off(document,"mouseup",c)}function d(a){return 1!=a.which?c():void f.moveTo(h+(a[e]-g)*(f.total/f.size))}if(1==b.which){a.e_preventDefault(b);var e="horizontal"==f.orientation?"pageX":"pageY",g=b[e],h=f.pos;a.on(document,"mousemove",d),a.on(document,"mouseup",c)}})),a.on(this.node,"click",(function(b){a.e_preventDefault(b);var c,d=f.inner.getBoundingClientRect();c="horizontal"==f.orientation?b.clientXd.right?1:0:b.clientYd.bottom?1:0,f.moveTo(f.pos+c*f.screen)})),a.on(this.node,"mousewheel",e),a.on(this.node,"DOMMouseScroll",e)}function c(a,c,d){this.addClass=a,this.horiz=new b(a,"horizontal",d),c(this.horiz.node),this.vert=new b(a,"vertical",d),c(this.vert.node),this.width=null}b.prototype.setPos=function(a,b){return a<0&&(a=0),a>this.total-this.screen&&(a=this.total-this.screen),!(!b&&a==this.pos)&&(this.pos=a,this.inner.style["horizontal"==this.orientation?"left":"top"]=a*(this.size/this.total)+"px",!0)},b.prototype.moveTo=function(a){this.setPos(a)&&this.scroll(a,this.orientation)};var d=10;b.prototype.update=function(a,b,c){var e=this.screen!=b||this.total!=a||this.size!=c;e&&(this.screen=b,this.total=a,this.size=c);var f=this.screen*(this.size/this.total);fa.clientWidth+1,e=a.scrollHeight>a.clientHeight+1;return this.vert.node.style.display=e?"block":"none",this.horiz.node.style.display=d?"block":"none", +e&&(this.vert.update(a.scrollHeight,a.clientHeight,a.viewHeight-(d?c:0)),this.vert.node.style.bottom=d?c+"px":"0"),d&&(this.horiz.update(a.scrollWidth,a.clientWidth,a.viewWidth-(e?c:0)-a.barLeft),this.horiz.node.style.right=e?c+"px":"0",this.horiz.node.style.left=a.barLeft+"px"),{right:e?c:0,bottom:d?c:0}},c.prototype.setScrollTop=function(a){this.vert.setPos(a)},c.prototype.setScrollLeft=function(a){this.horiz.setPos(a)},c.prototype.clear=function(){var a=this.horiz.node.parentNode;a.removeChild(this.horiz.node),a.removeChild(this.vert.node)},a.scrollbarModel.simple=function(a,b){return new c("CodeMirror-simplescroll",a,b)},a.scrollbarModel.overlay=function(a,b){return new c("CodeMirror-overlayscroll",a,b)}})),(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror"),require("./searchcursor"),require("../scroll/annotatescrollbar")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","./searchcursor","../scroll/annotatescrollbar"],a):a(CodeMirror)})((function(a){"use strict";function b(a,b,c,d){this.cm=a,this.options=d;var e={listenForChanges:!1};for(var f in d)e[f]=d[f];e.className||(e.className="CodeMirror-search-match"),this.annotation=a.annotateScrollbar(e),this.query=b,this.caseFold=c,this.gap={from:a.firstLine(),to:a.lastLine()+1},this.matches=[],this.update=null,this.findMatches(),this.annotation.update(this.matches);var g=this;a.on("change",this.changeHandler=function(a,b){g.onChange(b)})}function c(a,b,c){return a<=b?a:Math.max(b,a+c)}a.defineExtension("showMatchesOnScrollbar",(function(a,c,d){return"string"==typeof d&&(d={className:d}),d||(d={}),new b(this,a,c,d)}));var d=1e3;b.prototype.findMatches=function(){if(this.gap){for(var b=0;b=this.gap.to)break;c.to.line>=this.gap.from&&this.matches.splice(b--,1)}for(var e=this.cm.getSearchCursor(this.query,a.Pos(this.gap.from,0),this.caseFold),f=this.options&&this.options.maxMatches||d;e.findNext();){var c={from:e.from(),to:e.to()};if(c.from.line>=this.gap.to)break;if(this.matches.splice(b++,0,c),this.matches.length>f)break}this.gap=null}},b.prototype.onChange=function(b){var d=b.from.line,e=a.changeEnd(b).line,f=e-b.to.line;if(this.gap?(this.gap.from=Math.min(c(this.gap.from,d,f),b.from.line),this.gap.to=Math.max(c(this.gap.to,d,f),b.from.line)):this.gap={from:b.from.line,to:e+1},f)for(var g=0;g=b.options.minChars&&f(a,m,!1,b.options.style)}}))}function i(a,b,c){var d=a.getRange(b,c);if(null!==d.match(/^\w+$/)){if(b.ch>0){var e={line:b.line,ch:b.ch-1},f=a.getRange(e,b);if(null===f.match(/\W/))return!1}if(c.ch-1)return k=c(i,j,k),{from:d(f.line,k),to:d(f.line,k+g.length)}}else{var i=a.getLine(f.line).slice(f.ch),j=h(i),k=j.indexOf(b);if(k>-1)return k=c(i,j,k)+f.ch,{from:d(f.line,k),to:d(f.line,k+g.length)}}}:this.matches=function(){};else{var j=g.split("\n");this.matches=function(b,c){var e=i.length-1;if(b){if(c.line-(i.length-1)=1;--k,--g)if(i[k]!=h(a.getLine(g)))return;var l=a.getLine(g),m=l.length-j[0].length;if(h(l.slice(m))!=i[0])return;return{from:d(g,m),to:f}}if(!(c.line+(i.length-1)>a.lastLine())){var l=a.getLine(c.line),m=l.length-j[0].length;if(h(l.slice(m))==i[0]){for(var n=d(c.line,m),g=c.line+1,k=1;kc))return d;--d}}}var d=a.Pos;b.prototype={findNext:function(){return this.find(!1)},findPrevious:function(){return this.find(!0)},find:function(a){function b(a){var b=d(a,0);return c.pos={from:b,to:b},c.atOccurrence=!1,!1}for(var c=this,e=this.doc.clipPos(a?this.pos.from:this.pos.to);;){if(this.pos=this.matches(a,e))return this.atOccurrence=!0,this.pos.match||!0;if(a){if(!e.line)return b(0);e=d(e.line-1,this.doc.getLine(e.line-1).length)}else{var f=this.doc.lineCount();if(e.line==f-1)return b(f);e=d(e.line+1,0)}}},from:function(){if(this.atOccurrence)return this.pos.from},to:function(){if(this.atOccurrence)return this.pos.to},replace:function(b,c){if(this.atOccurrence){var e=a.splitLines(b);this.doc.replaceRange(e,this.pos.from,this.pos.to,c),this.pos.to=d(this.pos.from.line+e.length-1,e[e.length-1].length+(1==e.length?this.pos.from.ch:0))}}},a.defineExtension("getSearchCursor",(function(a,c,d){return new b(this.doc,a,c,d)})),a.defineDocExtension("getSearchCursor",(function(a,c,d){return new b(this,a,c,d)})),a.defineExtension("selectMatches",(function(b,c){for(var d=[],e=this.getSearchCursor(b,this.getCursor("from"),c);e.findNext()&&!(a.cmpPos(e.to(),this.getCursor("to"))>0);)d.push({anchor:e.from(),head:e.to()});d.length&&this.setSelections(d,0)}))})),(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";function b(a){for(var b=0;b",type:"keyToKey",toKeys:"h"},{keys:"",type:"keyToKey",toKeys:"l"},{keys:"",type:"keyToKey",toKeys:"k"},{keys:"",type:"keyToKey",toKeys:"j"},{keys:"",type:"keyToKey",toKeys:"l"},{keys:"",type:"keyToKey",toKeys:"h",context:"normal"},{keys:"",type:"keyToKey",toKeys:"W"},{keys:"",type:"keyToKey",toKeys:"B",context:"normal"},{keys:"",type:"keyToKey",toKeys:"w"},{keys:"",type:"keyToKey",toKeys:"b",context:"normal"},{keys:"",type:"keyToKey",toKeys:"j"},{keys:"",type:"keyToKey",toKeys:"k"},{keys:"",type:"keyToKey",toKeys:""},{keys:"",type:"keyToKey",toKeys:""},{keys:"",type:"keyToKey",toKeys:"",context:"insert"},{keys:"",type:"keyToKey",toKeys:"",context:"insert"},{keys:"s",type:"keyToKey",toKeys:"cl",context:"normal"},{keys:"s",type:"keyToKey",toKeys:"c",context:"visual"},{keys:"S",type:"keyToKey",toKeys:"cc",context:"normal"},{keys:"S",type:"keyToKey",toKeys:"VdO",context:"visual"},{keys:"",type:"keyToKey",toKeys:"0"},{keys:"",type:"keyToKey",toKeys:"$"},{keys:"",type:"keyToKey",toKeys:""},{keys:"",type:"keyToKey",toKeys:""},{keys:"",type:"keyToKey",toKeys:"j^",context:"normal"},{keys:"",type:"action",action:"toggleOverwrite",context:"insert"},{keys:"H",type:"motion",motion:"moveToTopLine",motionArgs:{linewise:!0,toJumplist:!0}},{keys:"M",type:"motion",motion:"moveToMiddleLine",motionArgs:{linewise:!0,toJumplist:!0}},{keys:"L",type:"motion",motion:"moveToBottomLine",motionArgs:{linewise:!0,toJumplist:!0}},{keys:"h",type:"motion",motion:"moveByCharacters",motionArgs:{forward:!1}},{keys:"l",type:"motion",motion:"moveByCharacters",motionArgs:{forward:!0}},{keys:"j",type:"motion",motion:"moveByLines",motionArgs:{forward:!0,linewise:!0}},{keys:"k",type:"motion",motion:"moveByLines",motionArgs:{forward:!1,linewise:!0}},{keys:"gj",type:"motion",motion:"moveByDisplayLines",motionArgs:{forward:!0}},{keys:"gk",type:"motion",motion:"moveByDisplayLines",motionArgs:{forward:!1}},{keys:"w",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!1}},{keys:"W",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!1,bigWord:!0}},{keys:"e",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!0,inclusive:!0}},{keys:"E",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!0,bigWord:!0,inclusive:!0}},{keys:"b",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!1}},{keys:"B",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!1,bigWord:!0}},{keys:"ge",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!0,inclusive:!0}},{keys:"gE",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!0,bigWord:!0,inclusive:!0}},{keys:"{",type:"motion",motion:"moveByParagraph",motionArgs:{forward:!1,toJumplist:!0}},{keys:"}",type:"motion",motion:"moveByParagraph",motionArgs:{forward:!0,toJumplist:!0}},{keys:"",type:"motion",motion:"moveByPage",motionArgs:{forward:!0}},{keys:"",type:"motion",motion:"moveByPage",motionArgs:{forward:!1}},{keys:"",type:"motion",motion:"moveByScroll",motionArgs:{forward:!0,explicitRepeat:!0}},{keys:"",type:"motion",motion:"moveByScroll",motionArgs:{forward:!1,explicitRepeat:!0}},{keys:"gg",type:"motion",motion:"moveToLineOrEdgeOfDocument",motionArgs:{forward:!1,explicitRepeat:!0,linewise:!0,toJumplist:!0}},{keys:"G",type:"motion",motion:"moveToLineOrEdgeOfDocument",motionArgs:{forward:!0,explicitRepeat:!0,linewise:!0,toJumplist:!0}},{keys:"0",type:"motion",motion:"moveToStartOfLine"},{keys:"^",type:"motion",motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:"+",type:"motion",motion:"moveByLines",motionArgs:{forward:!0,toFirstChar:!0}},{keys:"-",type:"motion",motion:"moveByLines",motionArgs:{forward:!1,toFirstChar:!0}},{keys:"_",type:"motion",motion:"moveByLines",motionArgs:{forward:!0,toFirstChar:!0,repeatOffset:-1}},{keys:"$",type:"motion",motion:"moveToEol",motionArgs:{inclusive:!0}},{keys:"%",type:"motion",motion:"moveToMatchedSymbol",motionArgs:{inclusive:!0,toJumplist:!0}},{keys:"f",type:"motion",motion:"moveToCharacter",motionArgs:{forward:!0,inclusive:!0}},{keys:"F",type:"motion",motion:"moveToCharacter",motionArgs:{forward:!1}},{keys:"t",type:"motion",motion:"moveTillCharacter",motionArgs:{forward:!0,inclusive:!0}},{keys:"T",type:"motion",motion:"moveTillCharacter",motionArgs:{forward:!1}},{keys:";",type:"motion",motion:"repeatLastCharacterSearch",motionArgs:{forward:!0}},{keys:",",type:"motion",motion:"repeatLastCharacterSearch",motionArgs:{forward:!1}},{keys:"'",type:"motion",motion:"goToMark",motionArgs:{toJumplist:!0,linewise:!0}},{keys:"`",type:"motion",motion:"goToMark",motionArgs:{toJumplist:!0}},{keys:"]`",type:"motion",motion:"jumpToMark",motionArgs:{forward:!0}},{keys:"[`",type:"motion",motion:"jumpToMark",motionArgs:{forward:!1}},{keys:"]'",type:"motion",motion:"jumpToMark",motionArgs:{forward:!0,linewise:!0}},{keys:"['",type:"motion",motion:"jumpToMark",motionArgs:{forward:!1,linewise:!0}},{keys:"]p",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!0,isEdit:!0,matchIndent:!0}},{keys:"[p",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!1,isEdit:!0,matchIndent:!0}},{keys:"]",type:"motion",motion:"moveToSymbol",motionArgs:{forward:!0,toJumplist:!0}},{keys:"[",type:"motion",motion:"moveToSymbol",motionArgs:{forward:!1,toJumplist:!0}},{keys:"|",type:"motion",motion:"moveToColumn"},{keys:"o",type:"motion",motion:"moveToOtherHighlightedEnd",context:"visual"},{keys:"O",type:"motion",motion:"moveToOtherHighlightedEnd",motionArgs:{sameLine:!0},context:"visual"},{keys:"d",type:"operator",operator:"delete"},{keys:"y",type:"operator",operator:"yank"},{keys:"c",type:"operator",operator:"change"},{keys:">",type:"operator",operator:"indent",operatorArgs:{indentRight:!0}},{keys:"<",type:"operator",operator:"indent",operatorArgs:{indentRight:!1}},{keys:"g~",type:"operator",operator:"changeCase"},{keys:"gu",type:"operator",operator:"changeCase",operatorArgs:{toLower:!0},isEdit:!0},{keys:"gU",type:"operator",operator:"changeCase",operatorArgs:{toLower:!1},isEdit:!0},{keys:"n",type:"motion",motion:"findNext",motionArgs:{forward:!0,toJumplist:!0}},{keys:"N",type:"motion",motion:"findNext",motionArgs:{forward:!1,toJumplist:!0}},{keys:"x",type:"operatorMotion",operator:"delete",motion:"moveByCharacters",motionArgs:{forward:!0},operatorMotionArgs:{visualLine:!1}},{keys:"X",type:"operatorMotion",operator:"delete",motion:"moveByCharacters",motionArgs:{forward:!1},operatorMotionArgs:{visualLine:!0}},{keys:"D",type:"operatorMotion",operator:"delete",motion:"moveToEol",motionArgs:{inclusive:!0},context:"normal"},{keys:"D",type:"operator",operator:"delete",operatorArgs:{linewise:!0},context:"visual"},{keys:"Y",type:"operatorMotion",operator:"yank",motion:"moveToEol",motionArgs:{inclusive:!0},context:"normal"},{keys:"Y",type:"operator",operator:"yank",operatorArgs:{linewise:!0},context:"visual"},{keys:"C",type:"operatorMotion",operator:"change",motion:"moveToEol",motionArgs:{inclusive:!0},context:"normal"},{keys:"C",type:"operator",operator:"change",operatorArgs:{linewise:!0},context:"visual"},{keys:"~",type:"operatorMotion",operator:"changeCase",motion:"moveByCharacters",motionArgs:{forward:!0},operatorArgs:{shouldMoveCursor:!0},context:"normal"},{keys:"~",type:"operator",operator:"changeCase",context:"visual"},{keys:"",type:"operatorMotion",operator:"delete",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!1},context:"insert"},{keys:"",type:"action",action:"jumpListWalk",actionArgs:{forward:!0}},{keys:"",type:"action",action:"jumpListWalk",actionArgs:{forward:!1}},{keys:"",type:"action",action:"scroll",actionArgs:{forward:!0,linewise:!0}},{keys:"",type:"action",action:"scroll",actionArgs:{forward:!1,linewise:!0}},{keys:"a",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"charAfter"},context:"normal"},{keys:"A",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"eol"},context:"normal"},{keys:"A",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"endOfSelectedArea"},context:"visual"},{keys:"i",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"inplace"},context:"normal"},{keys:"I",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"firstNonBlank"},context:"normal"},{keys:"I",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"startOfSelectedArea"},context:"visual"},{keys:"o",type:"action",action:"newLineAndEnterInsertMode",isEdit:!0,interlaceInsertRepeat:!0,actionArgs:{after:!0},context:"normal"},{keys:"O",type:"action",action:"newLineAndEnterInsertMode",isEdit:!0,interlaceInsertRepeat:!0,actionArgs:{after:!1},context:"normal"},{keys:"v",type:"action",action:"toggleVisualMode"},{keys:"V",type:"action",action:"toggleVisualMode",actionArgs:{linewise:!0}},{keys:"",type:"action",action:"toggleVisualMode",actionArgs:{blockwise:!0}},{keys:"",type:"action",action:"toggleVisualMode",actionArgs:{blockwise:!0}},{keys:"gv",type:"action",action:"reselectLastSelection"},{keys:"J",type:"action",action:"joinLines",isEdit:!0},{keys:"p",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!0,isEdit:!0}},{keys:"P",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!1,isEdit:!0}},{keys:"r",type:"action",action:"replace",isEdit:!0},{keys:"@",type:"action",action:"replayMacro"},{keys:"q",type:"action",action:"enterMacroRecordMode"},{keys:"R",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{replace:!0}},{keys:"u",type:"action",action:"undo",context:"normal"},{keys:"u",type:"operator",operator:"changeCase",operatorArgs:{toLower:!0},context:"visual",isEdit:!0},{keys:"U",type:"operator",operator:"changeCase",operatorArgs:{toLower:!1},context:"visual",isEdit:!0},{keys:"",type:"action",action:"redo"},{keys:"m",type:"action",action:"setMark"},{keys:'"',type:"action",action:"setRegister"},{keys:"zz",type:"action",action:"scrollToCursor",actionArgs:{position:"center"}},{keys:"z.",type:"action",action:"scrollToCursor",actionArgs:{position:"center"},motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:"zt",type:"action",action:"scrollToCursor",actionArgs:{position:"top"}},{keys:"z",type:"action",action:"scrollToCursor",actionArgs:{position:"top"},motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:"z-",type:"action",action:"scrollToCursor",actionArgs:{position:"bottom"}},{keys:"zb",type:"action",action:"scrollToCursor",actionArgs:{position:"bottom"},motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:".",type:"action",action:"repeatLastEdit"},{keys:"",type:"action",action:"incrementNumberToken",isEdit:!0,actionArgs:{increase:!0,backtrack:!1}},{keys:"",type:"action",action:"incrementNumberToken",isEdit:!0,actionArgs:{increase:!1,backtrack:!1}},{keys:"a",type:"motion",motion:"textObjectManipulation"},{keys:"i",type:"motion",motion:"textObjectManipulation",motionArgs:{textObjectInner:!0}},{keys:"/",type:"search",searchArgs:{forward:!0,querySrc:"prompt",toJumplist:!0}},{keys:"?",type:"search",searchArgs:{forward:!1,querySrc:"prompt",toJumplist:!0}},{keys:"*",type:"search",searchArgs:{forward:!0,querySrc:"wordUnderCursor",wholeWordOnly:!0,toJumplist:!0}},{keys:"#",type:"search",searchArgs:{forward:!1,querySrc:"wordUnderCursor",wholeWordOnly:!0,toJumplist:!0}},{keys:"g*",type:"search",searchArgs:{forward:!0,querySrc:"wordUnderCursor",toJumplist:!0}},{keys:"g#",type:"search",searchArgs:{forward:!1,querySrc:"wordUnderCursor",toJumplist:!0}},{keys:":",type:"ex"}],c=[{name:"colorscheme",shortName:"colo"},{name:"map"},{name:"imap",shortName:"im"},{name:"nmap",shortName:"nm"},{name:"vmap",shortName:"vm"},{name:"unmap"},{name:"write",shortName:"w"},{name:"undo",shortName:"u"},{name:"redo",shortName:"red"},{name:"set",shortName:"se"},{name:"set",shortName:"se"},{name:"setlocal",shortName:"setl"},{name:"setglobal",shortName:"setg"},{name:"sort",shortName:"sor"},{name:"substitute",shortName:"s",possiblyAsync:!0},{name:"nohlsearch",shortName:"noh"},{name:"yank",shortName:"y"},{name:"delmarks",shortName:"delm"},{name:"registers",shortName:"reg",excludeFromCommandHistory:!0},{name:"global",shortName:"g"}],d=a.Pos,e=function(){function e(b){b.setOption("disableInput",!0),b.setOption("showCursorWhenSelecting",!1),a.signal(b,"vim-mode-change",{mode:"normal"}),b.on("cursorActivity",ab),x(b),a.on(b.getInputField(),"paste",k(b))}function f(b){b.setOption("disableInput",!1),b.off("cursorActivity",ab),a.off(b.getInputField(),"paste",k(b)),b.state.vim=null}function g(b,c){this==a.keyMap.vim&&a.rmClass(b.getWrapperElement(),"cm-fat-cursor"),c&&c.attach==h||f(b,!1)}function h(b,c){this==a.keyMap.vim&&a.addClass(b.getWrapperElement(),"cm-fat-cursor"),c&&c.attach==h||e(b)}function i(b,c){if(c){if(this[b])return this[b];var d=j(b);if(!d)return!1;var e=a.Vim.findKey(c,d);return"function"==typeof e&&a.signal(c,"vim-keypress",d),e}}function j(a){if("'"==a.charAt(0))return a.charAt(1);var b=a.split(/-(?!$)/),c=b[b.length-1];if(1==b.length&&1==b[0].length)return!1;if(2==b.length&&"Shift"==b[0]&&1==c.length)return!1;for(var d=!1,e=0;e")}function k(a){var b=a.state.vim;return b.onPasteFn||(b.onPasteFn=function(){b.insertMode||(a.setCursor(L(a.getCursor(),0,1)),Ab.enterInsertMode(a,{},b))}),b.onPasteFn}function l(a,b){for(var c=[],d=a;d=a.firstLine()&&b<=a.lastLine()}function n(a){return/^[a-z]$/.test(a)}function o(a){return"()[]{}".indexOf(a)!=-1}function p(a){return jb.test(a)}function q(a){return/^[A-Z]$/.test(a)}function r(a){return/^\s*$/.test(a)}function s(a,b){for(var c=0;c"==b.slice(-11)){var c=b.length-11,d=a.slice(0,c),e=b.slice(0,c);return d==e&&a.length>c?"full":0==e.indexOf(d)&&"partial"}return a==b?"full":0==b.indexOf(a)&&"partial"}function P(a){var b=/^.*(<[\w\-]+>)$/.exec(a),c=b?b[1]:a.slice(-1);if(c.length>1)switch(c){case"":c="\n";break;case"":c=" "}return c}function Q(a,b,c){return function(){for(var d=0;d2&&(b=U.apply(void 0,Array.prototype.slice.call(arguments,1))),T(a,b)?a:b}function V(a,b){return arguments.length>2&&(b=V.apply(void 0,Array.prototype.slice.call(arguments,1))),T(a,b)?b:a}function W(a,b,c){var d=T(a,b),e=T(b,c);return d&&e}function X(a,b){return a.getLine(b).length}function Y(a){return a.trim?a.trim():a.replace(/^\s+|\s+$/g,"")}function Z(a){return a.replace(/([.?*+$\[\]\/\\(){}|\-])/g,"\\$1")}function $(a,b,c){var e=X(a,b),f=new Array(c-e+1).join(" ");a.setCursor(d(b,e)),a.replaceRange(f,a.getCursor())}function _(a,b){var c=[],e=a.listSelections(),f=R(a.clipPos(b)),g=!S(b,f),h=a.getCursor("head"),i=ba(e,h),j=S(e[i].head,e[i].anchor),k=e.length-1,l=k-i>i?k:0,m=e[l].anchor,n=Math.min(m.line,f.line),o=Math.max(m.line,f.line),p=m.ch,q=f.ch,r=e[l].head.ch-p,s=q-p;r>0&&s<=0?(p++,g||q--):r<0&&s>=0?(p--,j||q++):r<0&&s==-1&&(p--,q++);for(var t=n;t<=o;t++){var u={anchor:new d(t,p),head:new d(t,q)};c.push(u)}return i=f.line==o?c.length-1:0,a.setSelections(c),b.ch=q,m.ch=p,m}function aa(a,b,c){for(var d=[],e=0;ej&&(f.line=j),f.ch=X(a,f.line)}return{ranges:[{anchor:g,head:f}],primary:0}}if("block"==c){for(var k=Math.min(g.line,f.line),l=Math.min(g.ch,f.ch),m=Math.max(g.line,f.line),n=Math.max(g.ch,f.ch)+1,o=m-k+1,p=f.line==k?0:o-1,q=[],r=0;r0&&f&&r(f);f=e.pop())c.line--,c.ch=0;f?(c.line--,c.ch=X(a,c.line)):c.ch=0}}function ka(a,b,c){b.ch=0,c.ch=0,c.line++}function la(a){if(!a)return 0;var b=a.search(/\S/);return b==-1?a.length:b}function ma(a,b,c,e,f){for(var g=ha(a),h=a.getLine(g.line),i=g.ch,j=f?kb[0]:lb[0];!j(h.charAt(i));)if(i++,i>=h.length)return null;e?j=lb[0]:(j=kb[0],j(h.charAt(i))||(j=kb[1]));for(var k=i,l=i;j(h.charAt(k))&&k=0;)l--;if(l++,b){for(var m=k;/\s/.test(h.charAt(k))&&k0;)l--;l||(l=n)}}return{start:d(g.line,l),end:d(g.line,k)}}function na(a,b,c){S(b,c)||ub.jumpList.add(a,b,c)}function oa(a,b){ub.lastCharacterSearch.increment=a,ub.lastCharacterSearch.forward=b.forward,ub.lastCharacterSearch.selectedCharacter=b.selectedCharacter}function pa(a,b,c,e){var f=R(a.getCursor()),g=c?1:-1,h=c?a.lineCount():-1,i=f.ch,j=f.line,k=a.getLine(j),l={lineText:k,nextCh:k.charAt(i),lastCh:null,index:i,symb:e,reverseSymb:(c?{")":"(","}":"{"}:{"(":")","{":"}"})[e],forward:c,depth:0,curMoveThrough:!1},m=Bb[e];if(!m)return f;var n=Cb[m].init,o=Cb[m].isComplete;for(n&&n(l);j!==h&&b;){if(l.index+=g,l.nextCh=l.lineText.charAt(l.index),!l.nextCh){if(j+=g,l.lineText=a.getLine(j)||"",g>0)l.index=0;else{var p=l.lineText.length;l.index=p>0?p-1:0}l.nextCh=l.lineText.charAt(l.index)}o(l)&&(f.line=j,f.ch=l.index,b--)}return l.nextCh||l.curMoveThrough?d(j,l.index):f}function qa(a,b,c,d,e){var f=b.line,g=b.ch,h=a.getLine(f),i=c?1:-1,j=d?lb:kb;if(e&&""==h){if(f+=i,h=a.getLine(f),!m(a,f))return null;g=c?0:h.length}for(;;){if(e&&""==h)return{from:0,to:0,line:f};for(var k=i>0?h.length:-1,l=k,n=k;g!=k;){for(var o=!1,p=0;p0?0:h.length}}function ra(a,b,c,e,f,g){var h=R(b),i=[];(e&&!f||!e&&f)&&c++;for(var j=!(e&&f),k=0;k0;)h(n,e)&&c--,n+=e;return new d(n,0)}var o=a.state.vim;if(o.visualLine&&h(k,1,!0)){var p=o.sel.anchor;h(p.line,-1,!0)&&(f&&p.line==k||(k+=1))}var q=g(k);for(n=k;n<=m&&c;n++)h(n,1,!0)&&(f&&g(n)==q||c--);for(j=new d(n,0),n>m&&!q?q=!0:f=!1,n=k;n>l&&(f&&g(n)!=q&&n!=k||!h(n,-1,!0));n--);return i=new d(n,0),{start:i,end:j}}function xa(a,b,c,e){var f,g,h=b,i={"(":/[()]/,")":/[()]/,"[":/[[\]]/,"]":/[[\]]/,"{":/[{}]/,"}":/[{}]/}[c],j={"(":"(",")":"(","[":"[","]":"[","{":"{","}":"{"}[c],k=a.getLine(h.line).charAt(h.ch),l=k===j?1:0;if(f=a.scanForBracket(d(h.line,h.ch+l),-1,null,{bracketRegex:i}),g=a.scanForBracket(d(h.line,h.ch+l),1,null,{bracketRegex:i}),!f||!g)return{start:h,end:h};if(f=f.pos,g=g.pos,f.line==g.line&&f.ch>g.ch||f.line>g.line){var m=f;f=g,g=m}return e?g.ch+=1:f.ch+=1,{start:f,end:g}}function ya(a,b,c,e){var f,g,h,i,j=R(b),k=a.getLine(j.line),l=k.split(""),m=l.indexOf(c);if(j.ch-1&&!f;h--)l[h]==c&&(f=h+1);else f=j.ch+1;if(f&&!g)for(h=f,i=l.length;h'+b+"",{bottom:!0,duration:5e3}):alert(b)}function Ja(a,b){var c=''+(a||"")+'';return b&&(c+=' '+b+""),c}function Ka(a,b){var c=(b.prefix||"")+" "+(b.desc||""),d=Ja(b.prefix,b.desc);Ba(a,d,c,b.onClose,b)}function La(a,b){if(a instanceof RegExp&&b instanceof RegExp){for(var c=["global","multiline","ignoreCase","source"],d=0;d=b&&a<=c:a==b}function Sa(a){var b=a.getScrollInfo(),c=6,d=10,e=a.coordsChar({left:0,top:c+b.top},"local"),f=b.clientHeight-d+b.top,g=a.coordsChar({left:0,top:f},"local");return{top:e.line,bottom:g.line}}function Ta(b,c,d,e,f,g,h,i,j){function k(){b.operation((function(){for(;!p;)l(),m();n()}))}function l(){var a=b.getRange(g.from(),g.to()),c=a.replace(h,i);g.replace(c)}function m(){for(;g.findNext()&&Ra(g.from(),e,f);)if(d||!q||g.from().line!=q.line)return b.scrollIntoView(g.from(),30),b.setSelection(g.from(),g.to()),q=g.from(),void(p=!1);p=!0}function n(a){if(a&&a(),b.focus(),q){b.setCursor(q);var c=b.state.vim;c.exMode=!1,c.lastHPos=c.lastHSPos=q.ch}j&&j()}function o(c,d,e){a.e_stop(c);var f=a.keyName(c);switch(f){case"Y":l(),m();break;case"N":m();break;case"A":var g=j;j=void 0,b.operation(k),j=g;break;case"L":l();case"Q":case"Esc":case"Ctrl-C":case"Ctrl-[":n(e)}return p&&n(e),!0}b.state.vim.exMode=!0;var p=!1,q=g.from();return m(),p?void Ia(b,"No matches for "+h.source):c?void Ka(b,{prefix:"replace with "+i+" (y/n/a/q/l)",onKeyDown:o}):(k(),void(j&&j()))}function Ua(b){var c=b.state.vim,d=ub.macroModeState,e=ub.registerController.getRegister("."),f=d.isPlaying,g=d.lastInsertModeChanges,h=[];if(!f){for(var i=g.inVisualBlock?c.lastSelection.visualBlock.height:1,j=g.changes,h=[],k=0;k1&&(fb(b,c,c.insertModeRepeat-1,!0),c.lastEditInputState.repeatOverride=c.insertModeRepeat),delete c.insertModeRepeat,c.insertMode=!1,b.setCursor(b.getCursor().line,b.getCursor().ch-1),b.setOption("keyMap","vim"),b.setOption("disableInput",!0),b.toggleOverwrite(!1),e.setText(g.changes.join("")),a.signal(b,"vim-mode-change",{mode:"normal"}),d.isRecording&&Za(d)}function Va(a){b.unshift(a)}function Wa(a,b,c,d,e){var f={keys:a,type:b};f[b]=c,f[b+"Args"]=d;for(var g in e)f[g]=e[g];Va(f)}function Xa(b,c,d,e){var f=ub.registerController.getRegister(e);if(":"==e)return f.keyBuffer[0]&&Ib.processCommand(b,f.keyBuffer[0]),void(d.isPlaying=!1);var g=f.keyBuffer,h=0;d.isPlaying=!0,d.replaySearchQueries=f.searchQueries.slice(0);for(var i=0;i|<\w+>|./.exec(l),k=j[0],l=l.substring(j.index+k.length),a.Vim.handleKey(b,k,"macro"),c.insertMode){var m=f.insertModeChanges[h++].changes;ub.macroModeState.lastInsertModeChanges.changes=m,gb(b,m,1),Ua(b)}d.isPlaying=!1}function Ya(a,b){if(!a.isPlaying){var c=a.latestRegister,d=ub.registerController.getRegister(c);d&&d.pushText(b)}}function Za(a){if(!a.isPlaying){var b=a.latestRegister,c=ub.registerController.getRegister(b);c&&c.pushInsertModeChanges&&c.pushInsertModeChanges(a.lastInsertModeChanges)}}function $a(a,b){if(!a.isPlaying){var c=a.latestRegister,d=ub.registerController.getRegister(c);d&&d.pushSearchQuery&&d.pushSearchQuery(b)}}function _a(a,b){var c=ub.macroModeState,d=c.lastInsertModeChanges;if(!c.isPlaying)for(;b;){if(d.expectCursorActivityForChange=!0,"+input"==b.origin||"paste"==b.origin||void 0===b.origin){var e=b.text.join("\n");d.maybeReset&&(d.changes=[],d.maybeReset=!1),d.changes.push(e)}b=b.next}}function ab(a){var b=a.state.vim;if(b.insertMode){var c=ub.macroModeState;if(c.isPlaying)return;var d=c.lastInsertModeChanges;d.expectCursorActivityForChange?d.expectCursorActivityForChange=!1:d.maybeReset=!0}else a.curOp.isVimOp||cb(a,b);b.visualMode&&bb(a)}function bb(a){var b=a.state.vim,c=J(a,R(b.sel.head)),d=L(c,0,1);b.fakeCursor&&b.fakeCursor.clear(),b.fakeCursor=a.markText(c,d,{className:"cm-animate-fat-cursor"})}function cb(b,c){var d=b.getCursor("anchor"),e=b.getCursor("head");if(c.visualMode&&!b.somethingSelected()?ia(b,!1):c.visualMode||c.insertMode||!b.somethingSelected()||(c.visualMode=!0,c.visualLine=!1,a.signal(b,"vim-mode-change",{mode:"visual"})),c.visualMode){var f=T(e,d)?0:-1,g=T(e,d)?-1:0;e=L(e,0,f),d=L(d,0,g),c.sel={anchor:d,head:e},ua(b,c,"<",U(e,d)),ua(b,c,">",V(e,d))}else c.insertMode||(c.lastHPos=b.getCursor().ch)}function db(a){this.keyName=a}function eb(b){function c(){return e.maybeReset&&(e.changes=[],e.maybeReset=!1),e.changes.push(new db(f)),!0}var d=ub.macroModeState,e=d.lastInsertModeChanges,f=a.keyName(b);f&&(f.indexOf("Delete")==-1&&f.indexOf("Backspace")==-1||a.lookupKey(f,"vim-insert",c))}function fb(a,b,c,d){function e(){h?xb.processAction(a,b,b.lastEditActionCommand):xb.evalInput(a,b)}function f(c){if(g.lastInsertModeChanges.changes.length>0){c=b.lastEditActionCommand?c:1;var d=g.lastInsertModeChanges;gb(a,d.changes,c)}}var g=ub.macroModeState;g.isPlaying=!0;var h=!!b.lastEditActionCommand,i=b.inputState;if(b.inputState=b.lastEditInputState,h&&b.lastEditActionCommand.interlaceInsertRepeat)for(var j=0;j"]),qb=[].concat(mb,nb,ob,["-",'"',".",":","/"]),rb={};t("filetype",void 0,"string",["ft"],(function(a,b){if(void 0!==b){if(void 0===a){var c=b.getOption("mode");return"null"==c?"":c}var c=""==a?"null":a;b.setOption("mode",c)}}));var sb=function(){function a(a,b,h){function i(b){var e=++d%c,f=g[e];f&&f.clear(),g[e]=a.setBookmark(b)}var j=d%c,k=g[j];if(k){var l=k.find();l&&!S(l,b)&&i(b)}else i(b);i(h),e=d,f=d-c+1,f<0&&(f=0)}function b(a,b){d+=b,d>e?d=e:d0?1:-1,k=a.getCursor();do if(d+=j,h=g[(c+d)%c],h&&(i=h.find())&&!S(k,i))break;while(df)}return h}var c=100,d=-1,e=0,f=0,g=new Array(c);return{cachedCursor:void 0,add:a,move:b}},tb=function(a){return a?{changes:a.changes,expectCursorActivityForChange:a.expectCursorActivityForChange}:{changes:[],expectCursorActivityForChange:!1}};w.prototype={exitMacroRecordMode:function(){var a=ub.macroModeState;a.onRecordingDone&&a.onRecordingDone(),a.onRecordingDone=void 0,a.isRecording=!1},enterMacroRecordMode:function(a,b){var c=ub.registerController.getRegister(b);c&&(c.clear(),this.latestRegister=b,a.openDialog&&(this.onRecordingDone=a.openDialog("(recording)["+b+"]",null,{bottom:!0})),this.isRecording=!0)}};var ub,vb,wb={buildKeyMap:function(){},getRegisterController:function(){return ub.registerController},resetVimGlobalState_:y,getVimGlobalState_:function(){return ub},maybeInitVimState_:x,suppressErrorLogging:!1,InsertModeKey:db,map:function(a,b,c){Ib.map(a,b,c)},unmap:function(a,b){Ib.unmap(a,b)},setOption:u,getOption:v,defineOption:t,defineEx:function(a,b,c){if(b){if(0!==a.indexOf(b))throw new Error('(Vim.defineEx) "'+b+'" is not a prefix of "'+a+'", command not registered')}else b=a;Hb[a]=c,Ib.commandMap_[b]={name:a,shortName:b,type:"api"}},handleKey:function(a,b,c){var d=this.findKey(a,b,c);if("function"==typeof d)return d()},findKey:function(c,d,e){function f(){var a=ub.macroModeState;if(a.isRecording){if("q"==d)return a.exitMacroRecordMode(),A(c),!0;"mapping"!=e&&Ya(a,d)}}function g(){if(""==d)return A(c),l.visualMode?ia(c):l.insertMode&&Ua(c),!0}function h(b){for(var e;b;)e=/<\w+-.+?>|<\w+>|./.exec(b),d=e[0],b=b.substring(e.index+d.length),a.Vim.handleKey(c,d,"mapping")}function i(){if(g())return!0;for(var a=l.inputState.keyBuffer=l.inputState.keyBuffer+d,e=1==d.length,f=xb.matchCommand(a,b,l.inputState,"insert");a.length>1&&"full"!=f.type;){var a=l.inputState.keyBuffer=a.slice(1),h=xb.matchCommand(a,b,l.inputState,"insert");"none"!=h.type&&(f=h)}if("none"==f.type)return A(c),!1;if("partial"==f.type)return vb&&window.clearTimeout(vb),vb=window.setTimeout((function(){l.insertMode&&l.inputState.keyBuffer&&A(c)}),v("insertModeEscKeysTimeout")),!e;if(vb&&window.clearTimeout(vb),e){for(var i=c.listSelections(),j=0;j0||this.motionRepeat.length>0)&&(a=1,this.prefixRepeat.length>0&&(a*=parseInt(this.prefixRepeat.join(""),10)),this.motionRepeat.length>0&&(a*=parseInt(this.motionRepeat.join(""),10))),a},B.prototype={setText:function(a,b,c){this.keyBuffer=[a||""],this.linewise=!!b,this.blockwise=!!c},pushText:function(a,b){b&&(this.linewise||this.keyBuffer.push("\n"),this.linewise=!0),this.keyBuffer.push(a)},pushInsertModeChanges:function(a){this.insertModeChanges.push(tb(a))},pushSearchQuery:function(a){this.searchQueries.push(a)},clear:function(){this.keyBuffer=[],this.insertModeChanges=[],this.searchQueries=[],this.linewise=!1},toString:function(){return this.keyBuffer.join("")}},D.prototype={pushText:function(a,b,c,d,e){d&&"\n"==c.charAt(0)&&(c=c.slice(1)+"\n"),d&&"\n"!==c.charAt(c.length-1)&&(c+="\n");var f=this.isValidRegister(a)?this.getRegister(a):null;if(!f){switch(b){case"yank":this.registers[0]=new B(c,d,e);break;case"delete":case"change":c.indexOf("\n")==-1?this.registers["-"]=new B(c,d):(this.shiftNumericRegisters_(),this.registers[1]=new B(c,d))}return void this.unnamedRegister.setText(c,d,e)}var g=q(a);g?f.pushText(c,d):f.setText(c,d,e),this.unnamedRegister.setText(f.toString(),d)},getRegister:function(a){return this.isValidRegister(a)?(a=a.toLowerCase(),this.registers[a]||(this.registers[a]=new B),this.registers[a]):this.unnamedRegister},isValidRegister:function(a){return a&&s(a,qb)},shiftNumericRegisters_:function(){for(var a=9;a>=2;a--)this.registers[a]=this.getRegister(""+(a-1))}},E.prototype={nextMatch:function(a,b){var c=this.historyBuffer,d=b?-1:1;null===this.initialPrefix&&(this.initialPrefix=a);for(var e=this.iterator+d;b?e>=0:e=c.length?(this.iterator=c.length,this.initialPrefix):e<0?a:void 0},pushInput:function(a){var b=this.historyBuffer.indexOf(a);b>-1&&this.historyBuffer.splice(b,1),a.length&&this.historyBuffer.push(a)},reset:function(){this.initialPrefix=null,this.iterator=this.historyBuffer.length}};var xb={matchCommand:function(a,b,c,d){var e=N(a,b,d,c);if(!e.full&&!e.partial)return{type:"none"};if(!e.full&&e.partial)return{type:"partial"};for(var f,g=0;g"==f.keys.slice(-11)&&(c.selectedCharacter=P(a)),{type:"full",command:f}},processCommand:function(a,b,c){switch(b.inputState.repeatOverride=c.repeatOverride,c.type){case"motion":this.processMotion(a,b,c);break;case"operator":this.processOperator(a,b,c);break;case"operatorMotion":this.processOperatorMotion(a,b,c);break;case"action":this.processAction(a,b,c);break;case"search":this.processSearch(a,b,c);break;case"ex":case"keyToEx":this.processEx(a,b,c)}},processMotion:function(a,b,c){b.inputState.motion=c.motion,b.inputState.motionArgs=K(c.motionArgs),this.evalInput(a,b)},processOperator:function(a,b,c){var d=b.inputState;if(d.operator){if(d.operator==c.operator)return d.motion="expandToLine",d.motionArgs={linewise:!0},void this.evalInput(a,b);A(a)}d.operator=c.operator,d.operatorArgs=K(c.operatorArgs),b.visualMode&&this.evalInput(a,b)},processOperatorMotion:function(a,b,c){var d=b.visualMode,e=K(c.operatorMotionArgs);e&&d&&e.visualLine&&(b.visualLine=!0),this.processOperator(a,b,c),d||this.processMotion(a,b,c)},processAction:function(a,b,c){var d=b.inputState,e=d.getRepeat(),f=!!e,g=K(c.actionArgs)||{};d.selectedCharacter&&(g.selectedCharacter=d.selectedCharacter),c.operator&&this.processOperator(a,b,c),c.motion&&this.processMotion(a,b,c),(c.motion||c.operator)&&this.evalInput(a,b),g.repeat=e||1,g.repeatIsExplicit=f,g.registerName=d.registerName,A(a),b.lastMotion=null,c.isEdit&&this.recordLastEdit(b,d,c),Ab[c.action](a,g,b)},processSearch:function(b,c,d){function e(a,e,f){ub.searchHistoryController.pushInput(a),ub.searchHistoryController.reset();try{Ma(b,a,e,f)}catch(c){return Ia(b,"Invalid regex: "+a),void A(b)}xb.processMotion(b,c,{type:"motion",motion:"findNext",motionArgs:{forward:!0,toJumplist:d.searchArgs.toJumplist}})}function f(a){b.scrollTo(m.left,m.top),e(a,!0,!0);var c=ub.macroModeState;c.isRecording&&$a(c,a)}function g(c,d,e){var f,g=a.keyName(c);"Up"==g||"Down"==g?(f="Up"==g,d=ub.searchHistoryController.nextMatch(d,f)||"",e(d)):"Left"!=g&&"Right"!=g&&"Ctrl"!=g&&"Alt"!=g&&"Shift"!=g&&ub.searchHistoryController.reset();var h;try{h=Ma(b,d,!0,!0)}catch(a){}h?b.scrollIntoView(Pa(b,!i,h),30):(Qa(b),b.scrollTo(m.left,m.top))}function h(c,d,e){var f=a.keyName(c);"Esc"==f||"Ctrl-C"==f||"Ctrl-["==f||"Backspace"==f&&""==d?(ub.searchHistoryController.pushInput(d),ub.searchHistoryController.reset(),Ma(b,l),Qa(b),b.scrollTo(m.left,m.top),a.e_stop(c),A(b),e(),b.focus()):"Ctrl-U"==f&&(a.e_stop(c),e(""))}if(b.getSearchCursor){var i=d.searchArgs.forward,j=d.searchArgs.wholeWordOnly;Aa(b).setReversed(!i);var k=i?"/":"?",l=Aa(b).getQuery(),m=b.getScrollInfo();switch(d.searchArgs.querySrc){case"prompt":var n=ub.macroModeState;if(n.isPlaying){var o=n.replaySearchQueries.shift();e(o,!0,!1)}else Ka(b,{onClose:f,prefix:k,desc:Fb,onKeyUp:g,onKeyDown:h});break;case"wordUnderCursor":var p=ma(b,!1,!0,!1,!0),q=!0;if(p||(p=ma(b,!1,!0,!1,!1),q=!1),!p)return;var o=b.getLine(p.start.line).substring(p.start.ch,p.end.ch);o=q&&j?"\\b"+o+"\\b":Z(o),ub.jumpList.cachedCursor=b.getCursor(),b.setCursor(p.start),e(o,!0,!1)}}},processEx:function(b,c,d){function e(a){ub.exCommandHistoryController.pushInput(a),ub.exCommandHistoryController.reset(),Ib.processCommand(b,a)}function f(c,d,e){var f,g=a.keyName(c);("Esc"==g||"Ctrl-C"==g||"Ctrl-["==g||"Backspace"==g&&""==d)&&(ub.exCommandHistoryController.pushInput(d),ub.exCommandHistoryController.reset(),a.e_stop(c),A(b),e(),b.focus()),"Up"==g||"Down"==g?(f="Up"==g,d=ub.exCommandHistoryController.nextMatch(d,f)||"",e(d)):"Ctrl-U"==g?(a.e_stop(c),e("")):"Left"!=g&&"Right"!=g&&"Ctrl"!=g&&"Alt"!=g&&"Shift"!=g&&ub.exCommandHistoryController.reset()}"keyToEx"==d.type?Ib.processCommand(b,d.exArgs.input):c.visualMode?Ka(b,{onClose:e,prefix:":",value:"'<,'>",onKeyDown:f}):Ka(b,{onClose:e,prefix:":",onKeyDown:f})},evalInput:function(a,b){var c,e,f,g=b.inputState,h=g.motion,i=g.motionArgs||{},j=g.operator,k=g.operatorArgs||{},l=g.registerName,m=b.sel,n=R(b.visualMode?J(a,m.head):a.getCursor("head")),o=R(b.visualMode?J(a,m.anchor):a.getCursor("anchor")),p=R(n),q=R(o);if(j&&this.recordLastEdit(b,g),f=void 0!==g.repeatOverride?g.repeatOverride:g.getRepeat(),f>0&&i.explicitRepeat?i.repeatIsExplicit=!0:(i.noRepeat||!i.explicitRepeat&&0===f)&&(f=1,i.repeatIsExplicit=!1),g.selectedCharacter&&(i.selectedCharacter=k.selectedCharacter=g.selectedCharacter),i.repeat=f,A(a),h){var r=yb[h](a,n,i,b);if(b.lastMotion=yb[h],!r)return;if(i.toJumplist){var s=ub.jumpList,t=s.cachedCursor;t?(na(a,t,r),delete s.cachedCursor):na(a,n,r)}r instanceof Array?(e=r[0],c=r[1]):c=r,c||(c=R(n)),b.visualMode?(b.visualBlock&&c.ch===1/0||(c=J(a,c,b.visualBlock)),e&&(e=J(a,e,!0)),e=e||q,m.anchor=e,m.head=c,fa(a),ua(a,b,"<",T(e,c)?e:c),ua(a,b,">",T(e,c)?c:e)):j||(c=J(a,c),a.setCursor(c.line,c.ch))}if(j){if(k.lastSel){e=q;var u=k.lastSel,v=Math.abs(u.head.line-u.anchor.line),w=Math.abs(u.head.ch-u.anchor.ch);c=u.visualLine?d(q.line+v,q.ch):u.visualBlock?d(q.line+v,q.ch+w):u.head.line==u.anchor.line?d(q.line,q.ch+w):d(q.line+v,q.ch),b.visualMode=!0,b.visualLine=u.visualLine,b.visualBlock=u.visualBlock,m=b.sel={anchor:e,head:c},fa(a)}else b.visualMode&&(k.lastSel={anchor:R(m.anchor),head:R(m.head),visualBlock:b.visualBlock,visualLine:b.visualLine});var x,y,z,B,C;if(b.visualMode){if(x=U(m.head,m.anchor),y=V(m.head,m.anchor),z=b.visualLine||k.linewise,B=b.visualBlock?"block":z?"line":"char",C=ga(a,{anchor:x,head:y},B),z){var D=C.ranges;if("block"==B)for(var E=0;Ek&&f.line==k?this.moveToEol(a,b,c,e):(c.toFirstChar&&(g=la(a.getLine(i)),e.lastHPos=g),e.lastHSPos=a.charCoords(d(i,g),"div").left,d(i,g))},moveByDisplayLines:function(a,b,c,e){var f=b;switch(e.lastMotion){case this.moveByDisplayLines:case this.moveByScroll:case this.moveByLines:case this.moveToColumn:case this.moveToEol:break;default:e.lastHSPos=a.charCoords(f,"div").left}var g=c.repeat,h=a.findPosV(f,c.forward?g:-g,"line",e.lastHSPos);if(h.hitSide)if(c.forward)var i=a.charCoords(h,"div"),j={top:i.top+8,left:e.lastHSPos},h=a.coordsChar(j,"div");else{var k=a.charCoords(d(a.firstLine(),0),"div");k.left=e.lastHSPos,h=a.coordsChar(k,"div")}return e.lastHPos=h.ch,h},moveByPage:function(a,b,c){var d=b,e=c.repeat;return a.findPosV(d,c.forward?e:-e,"page")},moveByParagraph:function(a,b,c){var d=c.forward?1:-1;return wa(a,b,c.repeat,d)},moveByScroll:function(a,b,c,d){var e=a.getScrollInfo(),f=null,g=c.repeat;g||(g=e.clientHeight/(2*a.defaultTextHeight()));var h=a.charCoords(b,"local");c.repeat=g;var f=yb.moveByDisplayLines(a,b,c,d);if(!f)return null;var i=a.charCoords(f,"local");return a.scrollTo(null,e.top+i.top-h.top),f},moveByWords:function(a,b,c){return ra(a,b,c.repeat,!!c.forward,!!c.wordEnd,!!c.bigWord)},moveTillCharacter:function(a,b,c){var d=c.repeat,e=sa(a,d,c.forward,c.selectedCharacter),f=c.forward?-1:1;return oa(f,c),e?(e.ch+=f,e):null},moveToCharacter:function(a,b,c){var d=c.repeat;return oa(0,c),sa(a,d,c.forward,c.selectedCharacter)||b},moveToSymbol:function(a,b,c){var d=c.repeat;return pa(a,d,c.forward,c.selectedCharacter)||b},moveToColumn:function(a,b,c,d){var e=c.repeat;return d.lastHPos=e-1,d.lastHSPos=a.charCoords(b,"div").left,ta(a,e)},moveToEol:function(a,b,c,e){var f=b;e.lastHPos=1/0;var g=d(f.line+c.repeat-1,1/0),h=a.clipPos(g);return h.ch--,e.lastHSPos=a.charCoords(h,"div").left,g},moveToFirstNonWhiteSpaceCharacter:function(a,b){var c=b;return d(c.line,la(a.getLine(c.line)))},moveToMatchedSymbol:function(a,b){var c,e=b,f=e.line,g=e.ch,h=a.getLine(f);do if(c=h.charAt(g++),c&&o(c)){var i=a.getTokenTypeAt(d(f,g));if("string"!==i&&"comment"!==i)break}while(c);if(c){var j=a.findMatchingBracket(d(f,g));return j.to}return e},moveToStartOfLine:function(a,b){return d(b.line,0)},moveToLineOrEdgeOfDocument:function(a,b,c){var e=c.forward?a.lastLine():a.firstLine();return c.repeatIsExplicit&&(e=c.repeat-a.getOption("firstLineNumber")),d(e,la(a.getLine(e)))},textObjectManipulation:function(a,b,c,d){var e={"(":")",")":"(","{":"}","}":"{","[":"]","]":"["},f={"'":!0,'"':!0},g=c.selectedCharacter;"b"==g?g="(":"B"==g&&(g="{");var h,i=!c.textObjectInner;if(e[g])h=xa(a,b,g,i);else if(f[g])h=ya(a,b,g,i);else if("W"===g)h=ma(a,i,!0,!0);else if("w"===g)h=ma(a,i,!0,!1);else{if("p"!==g)return null;if(h=wa(a,b,c.repeat,0,i),c.linewise=!0,d.visualMode)d.visualLine||(d.visualLine=!0);else{var j=d.inputState.operatorArgs;j&&(j.linewise=!0),h.end.line--}}return a.state.vim.visualMode?ea(a,h.start,h.end):[h.start,h.end]},repeatLastCharacterSearch:function(a,b,c){var d=ub.lastCharacterSearch,e=c.repeat,f=c.forward===d.forward,g=(d.increment?1:0)*(f?-1:1);a.moveH(-g,"char"),c.inclusive=!!f;var h=sa(a,e,f,d.selectedCharacter);return h?(h.ch+=g,h):(a.moveH(g,"char"),b)}},zb={change:function(b,c,e){var f,g,h=b.state.vim;if(ub.macroModeState.lastInsertModeChanges.inVisualBlock=h.visualBlock,h.visualMode){g=b.getSelection();var i=G("",e.length);b.replaceSelections(i),f=U(e[0].head,e[0].anchor)}else{var j=e[0].anchor,k=e[0].head;g=b.getRange(j,k);var l=h.lastEditInputState||{};if("moveByWords"==l.motion&&!r(g)){var m=/\s+$/.exec(g);m&&l.motionArgs&&l.motionArgs.forward&&(k=L(k,0,-m[0].length),g=g.slice(0,-m[0].length))}var n=new d(j.line-1,Number.MAX_VALUE),o=b.firstLine()==b.lastLine();k.line>b.lastLine()&&c.linewise&&!o?b.replaceRange("",n,k):b.replaceRange("",j,k),c.linewise&&(o||(b.setCursor(n),a.commands.newlineAndIndent(b)),j.ch=Number.MAX_VALUE),f=j}ub.registerController.pushText(c.registerName,"change",g,c.linewise,e.length>1),Ab.enterInsertMode(b,{head:f},b.state.vim)},delete:function(a,b,c){var e,f,g=a.state.vim;if(g.visualBlock){f=a.getSelection();var h=G("",c.length);a.replaceSelections(h),e=c[0].anchor}else{var i=c[0].anchor,j=c[0].head;b.linewise&&j.line!=a.firstLine()&&i.line==a.lastLine()&&i.line==j.line-1&&(i.line==a.firstLine()?i.ch=0:i=d(i.line-1,X(a,i.line-1))), f=a.getRange(i,j),a.replaceRange("",i,j),e=i,b.linewise&&(e=yb.moveToFirstNonWhiteSpaceCharacter(a,i))}return ub.registerController.pushText(b.registerName,"delete",f,b.linewise,g.visualBlock),J(a,e)},indent:function(a,b,c){var d=a.state.vim,e=c[0].anchor.line,f=d.visualBlock?c[c.length-1].anchor.line:c[0].head.line,g=d.visualMode?b.repeat:1;b.linewise&&f--;for(var h=e;h<=f;h++)for(var i=0;ij.top?(i.line+=(h-j.top)/e,i.line=Math.ceil(i.line),a.setCursor(i),j=a.charCoords(i,"local"),a.scrollTo(null,j.top)):a.scrollTo(null,h);else{var k=h+a.getScrollInfo().clientHeight;k=g.anchor.line?L(g.head,0,1):d(g.anchor.line,0);else if("inplace"==f&&e.visualMode)return;b.setOption("disableInput",!1),c&&c.replace?(b.toggleOverwrite(!0),b.setOption("keyMap","vim-replace"),a.signal(b,"vim-mode-change",{mode:"replace"})):(b.toggleOverwrite(!1),b.setOption("keyMap","vim-insert"),a.signal(b,"vim-mode-change",{mode:"insert"})),ub.macroModeState.isPlaying||(b.on("change",_a),a.on(b.getInputField(),"keydown",eb)),e.visualMode&&ia(b),aa(b,h,i)}},toggleVisualMode:function(b,c,e){var f,g=c.repeat,h=b.getCursor();e.visualMode?e.visualLine^c.linewise||e.visualBlock^c.blockwise?(e.visualLine=!!c.linewise,e.visualBlock=!!c.blockwise,a.signal(b,"vim-mode-change",{mode:"visual",subMode:e.visualLine?"linewise":e.visualBlock?"blockwise":""}),fa(b)):ia(b):(e.visualMode=!0,e.visualLine=!!c.linewise,e.visualBlock=!!c.blockwise,f=J(b,d(h.line,h.ch+g-1),!0),e.sel={anchor:h,head:f},a.signal(b,"vim-mode-change",{mode:"visual",subMode:e.visualLine?"linewise":e.visualBlock?"blockwise":""}),fa(b),ua(b,e,"<",U(h,f)),ua(b,e,">",V(h,f)))},reselectLastSelection:function(b,c,d){var e=d.lastSelection;if(d.visualMode&&da(b,d),e){var f=e.anchorMark.find(),g=e.headMark.find();if(!f||!g)return;d.sel={anchor:f,head:g},d.visualMode=!0,d.visualLine=e.visualLine,d.visualBlock=e.visualBlock,fa(b),ua(b,d,"<",U(f,g)),ua(b,d,">",V(f,g)),a.signal(b,"vim-mode-change",{mode:"visual",subMode:d.visualLine?"linewise":d.visualBlock?"blockwise":""})}},joinLines:function(a,b,c){var e,f;if(c.visualMode){if(e=a.getCursor("anchor"),f=a.getCursor("head"),T(f,e)){var g=f;f=e,e=g}f.ch=X(a,f.line)-1}else{var h=Math.max(b.repeat,2);e=a.getCursor(),f=J(a,d(e.line+h-1,1/0))}for(var i=0,j=e.line;j1)var g=Array(b.repeat+1).join(g);var o=f.linewise,p=f.blockwise;if(o)c.visualMode?g=c.visualLine?g.slice(0,-1):"\n"+g.slice(0,g.length-1)+"\n":b.after?(g="\n"+g.slice(0,g.length-1),e.ch=X(a,e.line)):e.ch=0;else{if(p){g=g.split("\n");for(var q=0;qa.lastLine()&&a.replaceRange("\n",d(A,0));var B=X(a,A);Bk.length&&(f=k.length),g=d(i.line,f)}if("\n"==h)e.visualMode||b.replaceRange("",i,g),(a.commands.newlineAndIndentContinueComment||a.commands.newlineAndIndent)(b);else{var l=b.getRange(i,g);if(l=l.replace(/[^\n]/g,h),e.visualBlock){var m=new Array(b.getOption("tabSize")+1).join(" ");l=b.getSelection(),l=l.replace(/\t/g,m).replace(/[^\n]/g,h).split("\n"),b.replaceSelections(l)}else b.replaceRange(l,i,g);e.visualMode?(i=T(j[0].anchor,j[0].head)?j[0].anchor:j[0].head,b.setCursor(i),ia(b,!1)):b.setCursor(L(g,0,-1))}},incrementNumberToken:function(a,b){for(var c,e,f,g,h,i=a.getCursor(),j=a.getLine(i.line),k=/-?\d+/g;null!==(c=k.exec(j))&&(h=c[0],e=c.index,f=e+h.length,!(i.ch=1)return!0}else a.nextCh===a.reverseSymb&&a.depth--;return!1}},section:{init:function(a){a.curMoveThrough=!0,a.symb=(a.forward?"]":"[")===a.symb?"{":"}"},isComplete:function(a){return 0===a.index&&a.nextCh===a.symb}},comment:{isComplete:function(a){var b="*"===a.lastCh&&"/"===a.nextCh;return a.lastCh=a.nextCh,b}},method:{init:function(a){a.symb="m"===a.symb?"{":"}",a.reverseSymb="{"===a.symb?"}":"{"},isComplete:function(a){return a.nextCh===a.symb}},preprocess:{init:function(a){a.index=0},isComplete:function(a){if("#"===a.nextCh){var b=a.lineText.match(/#(\w+)/)[1];if("endif"===b){if(a.forward&&0===a.depth)return!0;a.depth++}else if("if"===b){if(!a.forward&&0===a.depth)return!0;a.depth--}if("else"===b&&0===a.depth)return!0}return!1}}};t("pcre",!0,"boolean"),za.prototype={getQuery:function(){return ub.query},setQuery:function(a){ub.query=a},getOverlay:function(){return this.searchOverlay},setOverlay:function(a){this.searchOverlay=a},isReversed:function(){return ub.isReversed},setReversed:function(a){ub.isReversed=a},getScrollbarAnnotate:function(){return this.annotate},setScrollbarAnnotate:function(a){this.annotate=a}};var Db={"\\n":"\n","\\r":"\r","\\t":"\t"},Eb={"\\/":"/","\\\\":"\\","\\n":"\n","\\r":"\r","\\t":"\t"},Fb="(Javascript regexp)",Gb=function(){this.buildCommandMap_()};Gb.prototype={processCommand:function(a,b,c){var d=this;a.operation((function(){a.curOp.isVimOp=!0,d._processCommand(a,b,c)}))},_processCommand:function(b,c,d){var e=b.state.vim,f=ub.registerController.getRegister(":"),g=f.toString();e.visualMode&&ia(b);var h=new a.StringStream(c);f.setText(c);var i=d||{};i.input=c;try{this.parseInput_(b,h,i)}catch(a){throw Ia(b,a),a}var j,k;if(i.commandName){if(j=this.matchCommand_(i.commandName)){if(k=j.name,j.excludeFromCommandHistory&&f.setText(g),this.parseCommandArgs_(h,i,j),"exToKey"==j.type){for(var l=0;l0;b--){var c=a.substring(0,b);if(this.commandMap_[c]){var d=this.commandMap_[c];if(0===d.name.indexOf(a))return d}}return null},buildCommandMap_:function(){this.commandMap_={};for(var a=0;a
";if(c){var f;c=c.join("");for(var g=0;g"}}else for(var f in d){var i=d[f].toString();i.length&&(e+='"'+f+" "+i+"
")}Ia(a,e)},sort:function(b,c){function e(){if(c.argString){var b=new a.StringStream(c.argString);if(b.eat("!")&&(g=!0),b.eol())return;if(!b.eatSpace())return"Invalid arguments";var d=b.match(/[a-z]+/);if(d){d=d[0],h=d.indexOf("i")!=-1,i=d.indexOf("u")!=-1;var e=d.indexOf("d")!=-1&&1,f=d.indexOf("x")!=-1&&1,k=d.indexOf("o")!=-1&&1;if(e+f+k>1)return"Invalid arguments";j=e&&"decimal"||f&&"hex"||k&&"octal"}if(b.match(/\/.*\//))return"patterns not supported"}}function f(a,b){if(g){var c;c=a,a=b,b=c}h&&(a=a.toLowerCase(),b=b.toLowerCase());var d=j&&q.exec(a),e=j&&q.exec(b);return d?(d=parseInt((d[1]+d[2]).toLowerCase(),r),e=parseInt((e[1]+e[2]).toLowerCase(),r),d-e):a")}if(!d)return void Ia(a,k);var n=0,o=function(){if(n=k)return void Ia(b,"Invalid argument: "+c.argString.substring(f));for(var l=0;l<=k-j;l++){var m=String.fromCharCode(j+l);delete d.marks[m]}}else delete d.marks[g]}}},Ib=new Gb;return a.keyMap.vim={attach:h,detach:g,call:i},t("insertModeEscKeysTimeout",200,"number"),a.keyMap["vim-insert"]={fallthrough:["default"],attach:h,detach:g,call:i},a.keyMap["vim-replace"]={Backspace:"goCharLeft",fallthrough:["vim-insert"],attach:h,detach:g,call:i},y(),wb};a.Vim=e()})); \ No newline at end of file diff --git a/media/editors/codemirror/lib/codemirror.css b/media/editors/codemirror/lib/codemirror.css index 18b0bf70dbf23..d7821d17dfe3c 100644 --- a/media/editors/codemirror/lib/codemirror.css +++ b/media/editors/codemirror/lib/codemirror.css @@ -206,9 +206,6 @@ div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;} display: inline-block; vertical-align: top; margin-bottom: -30px; - /* Hack to make IE7 behave */ - *zoom:1; - *display:inline; } .CodeMirror-gutter-wrapper { position: absolute; @@ -327,9 +324,6 @@ div.CodeMirror-dragcursors { background: rgba(255, 255, 0, .4); } -/* IE7 hack to prevent it from returning funny offsetTops on the spans */ -.CodeMirror span { *vertical-align: text-bottom; } - /* Used to force a border model for a node */ .cm-force-border { padding-right: .1px; } diff --git a/media/editors/codemirror/lib/codemirror.js b/media/editors/codemirror/lib/codemirror.js index 32d974398163f..c6f2d835233de 100644 --- a/media/editors/codemirror/lib/codemirror.js +++ b/media/editors/codemirror/lib/codemirror.js @@ -7,8958 +7,9089 @@ // You can find some technical background for some of the code below // at http://marijnhaverbeke.nl/blog/#cm-internals . -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - module.exports = mod(); - else if (typeof define == "function" && define.amd) // AMD - return define([], mod); - else // Plain browser env - (this || window).CodeMirror = mod(); -})(function() { - "use strict"; - - // BROWSER SNIFFING - - // Kludges for bugs and behavior differences that can't be feature - // detected are enabled based on userAgent etc sniffing. - var userAgent = navigator.userAgent; - var platform = navigator.platform; - - var gecko = /gecko\/\d/i.test(userAgent); - var ie_upto10 = /MSIE \d/.test(userAgent); - var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent); - var ie = ie_upto10 || ie_11up; - var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]); - var webkit = /WebKit\//.test(userAgent); - var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent); - var chrome = /Chrome\//.test(userAgent); - var presto = /Opera\//.test(userAgent); - var safari = /Apple Computer/.test(navigator.vendor); - var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent); - var phantom = /PhantomJS/.test(userAgent); - - var ios = /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent); - // This is woefully incomplete. Suggestions for alternative methods welcome. - var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent); - var mac = ios || /Mac/.test(platform); - var chromeOS = /\bCrOS\b/.test(userAgent); - var windows = /win/i.test(platform); - - var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/); - if (presto_version) presto_version = Number(presto_version[1]); - if (presto_version && presto_version >= 15) { presto = false; webkit = true; } - // Some browsers use the wrong event properties to signal cmd/ctrl on OS X - var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)); - var captureRightClick = gecko || (ie && ie_version >= 9); - - // Optimize some code when these features are not used. - var sawReadOnlySpans = false, sawCollapsedSpans = false; - - // EDITOR CONSTRUCTOR - - // A CodeMirror instance represents an editor. This is the object - // that user code is usually dealing with. - - function CodeMirror(place, options) { - if (!(this instanceof CodeMirror)) return new CodeMirror(place, options); - - this.options = options = options ? copyObj(options) : {}; - // Determine effective options based on given values and defaults. - copyObj(defaults, options, false); - setGuttersForLineNumbers(options); - - var doc = options.value; - if (typeof doc == "string") doc = new Doc(doc, options.mode, null, options.lineSeparator); - this.doc = doc; - - var input = new CodeMirror.inputStyles[options.inputStyle](this); - var display = this.display = new Display(place, doc, input); - display.wrapper.CodeMirror = this; - updateGutters(this); - themeChanged(this); - if (options.lineWrapping) - this.display.wrapper.className += " CodeMirror-wrap"; - if (options.autofocus && !mobile) display.input.focus(); - initScrollbars(this); - - this.state = { - keyMaps: [], // stores maps added by addKeyMap - overlays: [], // highlighting overlays, as added by addOverlay - modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info - overwrite: false, - delayingBlurEvent: false, - focused: false, - suppressEdits: false, // used to disable editing during key handlers when in readOnly mode - pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll - selectingText: false, - draggingText: false, - highlight: new Delayed(), // stores highlight worker timeout - keySeq: null, // Unfinished key sequence - specialChars: null - }; - - var cm = this; - - // Override magic textarea content restore that IE sometimes does - // on our hidden textarea on reload - if (ie && ie_version < 11) setTimeout(function() { cm.display.input.reset(true); }, 20); - - registerEventHandlers(this); - ensureGlobalHandlers(); - - startOperation(this); - this.curOp.forceUpdate = true; - attachDoc(this, doc); - - if ((options.autofocus && !mobile) || cm.hasFocus()) - setTimeout(bind(onFocus, this), 20); - else - onBlur(this); - - for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt)) - optionHandlers[opt](this, options[opt], Init); - maybeUpdateLineNumberWidth(this); - if (options.finishInit) options.finishInit(this); - for (var i = 0; i < initHooks.length; ++i) initHooks[i](this); - endOperation(this); - // Suppress optimizelegibility in Webkit, since it breaks text - // measuring on line wrapping boundaries. - if (webkit && options.lineWrapping && - getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") - display.lineDiv.style.textRendering = "auto"; - } - - // DISPLAY CONSTRUCTOR - - // The display handles the DOM integration, both for input reading - // and content drawing. It holds references to DOM nodes and - // display-related state. - - function Display(place, doc, input) { - var d = this; - this.input = input; - - // Covers bottom-right square when both scrollbars are present. - d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); - d.scrollbarFiller.setAttribute("cm-not-content", "true"); - // Covers bottom of gutter when coverGutterNextToScrollbar is on - // and h scrollbar is present. - d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); - d.gutterFiller.setAttribute("cm-not-content", "true"); - // Will contain the actual code, positioned to cover the viewport. - d.lineDiv = elt("div", null, "CodeMirror-code"); - // Elements are added to these to represent selection and cursors. - d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); - d.cursorDiv = elt("div", null, "CodeMirror-cursors"); - // A visibility: hidden element used to find the size of things. - d.measure = elt("div", null, "CodeMirror-measure"); - // When lines outside of the viewport are measured, they are drawn in this. - d.lineMeasure = elt("div", null, "CodeMirror-measure"); - // Wraps everything that needs to exist inside the vertically-padded coordinate system - d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], - null, "position: relative; outline: none"); - // Moved around its parent to cover visible view. - d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative"); - // Set to the height of the document, allowing scrolling. - d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); - d.sizerWidth = null; - // Behavior of elts with overflow: auto and padding is - // inconsistent across browsers. This is used to ensure the - // scrollable area is big enough. - d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;"); - // Will contain the gutters, if any. - d.gutters = elt("div", null, "CodeMirror-gutters"); - d.lineGutter = null; - // Actual scrollable element. - d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); - d.scroller.setAttribute("tabIndex", "-1"); - // The element in which the editor lives. - d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); - - // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) - if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } - if (!webkit && !(gecko && mobile)) d.scroller.draggable = true; - - if (place) { - if (place.appendChild) place.appendChild(d.wrapper); - else place(d.wrapper); - } - - // Current rendered range (may be bigger than the view window). - d.viewFrom = d.viewTo = doc.first; - d.reportedViewFrom = d.reportedViewTo = doc.first; - // Information about the rendered lines. - d.view = []; - d.renderedView = null; - // Holds info about a single rendered line when it was rendered - // for measurement, while not in view. - d.externalMeasured = null; - // Empty space (in pixels) above the view - d.viewOffset = 0; - d.lastWrapHeight = d.lastWrapWidth = 0; - d.updateLineNumbers = null; - - d.nativeBarWidth = d.barHeight = d.barWidth = 0; - d.scrollbarsClipped = false; - - // Used to only resize the line number gutter when necessary (when - // the amount of lines crosses a boundary that makes its width change) - d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; - // Set to true when a non-horizontal-scrolling line widget is - // added. As an optimization, line widget aligning is skipped when - // this is false. - d.alignWidgets = false; - - d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; - - // Tracks the maximum line length so that the horizontal scrollbar - // can be kept static when scrolling. - d.maxLine = null; - d.maxLineLength = 0; - d.maxLineChanged = false; - - // Used for measuring wheel scrolling granularity - d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; - - // True when shift is held down. - d.shift = false; - - // Used to track whether anything happened since the context menu - // was opened. - d.selForContextMenu = null; - - d.activeTouch = null; - - input.init(d); - } - - // STATE UPDATES - - // Used to get the editor into a consistent state again when options change. - - function loadMode(cm) { - cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption); - resetModeState(cm); - } - - function resetModeState(cm) { - cm.doc.iter(function(line) { - if (line.stateAfter) line.stateAfter = null; - if (line.styles) line.styles = null; - }); - cm.doc.frontier = cm.doc.first; - startWorker(cm, 100); - cm.state.modeGen++; - if (cm.curOp) regChange(cm); - } - - function wrappingChanged(cm) { - if (cm.options.lineWrapping) { - addClass(cm.display.wrapper, "CodeMirror-wrap"); - cm.display.sizer.style.minWidth = ""; - cm.display.sizerWidth = null; +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.CodeMirror = factory()); +}(this, (function () { 'use strict'; + +// Kludges for bugs and behavior differences that can't be feature +// detected are enabled based on userAgent etc sniffing. +var userAgent = navigator.userAgent +var platform = navigator.platform + +var gecko = /gecko\/\d/i.test(userAgent) +var ie_upto10 = /MSIE \d/.test(userAgent) +var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent) +var ie = ie_upto10 || ie_11up +var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]) +var webkit = /WebKit\//.test(userAgent) +var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent) +var chrome = /Chrome\//.test(userAgent) +var presto = /Opera\//.test(userAgent) +var safari = /Apple Computer/.test(navigator.vendor) +var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent) +var phantom = /PhantomJS/.test(userAgent) + +var ios = /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent) +// This is woefully incomplete. Suggestions for alternative methods welcome. +var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent) +var mac = ios || /Mac/.test(platform) +var chromeOS = /\bCrOS\b/.test(userAgent) +var windows = /win/i.test(platform) + +var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/) +if (presto_version) { presto_version = Number(presto_version[1]) } +if (presto_version && presto_version >= 15) { presto = false; webkit = true } +// Some browsers use the wrong event properties to signal cmd/ctrl on OS X +var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)) +var captureRightClick = gecko || (ie && ie_version >= 9) + +function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") } + +var rmClass = function(node, cls) { + var current = node.className + var match = classTest(cls).exec(current) + if (match) { + var after = current.slice(match.index + match[0].length) + node.className = current.slice(0, match.index) + (after ? match[1] + after : "") + } +} + +function removeChildren(e) { + for (var count = e.childNodes.length; count > 0; --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 } + if (style) { e.style.cssText = style } + if (typeof content == "string") { e.appendChild(document.createTextNode(content)) } + else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]) } } + return e +} + +var range +if (document.createRange) { range = function(node, start, end, endNode) { + var r = document.createRange() + r.setEnd(endNode || node, end) + r.setStart(node, start) + return r +} } +else { range = function(node, start, end) { + var r = document.body.createTextRange() + try { r.moveToElementText(node.parentNode) } + catch(e) { return r } + r.collapse(true) + r.moveEnd("character", end) + r.moveStart("character", start) + return r +} } + +function contains(parent, child) { + if (child.nodeType == 3) // Android browser always returns false when child is a textnode + { child = child.parentNode } + if (parent.contains) + { return parent.contains(child) } + do { + if (child.nodeType == 11) { child = child.host } + if (child == parent) { return true } + } while (child = child.parentNode) +} + +var activeElt = function() { + var activeElement = document.activeElement + while (activeElement && activeElement.root && activeElement.root.activeElement) + { activeElement = activeElement.root.activeElement } + return activeElement +} +// Older versions of IE throws unspecified error when touching +// document.activeElement in some cases (during loading, in iframe) +if (ie && ie_version < 11) { activeElt = function() { + try { return document.activeElement } + catch(e) { return document.body } +} } + +function addClass(node, cls) { + var current = node.className + if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls } +} +function joinClasses(a, b) { + var as = a.split(" ") + for (var i = 0; i < as.length; i++) + { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i] } } + return b +} + +var selectInput = function(node) { node.select() } +if (ios) // Mobile Safari apparently has a bug where select() is broken. + { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length } } +else if (ie) // Suppress mysterious IE10 errors + { selectInput = function(node) { try { node.select() } catch(_e) {} } } + +function bind(f) { + var args = Array.prototype.slice.call(arguments, 1) + return function(){return f.apply(null, args)} +} + +function copyObj(obj, target, overwrite) { + if (!target) { target = {} } + for (var prop in obj) + { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) + { target[prop] = obj[prop] } } + return target +} + +// Counts the column offset in a string, taking tabs into account. +// Used mostly to find indentation. +function countColumn(string, end, tabSize, startIndex, startValue) { + if (end == null) { + end = string.search(/[^\s\u00a0]/) + if (end == -1) { end = string.length } + } + for (var i = startIndex || 0, n = startValue || 0;;) { + var nextTab = string.indexOf("\t", i) + if (nextTab < 0 || nextTab >= end) + { return n + (end - i) } + n += nextTab - i + n += tabSize - (n % tabSize) + i = nextTab + 1 + } +} + +function Delayed() {this.id = null} +Delayed.prototype.set = function(ms, f) { + clearTimeout(this.id) + this.id = setTimeout(f, ms) +} + +function indexOf(array, elt) { + for (var i = 0; i < array.length; ++i) + { if (array[i] == elt) { return i } } + return -1 +} + +// Number of pixels added to scroller and sizer to hide scrollbar +var scrollerGap = 30 + +// Returned or thrown by various protocols to signal 'I'm not +// handling this'. +var Pass = {toString: function(){return "CodeMirror.Pass"}} + +// Reused option objects for setSelection & friends +var sel_dontScroll = {scroll: false}; +var sel_mouse = {origin: "*mouse"}; +var sel_move = {origin: "+move"}; +// The inverse of countColumn -- find the offset that corresponds to +// a particular column. +function findColumn(string, goal, tabSize) { + for (var pos = 0, col = 0;;) { + var nextTab = string.indexOf("\t", pos) + if (nextTab == -1) { nextTab = string.length } + var skipped = nextTab - pos + if (nextTab == string.length || col + skipped >= goal) + { return pos + Math.min(skipped, goal - col) } + col += nextTab - pos + col += tabSize - (col % tabSize) + pos = nextTab + 1 + if (col >= goal) { return pos } + } +} + +var spaceStrs = [""] +function spaceStr(n) { + while (spaceStrs.length <= n) + { spaceStrs.push(lst(spaceStrs) + " ") } + return spaceStrs[n] +} + +function lst(arr) { return arr[arr.length-1] } + +function map(array, f) { + var out = [] + for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i) } + return out +} + +function insertSorted(array, value, score) { + var pos = 0, priority = score(value) + while (pos < array.length && score(array[pos]) <= priority) { pos++ } + array.splice(pos, 0, value) +} + +function nothing() {} + +function createObj(base, props) { + var inst + if (Object.create) { + inst = Object.create(base) + } else { + nothing.prototype = base + inst = new nothing() + } + if (props) { copyObj(props, inst) } + return inst +} + +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 > "\x80" && + (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)) +} +function isWordChar(ch, helper) { + if (!helper) { return isWordCharBasic(ch) } + if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true } + return helper.test(ch) +} + +function isEmpty(obj) { + for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } } + return true +} + +// Extending unicode characters. A series of a non-extending char + +// any number of extending chars is treated as a single unit as far +// as editing and measuring is concerned. This is not fully correct, +// since some scripts/fonts/browsers also treat other configurations +// of code points as a group. +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 ch.charCodeAt(0) >= 768 && extendingChars.test(ch) } + +// The display handles the DOM integration, both for input reading +// and content drawing. It holds references to DOM nodes and +// display-related state. + +function Display(place, doc, input) { + var d = this + this.input = input + + // Covers bottom-right square when both scrollbars are present. + d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler") + d.scrollbarFiller.setAttribute("cm-not-content", "true") + // Covers bottom of gutter when coverGutterNextToScrollbar is on + // and h scrollbar is present. + d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler") + d.gutterFiller.setAttribute("cm-not-content", "true") + // Will contain the actual code, positioned to cover the viewport. + d.lineDiv = elt("div", null, "CodeMirror-code") + // Elements are added to these to represent selection and cursors. + d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1") + d.cursorDiv = elt("div", null, "CodeMirror-cursors") + // A visibility: hidden element used to find the size of things. + d.measure = elt("div", null, "CodeMirror-measure") + // When lines outside of the viewport are measured, they are drawn in this. + d.lineMeasure = elt("div", null, "CodeMirror-measure") + // Wraps everything that needs to exist inside the vertically-padded coordinate system + d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], + null, "position: relative; outline: none") + // Moved around its parent to cover visible view. + d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative") + // Set to the height of the document, allowing scrolling. + d.sizer = elt("div", [d.mover], "CodeMirror-sizer") + d.sizerWidth = null + // Behavior of elts with overflow: auto and padding is + // inconsistent across browsers. This is used to ensure the + // scrollable area is big enough. + d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;") + // Will contain the gutters, if any. + d.gutters = elt("div", null, "CodeMirror-gutters") + d.lineGutter = null + // Actual scrollable element. + d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll") + d.scroller.setAttribute("tabIndex", "-1") + // The element in which the editor lives. + d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror") + + // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) + if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0 } + if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true } + + if (place) { + if (place.appendChild) { place.appendChild(d.wrapper) } + else { place(d.wrapper) } + } + + // Current rendered range (may be bigger than the view window). + d.viewFrom = d.viewTo = doc.first + d.reportedViewFrom = d.reportedViewTo = doc.first + // Information about the rendered lines. + d.view = [] + d.renderedView = null + // Holds info about a single rendered line when it was rendered + // for measurement, while not in view. + d.externalMeasured = null + // Empty space (in pixels) above the view + d.viewOffset = 0 + d.lastWrapHeight = d.lastWrapWidth = 0 + d.updateLineNumbers = null + + d.nativeBarWidth = d.barHeight = d.barWidth = 0 + d.scrollbarsClipped = false + + // Used to only resize the line number gutter when necessary (when + // the amount of lines crosses a boundary that makes its width change) + d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null + // Set to true when a non-horizontal-scrolling line widget is + // added. As an optimization, line widget aligning is skipped when + // this is false. + d.alignWidgets = false + + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null + + // Tracks the maximum line length so that the horizontal scrollbar + // can be kept static when scrolling. + d.maxLine = null + d.maxLineLength = 0 + d.maxLineChanged = false + + // Used for measuring wheel scrolling granularity + d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null + + // True when shift is held down. + d.shift = false + + // Used to track whether anything happened since the context menu + // was opened. + d.selForContextMenu = null + + d.activeTouch = null + + input.init(d) +} + +// Find the line object corresponding to the given line number. +function getLine(doc, n) { + n -= doc.first + if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") } + var chunk = doc + while (!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] +} + +// Get the part of a document between two positions, as an array of +// strings. +function getBetween(doc, start, end) { + var out = [], n = start.line + doc.iter(start.line, end.line + 1, function (line) { + var text = line.text + if (n == end.line) { text = text.slice(0, end.ch) } + if (n == start.line) { text = text.slice(start.ch) } + out.push(text) + ++n + }) + return out +} +// Get the lines between from and to, as array of strings. +function getLines(doc, from, to) { + var out = [] + doc.iter(from, to, function (line) { out.push(line.text) }) // iter aborts when callback returns truthy value + return out +} + +// Update the height of a line, propagating the height change +// upwards to parent nodes. +function updateLineHeight(line, height) { + var diff = height - line.height + if (diff) { for (var n = line; n; n = n.parent) { n.height += diff } } +} + +// Given a line object, find its line number by walking up through +// its parent links. +function lineNo(line) { + if (line.parent == null) { return null } + var cur = line.parent, no = indexOf(cur.lines, line) + for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { + for (var i = 0;; ++i) { + if (chunk.children[i] == cur) { break } + no += chunk.children[i].chunkSize() + } + } + return no + cur.first +} + +// Find the line at the given vertical position, using the height +// information in the document tree. +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) + var i = 0 + for (; i < chunk.lines.length; ++i) { + var line = chunk.lines[i], lh = line.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)) +} + +// A Pos instance represents a position within the text. +function Pos (line, ch) { + if (!(this instanceof Pos)) { return new Pos(line, ch) } + this.line = line; this.ch = ch +} + +// Compare two positions, return 0 if they are the same, a negative +// number when a is less, and a positive number otherwise. +function cmp(a, b) { return a.line - b.line || a.ch - b.ch } + +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 } + +// Most of the external API clips given positions to make sure they +// actually exist within the document. +function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))} +function clipPos(doc, pos) { + if (pos.line < doc.first) { return Pos(doc.first, 0) } + var last = doc.first + doc.size - 1 + if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) } + return clipToLen(pos, getLine(doc, pos.line).text.length) +} +function clipToLen(pos, linelen) { + var ch = pos.ch + if (ch == null || ch > linelen) { return Pos(pos.line, linelen) } + else if (ch < 0) { return Pos(pos.line, 0) } + else { return pos } +} +function clipPosArray(doc, array) { + var out = [] + for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]) } + return out +} + +// Optimize some code when these features are not used. +var sawReadOnlySpans = false; +var sawCollapsedSpans = false; +function seeReadOnlySpans() { + sawReadOnlySpans = true +} + +function seeCollapsedSpans() { + sawCollapsedSpans = true +} + +// TEXTMARKER SPANS + +function MarkedSpan(marker, from, to) { + this.marker = marker + this.from = from; this.to = to +} + +// Search an array of spans for a span matching the given marker. +function getMarkedSpanFor(spans, marker) { + if (spans) { for (var i = 0; i < spans.length; ++i) { + var span = spans[i] + if (span.marker == marker) { return span } + } } +} +// Remove a span from an array, returning undefined if no spans are +// left (we don't store arrays for lines without spans). +function removeMarkedSpan(spans, span) { + var r + for (var i = 0; i < spans.length; ++i) + { if (spans[i] != span) { (r || (r = [])).push(spans[i]) } } + return r +} +// Add a span to a line. +function addMarkedSpan(line, span) { + line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span] + span.marker.attachLine(line) +} + +// Used for the algorithm that adjusts markers for a change in the +// document. These functions cut an array of spans at a given +// character position, returning an array of remaining chunks (or +// undefined if nothing remains). +function markedSpansBefore(old, startCh, isInsert) { + var nw + if (old) { for (var i = 0; i < old.length; ++i) { + var span = old[i], marker = span.marker + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh) + if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh) + ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)) + } + } } + return nw +} +function markedSpansAfter(old, endCh, isInsert) { + var nw + if (old) { for (var i = 0; i < old.length; ++i) { + var span = old[i], marker = span.marker + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh) + if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh) + ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, + span.to == null ? null : span.to - endCh)) + } + } } + return nw +} + +// Given a change object, compute the new set of marker spans that +// cover the line in which the change took place. Removes spans +// entirely within the change, reconnects spans belonging to the +// same marker that appear on both sides of the change, and cuts off +// spans partially within the change. Returns an array of span +// arrays with one element for each line in (after) the change. +function stretchSpansOverChange(doc, change) { + if (change.full) { return null } + var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans + var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans + if (!oldFirst && !oldLast) { return null } + + var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0 + // Get the spans that 'stick out' on both sides + var first = markedSpansBefore(oldFirst, startCh, isInsert) + var last = markedSpansAfter(oldLast, endCh, isInsert) + + // Next, merge those two ends + var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0) + if (first) { + // Fix up .to properties of first + for (var i = 0; i < first.length; ++i) { + var span = first[i] + if (span.to == null) { + var found = getMarkedSpanFor(last, span.marker) + if (!found) { span.to = startCh } + else if (sameLine) { span.to = found.to == null ? null : found.to + offset } + } + } + } + if (last) { + // Fix up .from in last (or move them into first in case of sameLine) + for (var i$1 = 0; i$1 < last.length; ++i$1) { + var span$1 = last[i$1] + if (span$1.to != null) { span$1.to += offset } + if (span$1.from == null) { + var found$1 = getMarkedSpanFor(first, span$1.marker) + if (!found$1) { + span$1.from = offset + if (sameLine) { (first || (first = [])).push(span$1) } + } + } else { + span$1.from += offset + if (sameLine) { (first || (first = [])).push(span$1) } + } + } + } + // Make sure we didn't create any zero-length spans + if (first) { first = clearEmptySpans(first) } + if (last && last != first) { last = clearEmptySpans(last) } + + var newMarkers = [first] + if (!sameLine) { + // Fill gap with whole-line-spans + var gap = change.text.length - 2, gapMarkers + if (gap > 0 && first) + { for (var i$2 = 0; i$2 < first.length; ++i$2) + { if (first[i$2].to == null) + { (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 +} + +// Remove spans that are empty and don't have a clearWhenEmpty +// option of false. +function clearEmptySpans(spans) { + for (var i = 0; i < spans.length; ++i) { + var span = spans[i] + if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) + { spans.splice(i--, 1) } + } + if (!spans.length) { return null } + return spans +} + +// Used to 'clip' out readOnly ranges when making a change. +function removeReadOnlyRanges(doc, from, to) { + var markers = null + 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 + if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) + { (markers || (markers = [])).push(mark) } + } } + }) + if (!markers) { return null } + var parts = [{from: from, to: to}] + for (var i = 0; i < markers.length; ++i) { + var mk = markers[i], m = mk.find(0) + for (var j = 0; j < parts.length; ++j) { + var p = parts[j] + if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue } + var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to) + if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) + { newParts.push({from: p.from, to: m.from}) } + if (dto > 0 || !mk.inclusiveRight && !dto) + { newParts.push({from: m.to, to: p.to}) } + parts.splice.apply(parts, newParts) + j += newParts.length - 1 + } + } + return parts +} + +// Connect or disconnect spans from a line. +function detachMarkedSpans(line) { + var spans = line.markedSpans + if (!spans) { return } + for (var i = 0; i < spans.length; ++i) + { spans[i].marker.detachLine(line) } + line.markedSpans = null +} +function attachMarkedSpans(line, spans) { + if (!spans) { return } + for (var i = 0; i < spans.length; ++i) + { spans[i].marker.attachLine(line) } + line.markedSpans = spans +} + +// Helpers used when computing which overlapping collapsed span +// counts as the larger one. +function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 } +function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 } + +// Returns a number indicating which of two overlapping collapsed +// spans is larger (and thus includes the other). Falls back to +// comparing ids when the spans cover exactly the same range. +function compareCollapsedMarkers(a, b) { + var lenDiff = a.lines.length - b.lines.length + if (lenDiff != 0) { return lenDiff } + var aPos = a.find(), bPos = b.find() + var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b) + if (fromCmp) { return -fromCmp } + var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b) + if (toCmp) { return toCmp } + return b.id - a.id +} + +// Find out whether a line ends or starts in a collapsed span. If +// so, return the marker for that span. +function collapsedSpanAtSide(line, start) { + var sps = sawCollapsedSpans && line.markedSpans, found + if (sps) { for (var sp = void 0, i = 0; i < sps.length; ++i) { + sp = sps[i] + if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && + (!found || compareCollapsedMarkers(found, sp.marker) < 0)) + { found = sp.marker } + } } + return found +} +function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) } +function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) } + +// Test whether there exists a collapsed span that partially +// overlaps (covers the start or end, but not both) of a new span. +// Such overlap is not allowed. +function conflictingCollapsedRange(doc, lineNo, from, to, marker) { + var line = getLine(doc, lineNo) + var sps = sawCollapsedSpans && line.markedSpans + if (sps) { for (var i = 0; i < sps.length; ++i) { + var sp = sps[i] + if (!sp.marker.collapsed) { continue } + var found = sp.marker.find(0) + var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker) + var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker) + if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue } + if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) || + fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0)) + { return true } + } } +} + +// A visual line is a line as drawn on the screen. Folding, for +// example, can cause multiple logical lines to appear on the same +// visual line. This finds the start of the visual line that the +// given line is part of (usually that is the line itself). +function visualLine(line) { + var merged + while (merged = collapsedSpanAtStart(line)) + { line = merged.find(-1, true).line } + return line +} + +// Returns an array of logical lines that continue the visual line +// started by the argument, or undefined if there are no such lines. +function visualLineContinued(line) { + var merged, lines + while (merged = collapsedSpanAtEnd(line)) { + line = merged.find(1, true).line + ;(lines || (lines = [])).push(line) + } + return lines +} + +// Get the line number of the start of the visual line that the +// given line number is part of. +function visualLineNo(doc, lineN) { + var line = getLine(doc, lineN), vis = visualLine(line) + if (line == vis) { return lineN } + return lineNo(vis) +} + +// Get the line number of the start of the next visual line after +// the given line. +function visualLineEndNo(doc, lineN) { + if (lineN > doc.lastLine()) { return lineN } + var line = getLine(doc, lineN), merged + if (!lineIsHidden(doc, line)) { return lineN } + while (merged = collapsedSpanAtEnd(line)) + { line = merged.find(1, true).line } + return lineNo(line) + 1 +} + +// Compute whether a line is hidden. Lines count as hidden when they +// are part of a visual line that starts with another line, or when +// they are entirely covered by collapsed, non-widget span. +function lineIsHidden(doc, line) { + var sps = sawCollapsedSpans && line.markedSpans + if (sps) { for (var sp = void 0, i = 0; i < sps.length; ++i) { + sp = sps[i] + if (!sp.marker.collapsed) { continue } + if (sp.from == null) { return true } + if (sp.marker.widgetNode) { continue } + if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) + { return true } + } } +} +function lineIsHiddenInner(doc, line, span) { + if (span.to == null) { + var end = span.marker.find(1, true) + return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)) + } + if (span.marker.inclusiveRight && span.to == line.text.length) + { return true } + for (var sp = void 0, i = 0; i < line.markedSpans.length; ++i) { + sp = line.markedSpans[i] + if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && + (sp.to == null || sp.to != span.from) && + (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && + lineIsHiddenInner(doc, line, sp)) { return true } + } +} + +// Find the height above the given line. +function heightAtLine(lineObj) { + lineObj = visualLine(lineObj) + + var h = 0, chunk = lineObj.parent + for (var i = 0; i < chunk.lines.length; ++i) { + var line = chunk.lines[i] + if (line == lineObj) { break } + else { h += line.height } + } + for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { + for (var i$1 = 0; i$1 < p.children.length; ++i$1) { + var cur = p.children[i$1] + if (cur == chunk) { break } + else { h += cur.height } + } + } + return h +} + +// Compute the character length of a line, taking into account +// collapsed ranges (see markText) that might hide parts, and join +// other lines onto it. +function lineLength(line) { + if (line.height == 0) { return 0 } + var len = line.text.length, merged, cur = line + while (merged = collapsedSpanAtStart(cur)) { + var found = merged.find(0, true) + cur = found.from.line + len += found.from.ch - found.to.ch + } + cur = line + while (merged = collapsedSpanAtEnd(cur)) { + var found$1 = merged.find(0, true) + len -= cur.text.length - found$1.from.ch + cur = found$1.to.line + len += cur.text.length - found$1.to.ch + } + return len +} + +// Find the longest line in the document. +function findMaxLine(cm) { + var d = cm.display, doc = cm.doc + d.maxLine = getLine(doc, doc.first) + d.maxLineLength = lineLength(d.maxLine) + d.maxLineChanged = true + doc.iter(function (line) { + var len = lineLength(line) + if (len > d.maxLineLength) { + d.maxLineLength = len + d.maxLine = line + } + }) +} + +// BIDI HELPERS + +function iterateBidiSections(order, from, to, f) { + if (!order) { return f(from, to, "ltr") } + var found = false + for (var i = 0; i < order.length; ++i) { + var part = order[i] + if (part.from < to && part.to > from || from == to && part.to == from) { + f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr") + found = true + } + } + if (!found) { f(from, to, "ltr") } +} + +function bidiLeft(part) { return part.level % 2 ? part.to : part.from } +function bidiRight(part) { return part.level % 2 ? part.from : part.to } + +function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0 } +function lineRight(line) { + var order = getOrder(line) + if (!order) { return line.text.length } + return bidiRight(lst(order)) +} + +function compareBidiLevel(order, a, b) { + var linedir = order[0].level + if (a == linedir) { return true } + if (b == linedir) { return false } + return a < b +} + +var bidiOther = null +function getBidiPartAt(order, pos) { + var found + bidiOther = null + for (var i = 0; i < order.length; ++i) { + var cur = order[i] + if (cur.from < pos && cur.to > pos) { return i } + if ((cur.from == pos || cur.to == pos)) { + if (found == null) { + found = i + } else if (compareBidiLevel(order, cur.level, order[found].level)) { + if (cur.from != cur.to) { bidiOther = found } + return i + } else { + if (cur.from != cur.to) { bidiOther = i } + return found + } + } + } + return found +} + +function moveInLine(line, pos, dir, byUnit) { + if (!byUnit) { return pos + dir } + do { pos += dir } + while (pos > 0 && isExtendingChar(line.text.charAt(pos))) + return pos +} + +// This is needed in order to move 'visually' through bi-directional +// text -- i.e., pressing left should make the cursor go left, even +// when in RTL text. The tricky part is the 'jumps', where RTL and +// LTR text touch each other. This often requires the cursor offset +// to move more than one unit, in order to visually move one unit. +function moveVisually(line, start, dir, byUnit) { + var bidi = getOrder(line) + if (!bidi) { return moveLogically(line, start, dir, byUnit) } + var pos = getBidiPartAt(bidi, start), part = bidi[pos] + var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit) + + for (;;) { + if (target > part.from && target < part.to) { return target } + if (target == part.from || target == part.to) { + if (getBidiPartAt(bidi, target) == pos) { return target } + part = bidi[pos += dir] + return (dir > 0) == part.level % 2 ? part.to : part.from } else { - rmClass(cm.display.wrapper, "CodeMirror-wrap"); - findMaxLine(cm); - } - estimateLineHeights(cm); - regChange(cm); - clearCaches(cm); - setTimeout(function(){updateScrollbars(cm);}, 100); - } - - // Returns a function that estimates the height of a line, to use as - // first approximation until the line becomes visible (and is thus - // properly measurable). - function estimateHeight(cm) { - var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; - var 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++) { - if (line.widgets[i].height) widgetsHeight += line.widgets[i].height; - } - - if (wrapping) - return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th; + part = bidi[pos += dir] + if (!part) { return null } + if ((dir > 0) == part.level % 2) + { target = moveInLine(line, part.to, -1, byUnit) } else - return widgetsHeight + th; - }; - } - - function estimateLineHeights(cm) { - var doc = cm.doc, est = estimateHeight(cm); - doc.iter(function(line) { - var estHeight = est(line); - if (estHeight != line.height) updateLineHeight(line, estHeight); - }); - } - - 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); - } - - function guttersChanged(cm) { - updateGutters(cm); - regChange(cm); - setTimeout(function(){alignHorizontally(cm);}, 20); - } - - // Rebuild the gutter elements, ensure the margin to the left of the - // code matches their width. - function updateGutters(cm) { - var gutters = cm.display.gutters, specs = cm.options.gutters; - removeChildren(gutters); - for (var i = 0; i < specs.length; ++i) { - var gutterClass = specs[i]; - var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass)); - if (gutterClass == "CodeMirror-linenumbers") { - cm.display.lineGutter = gElt; - gElt.style.width = (cm.display.lineNumWidth || 1) + "px"; - } - } - gutters.style.display = i ? "" : "none"; - updateGutterSpace(cm); - } - - function updateGutterSpace(cm) { - var width = cm.display.gutters.offsetWidth; - cm.display.sizer.style.marginLeft = width + "px"; - } - - // Compute the character length of a line, taking into account - // collapsed ranges (see markText) that might hide parts, and join - // other lines onto it. - function lineLength(line) { - if (line.height == 0) return 0; - var len = line.text.length, merged, cur = line; - while (merged = collapsedSpanAtStart(cur)) { - var found = merged.find(0, true); - cur = found.from.line; - len += found.from.ch - found.to.ch; - } - cur = line; - while (merged = collapsedSpanAtEnd(cur)) { - var found = merged.find(0, true); - len -= cur.text.length - found.from.ch; - cur = found.to.line; - len += cur.text.length - found.to.ch; - } - return len; - } - - // Find the longest line in the document. - function findMaxLine(cm) { - var d = cm.display, doc = cm.doc; - d.maxLine = getLine(doc, doc.first); - d.maxLineLength = lineLength(d.maxLine); - d.maxLineChanged = true; - doc.iter(function(line) { - var len = lineLength(line); - if (len > d.maxLineLength) { - d.maxLineLength = len; - d.maxLine = line; - } - }); - } - - // Make sure the gutters options contains the element - // "CodeMirror-linenumbers" when the lineNumbers option is true. - function setGuttersForLineNumbers(options) { - var found = indexOf(options.gutters, "CodeMirror-linenumbers"); - if (found == -1 && options.lineNumbers) { - options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]); - } else if (found > -1 && !options.lineNumbers) { - options.gutters = options.gutters.slice(0); - options.gutters.splice(found, 1); - } - } - - // SCROLLBARS - - // Prepare DOM reads needed to update the scrollbars. Done in one - // shot to minimize update/measure roundtrips. - function measureForScrollbars(cm) { - var d = cm.display, gutterW = d.gutters.offsetWidth; - var 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"); - var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar"); - place(vert); place(horiz); - - on(vert, "scroll", function() { - if (vert.clientHeight) scroll(vert.scrollTop, "vertical"); - }); - on(horiz, "scroll", function() { - if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal"); - }); - - this.checkedZeroWidth = false; - // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). - if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; - } - - NativeScrollbars.prototype = copyObj({ - update: function(measure) { - var needsH = measure.scrollWidth > measure.clientWidth + 1; - var needsV = measure.scrollHeight > measure.clientHeight + 1; - var sWidth = measure.nativeBarWidth; - - if (needsV) { - this.vert.style.display = "block"; - this.vert.style.bottom = needsH ? sWidth + "px" : "0"; - var totalHeight = measure.viewHeight - (needsH ? sWidth : 0); - // A bug in IE8 can cause this value to be negative, so guard it. - this.vert.firstChild.style.height = - Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"; + { target = moveInLine(line, part.from, 1, byUnit) } + } + } +} + +function moveLogically(line, start, dir, byUnit) { + var target = start + dir + if (byUnit) { while (target > 0 && isExtendingChar(line.text.charAt(target))) { target += dir } } + return target < 0 || target > line.text.length ? null : target +} + +// Bidirectional ordering algorithm +// See http://unicode.org/reports/tr9/tr9-13.html for the algorithm +// that this (partially) implements. + +// One-char codes used for character types: +// L (L): Left-to-Right +// R (R): Right-to-Left +// r (AL): Right-to-Left Arabic +// 1 (EN): European Number +// + (ES): European Number Separator +// % (ET): European Number Terminator +// n (AN): Arabic Number +// , (CS): Common Number Separator +// m (NSM): Non-Spacing Mark +// b (BN): Boundary Neutral +// s (B): Paragraph Separator +// t (S): Segment Separator +// w (WS): Whitespace +// N (ON): Other Neutrals + +// Returns null if characters are ordered as they appear +// (left-to-right), or an array of sections ({from, to, level} +// objects) in the order in which they occur visually. +var bidiOrdering = (function() { + // Character types for codepoints 0 to 0xff + var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN" + // Character types for codepoints 0x600 to 0x6ff + var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm" + function charType(code) { + if (code <= 0xf7) { return lowTypes.charAt(code) } + else if (0x590 <= code && code <= 0x5f4) { return "R" } + else if (0x600 <= code && code <= 0x6ed) { return arabicTypes.charAt(code - 0x600) } + else if (0x6ee <= code && code <= 0x8ac) { return "r" } + else if (0x2000 <= code && code <= 0x200b) { return "w" } + else if (code == 0x200c) { return "b" } + else { return "L" } + } + + var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/ + var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/ + // Browsers seem to always treat the boundaries of block elements as being L. + var outerType = "L" + + function BidiSpan(level, from, to) { + this.level = level + this.from = from; this.to = to + } + + return function(str) { + if (!bidiRE.test(str)) { return false } + var len = str.length, types = [] + for (var i = 0; i < len; ++i) + { types.push(charType(str.charCodeAt(i))) } + + // W1. Examine each non-spacing mark (NSM) in the level run, and + // change the type of the NSM to the type of the previous + // character. If the NSM is at the start of the level run, it will + // get the type of sor. + for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) { + var type = types[i$1] + if (type == "m") { types[i$1] = prev } + else { prev = type } + } + + // W2. Search backwards from each instance of a European number + // until the first strong type (R, L, AL, or sor) is found. If an + // AL is found, change the type of the European number to Arabic + // number. + // W3. Change all ALs to R. + for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) { + var type$1 = types[i$2] + if (type$1 == "1" && cur == "r") { types[i$2] = "n" } + else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R" } } + } + + // W4. A single European separator between two European numbers + // changes to a European number. A single common separator between + // two numbers of the same type changes to that type. + for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) { + var type$2 = types[i$3] + if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1" } + else if (type$2 == "," && prev$1 == types[i$3+1] && + (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1 } + prev$1 = type$2 + } + + // W5. A sequence of European terminators adjacent to European + // numbers changes to all European numbers. + // W6. Otherwise, separators and terminators change to Other + // Neutral. + 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 == "%") { + var end = void 0 + for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {} + var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N" + for (var j = i$4; j < end; ++j) { types[j] = replace } + i$4 = end - 1 + } + } + + // W7. Search backwards from each instance of a European number + // until the first strong type (R, L, or sor) is found. If an L is + // found, then change the type of the European number to L. + for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) { + var type$4 = types[i$5] + if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L" } + else if (isStrong.test(type$4)) { cur$1 = type$4 } + } + + // N1. A sequence of neutrals takes the direction of the + // surrounding strong text if the text on both sides has the same + // direction. European and Arabic numbers act as if they were R in + // terms of their influence on neutrals. Start-of-level-run (sor) + // and end-of-level-run (eor) are used at level run boundaries. + // N2. Any remaining neutrals take the embedding direction. + for (var i$6 = 0; i$6 < len; ++i$6) { + if (isNeutral.test(types[i$6])) { + var end$1 = void 0 + for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {} + var before = (i$6 ? types[i$6-1] : outerType) == "L" + var after = (end$1 < len ? types[end$1] : outerType) == "L" + var replace$1 = before || after ? "L" : "R" + for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1 } + i$6 = end$1 - 1 + } + } + + // Here we depart from the documented algorithm, in order to avoid + // building up an actual levels array. Since there are only three + // levels (0, 1, 2) in an implementation that doesn't take + // explicit embedding into account, we can build up the order on + // the fly, without following the level-based algorithm. + var order = [], m + for (var 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 { - this.vert.style.display = ""; - this.vert.firstChild.style.height = "0"; + var pos = i$7, at = order.length + for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {} + for (var j$2 = pos; j$2 < i$7;) { + if (countsAsNum.test(types[j$2])) { + if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)) } + 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)) + pos = j$2 + } else { ++j$2 } + } + if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)) } + } + } + if (order[0].level == 1 && (m = str.match(/^\s+/))) { + order[0].from = m[0].length + order.unshift(new BidiSpan(0, 0, m[0].length)) + } + if (lst(order).level == 1 && (m = str.match(/\s+$/))) { + lst(order).to -= m[0].length + order.push(new BidiSpan(0, len - m[0].length, len)) + } + if (order[0].level == 2) + { order.unshift(new BidiSpan(1, order[0].to, order[0].to)) } + if (order[0].level != lst(order).level) + { order.push(new BidiSpan(order[0].level, len, len)) } + + return order + } +})() + +// Get the bidi ordering for the given line (and cache it). Returns +// false for lines that are fully left-to-right, and an array of +// BidiSpan objects otherwise. +function getOrder(line) { + var order = line.order + if (order == null) { order = line.order = bidiOrdering(line.text) } + return order +} + +// EVENT HANDLING + +// Lightweight event framework. on/off also work on DOM nodes, +// registering native DOM handlers. + +var on = function(emitter, type, f) { + if (emitter.addEventListener) + { emitter.addEventListener(type, f, false) } + else if (emitter.attachEvent) + { emitter.attachEvent("on" + type, f) } + else { + var map = emitter._handlers || (emitter._handlers = {}) + var arr = map[type] || (map[type] = []) + arr.push(f) + } +} + +var noHandlers = [] +function getHandlers(emitter, type, copy) { + var arr = emitter._handlers && emitter._handlers[type] + if (copy) { return arr && arr.length > 0 ? arr.slice() : noHandlers } + else { return arr || noHandlers } +} + +function off(emitter, type, f) { + if (emitter.removeEventListener) + { emitter.removeEventListener(type, f, false) } + else if (emitter.detachEvent) + { emitter.detachEvent("on" + type, f) } + else { + var handlers = getHandlers(emitter, type, false) + for (var i = 0; i < handlers.length; ++i) + { if (handlers[i] == f) { handlers.splice(i, 1); break } } + } +} + +function signal(emitter, type /*, values...*/) { + var handlers = getHandlers(emitter, type, true) + if (!handlers.length) { return } + var args = Array.prototype.slice.call(arguments, 2) + for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args) } +} + +// The DOM events that CodeMirror handles can be overridden by +// registering a (non-DOM) handler on the editor for the event name, +// and preventDefault-ing the event in that handler. +function signalDOMEvent(cm, e, override) { + if (typeof e == "string") + { e = {type: e, preventDefault: function() { this.defaultPrevented = true }} } + signal(cm, override || e.type, cm, e) + return e_defaultPrevented(e) || e.codemirrorIgnore +} + +function signalCursorActivity(cm) { + var arr = cm._handlers && cm._handlers.cursorActivity + if (!arr) { return } + var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []) + for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1) + { set.push(arr[i]) } } +} + +function hasHandler(emitter, type) { + return getHandlers(emitter, type).length > 0 +} + +// Add on and off methods to a constructor's prototype, to make +// registering events on such objects more convenient. +function eventMixin(ctor) { + ctor.prototype.on = function(type, f) {on(this, type, f)} + ctor.prototype.off = function(type, f) {off(this, type, f)} +} + +// Due to the fact that we still support jurassic IE versions, some +// compatibility wrappers are needed. + +function e_preventDefault(e) { + if (e.preventDefault) { e.preventDefault() } + else { e.returnValue = false } +} +function e_stopPropagation(e) { + if (e.stopPropagation) { e.stopPropagation() } + else { e.cancelBubble = true } +} +function e_defaultPrevented(e) { + return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false +} +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 + if (b == null) { + if (e.button & 1) { b = 1 } + else if (e.button & 2) { b = 3 } + else if (e.button & 4) { b = 2 } + } + if (mac && e.ctrlKey && b == 1) { b = 3 } + return b +} + +// Detect drag-and-drop +var dragAndDrop = function() { + // There is *some* kind of drag-and-drop support in IE6-8, but I + // couldn't get it to work yet. + if (ie && ie_version < 9) { return false } + var div = elt('div') + return "draggable" in div || "dragDrop" in div +}() + +var zwspSupported +function zeroWidthElement(measure) { + if (zwspSupported == null) { + var test = elt("span", "\u200b") + removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])) + if (measure.firstChild.offsetHeight != 0) + { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8) } + } + var node = zwspSupported ? elt("span", "\u200b") : + elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px") + node.setAttribute("cm-text", "") + return node +} + +// Feature-detect IE's crummy client rect reporting for bidi text +var badBidiRects +function hasBadBidiRects(measure) { + if (badBidiRects != null) { return badBidiRects } + var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")) + var r0 = range(txt, 0, 1).getBoundingClientRect() + var r1 = range(txt, 1, 2).getBoundingClientRect() + removeChildren(measure) + if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780) + return badBidiRects = (r1.right - r0.right < 3) +} + +// See if "".split is the broken IE version, if so, provide an +// alternative way to split lines. +var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) { + var pos = 0, result = [], l = string.length + while (pos <= l) { + var nl = string.indexOf("\n", pos) + if (nl == -1) { nl = string.length } + var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl) + var rt = line.indexOf("\r") + if (rt != -1) { + result.push(line.slice(0, rt)) + pos += rt + 1 + } else { + result.push(line) + pos = nl + 1 + } + } + return result +} : function (string) { return string.split(/\r\n?|\n/); } + +var hasSelection = window.getSelection ? function (te) { + try { return te.selectionStart != te.selectionEnd } + catch(e) { return false } +} : function (te) { + var range + try {range = te.ownerDocument.selection.createRange()} + catch(e) {} + if (!range || range.parentElement() != te) { return false } + return range.compareEndPoints("StartToEnd", range) != 0 +} + +var hasCopyEvent = (function () { + var e = elt("div") + if ("oncopy" in e) { return true } + e.setAttribute("oncopy", "return;") + return typeof e.oncopy == "function" +})() + +var badZoomedRects = null +function hasBadZoomedRects(measure) { + if (badZoomedRects != null) { return badZoomedRects } + var node = removeChildrenAndAdd(measure, elt("span", "x")) + var normal = node.getBoundingClientRect() + var fromRange = range(node, 0, 1).getBoundingClientRect() + return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1 +} + +var modes = {}; +var mimeModes = {}; +// Extra arguments are stored as the mode's dependencies, which is +// used by (legacy) mechanisms like loadmode.js to automatically +// load a mode. (Preferred mechanism is the require/define calls.) +function defineMode(name, mode) { + if (arguments.length > 2) + { mode.dependencies = Array.prototype.slice.call(arguments, 2) } + modes[name] = mode +} + +function defineMIME(mime, spec) { + mimeModes[mime] = spec +} + +// Given a MIME type, a {name, ...options} config object, or a name +// string, return a mode config object. +function resolveMode(spec) { + if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { + spec = mimeModes[spec] + } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { + var found = mimeModes[spec.name] + if (typeof found == "string") { found = {name: found} } + spec = createObj(found, spec) + spec.name = found.name + } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { + return resolveMode("application/xml") + } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) { + return resolveMode("application/json") + } + if (typeof spec == "string") { return {name: spec} } + else { return spec || {name: "null"} } +} + +// Given a mode spec (anything that resolveMode accepts), find and +// initialize an actual mode object. +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 exts = modeExtensions[spec.name] + for (var prop in exts) { + if (!exts.hasOwnProperty(prop)) { continue } + if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop] } + modeObj[prop] = exts[prop] + } + } + modeObj.name = spec.name + if (spec.helperType) { modeObj.helperType = spec.helperType } + if (spec.modeProps) { for (var prop$1 in spec.modeProps) + { modeObj[prop$1] = spec.modeProps[prop$1] } } + + return modeObj +} + +// This can be used to attach properties to mode objects from +// outside the actual mode definition. +var modeExtensions = {} +function extendMode(mode, properties) { + var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}) + copyObj(properties, exts) +} + +function copyState(mode, state) { + if (state === true) { return state } + if (mode.copyState) { return mode.copyState(state) } + var nstate = {} + for (var n in state) { + var val = state[n] + if (val instanceof Array) { val = val.concat([]) } + nstate[n] = val + } + return nstate +} + +// Given a mode and a state (for that mode), find the inner mode and +// state at the position that the state refers to. +function innerMode(mode, state) { + var info + while (mode.innerMode) { + info = mode.innerMode(state) + if (!info || info.mode == mode) { break } + state = info.state + mode = info.mode + } + return info || {mode: mode, state: state} +} + +function startState(mode, a1, a2) { + return mode.startState ? mode.startState(a1, a2) : true +} + +// STRING STREAM + +// Fed to the mode parsers, provides helper functions to make +// parsers more succinct. + +var StringStream = function(string, tabSize) { + this.pos = this.start = 0 + this.string = string + this.tabSize = tabSize || 8 + this.lastColumnPos = this.lastColumnValue = 0 + this.lineStart = 0 +} + +StringStream.prototype = { + eol: function() {return this.pos >= this.string.length}, + sol: function() {return this.pos == this.lineStart}, + peek: function() {return this.string.charAt(this.pos) || undefined}, + next: function() { + if (this.pos < this.string.length) + { return this.string.charAt(this.pos++) } + }, + eat: function(match) { + var ch = this.string.charAt(this.pos) + var ok + if (typeof match == "string") { ok = ch == match } + else { ok = ch && (match.test ? match.test(ch) : match(ch)) } + if (ok) {++this.pos; return ch} + }, + eatWhile: function(match) { + var start = this.pos + while (this.eat(match)){} + return this.pos > start + }, + eatSpace: function() { + var this$1 = this; + + var start = this.pos + while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos } + return this.pos > start + }, + skipToEnd: function() {this.pos = this.string.length}, + skipTo: function(ch) { + var found = this.string.indexOf(ch, this.pos) + if (found > -1) {this.pos = found; return true} + }, + backUp: function(n) {this.pos -= n}, + column: function() { + if (this.lastColumnPos < this.start) { + this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue) + this.lastColumnPos = this.start + } + return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) + }, + indentation: function() { + return countColumn(this.string, null, this.tabSize) - + (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) + }, + match: function(pattern, consume, caseInsensitive) { + if (typeof pattern == "string") { + var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; } + var substr = this.string.substr(this.pos, pattern.length) + if (cased(substr) == cased(pattern)) { + if (consume !== false) { this.pos += pattern.length } + return true } - - if (needsH) { - this.horiz.style.display = "block"; - this.horiz.style.right = needsV ? sWidth + "px" : "0"; - this.horiz.style.left = measure.barLeft + "px"; - var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0); - this.horiz.firstChild.style.width = - (measure.scrollWidth - measure.clientWidth + totalWidth) + "px"; + } else { + var match = this.string.slice(this.pos).match(pattern) + if (match && match.index > 0) { return null } + if (match && consume !== false) { this.pos += match[0].length } + return match + } + }, + current: function(){return this.string.slice(this.start, this.pos)}, + hideFirstChars: function(n, inner) { + this.lineStart += n + try { return inner() } + finally { this.lineStart -= n } + } +} + +// Compute a style array (an array starting with a mode generation +// -- for invalidation -- followed by pairs of end positions and +// style strings), which is used to highlight the tokens on the +// line. +function highlightLine(cm, line, state, forceToEnd) { + // A styles array always starts with a number identifying the + // mode/overlays that it is based on (for easy invalidation). + var st = [cm.state.modeGen], lineClasses = {} + // Compute the base array of styles + runMode(cm, line.text, cm.doc.mode, state, function (end, style) { return st.push(end, style); }, + lineClasses, forceToEnd) + + // Run overlays, adjust style array. + var loop = function ( o ) { + var overlay = cm.state.overlays[o], i = 1, at = 0 + runMode(cm, line.text, overlay.mode, true, function (end, style) { + var start = i + // Ensure there's a token end at the current position, and that i points at it + while (at < end) { + var i_end = st[i] + if (i_end > end) + { st.splice(i, 1, end, st[i+1], i_end) } + i += 2 + at = Math.min(end, i_end) + } + if (!style) { return } + if (overlay.opaque) { + st.splice(start, i - start, end, "overlay " + style) + i = start + 2 } else { - this.horiz.style.display = ""; - this.horiz.firstChild.style.width = "0"; + for (; start < i; start += 2) { + var cur = st[start+1] + st[start+1] = (cur ? cur + " " : "") + "overlay " + style + } } + }, lineClasses) + }; - if (!this.checkedZeroWidth && measure.clientHeight > 0) { - if (sWidth == 0) this.zeroWidthHack(); - this.checkedZeroWidth = true; + for (var o = 0; o < cm.state.overlays.length; ++o) loop( o ); + + return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null} +} + +function getLineStyles(cm, line, updateFrontier) { + if (!line.styles || line.styles[0] != cm.state.modeGen) { + var state = getStateBefore(cm, lineNo(line)) + var result = highlightLine(cm, line, line.text.length > cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state) + line.stateAfter = state + line.styles = result.styles + if (result.classes) { line.styleClasses = result.classes } + else if (line.styleClasses) { line.styleClasses = null } + if (updateFrontier === cm.doc.frontier) { cm.doc.frontier++ } + } + return line.styles +} + +function getStateBefore(cm, n, precise) { + var doc = cm.doc, display = cm.display + if (!doc.mode.startState) { return true } + var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter + if (!state) { state = startState(doc.mode) } + else { state = copyState(doc.mode, state) } + doc.iter(pos, n, function (line) { + processLine(cm, line.text, state) + var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo + line.stateAfter = save ? copyState(doc.mode, state) : null + ++pos + }) + if (precise) { doc.frontier = pos } + return state +} + +// Lightweight form of highlight -- proceed over this line and +// update state, but don't save a style array. Used for lines that +// aren't currently visible. +function processLine(cm, text, state, startAt) { + var mode = cm.doc.mode + var stream = new StringStream(text, cm.options.tabSize) + stream.start = stream.pos = startAt || 0 + if (text == "") { callBlankLine(mode, state) } + while (!stream.eol()) { + readToken(mode, stream, state) + stream.start = stream.pos + } +} + +function callBlankLine(mode, state) { + if (mode.blankLine) { return mode.blankLine(state) } + if (!mode.innerMode) { return } + var inner = innerMode(mode, state) + if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) } +} + +function readToken(mode, stream, state, inner) { + for (var i = 0; i < 10; i++) { + if (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.") +} + +// Utility for getTokenAt and getLineTokens +function takeToken(cm, pos, precise, asArray) { + var getObj = function (copy) { return ({ + start: stream.start, end: stream.pos, + string: stream.current(), + type: style || null, + state: copy ? copyState(doc.mode, state) : state + }); } + + var doc = cm.doc, mode = doc.mode, style + pos = clipPos(doc, pos) + var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise) + var stream = new StringStream(line.text, cm.options.tabSize), tokens + if (asArray) { tokens = [] } + while ((asArray || stream.pos < pos.ch) && !stream.eol()) { + stream.start = stream.pos + style = readToken(mode, stream, state) + if (asArray) { tokens.push(getObj(true)) } + } + return asArray ? tokens : getObj() +} + +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" + if (output[prop] == null) + { output[prop] = lineClass[2] } + else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop])) + { output[prop] += " " + lineClass[2] } + } } + return type +} + +// Run the given mode's parser over a line, calling f for each token. +function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) { + var flattenSpans = mode.flattenSpans + if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans } + var curStart = 0, curStyle = null + var stream = new StringStream(text, cm.options.tabSize), style + var inner = cm.options.addModeClass && [null] + if (text == "") { extractLineClasses(callBlankLine(mode, state), lineClasses) } + while (!stream.eol()) { + if (stream.pos > cm.options.maxHighlightLength) { + flattenSpans = false + if (forceToEnd) { processLine(cm, text, state, stream.pos) } + stream.pos = text.length + style = null + } else { + style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses) + } + if (inner) { + var mName = inner[0].name + if (mName) { style = "m-" + (style ? mName + " " + style : mName) } + } + if (!flattenSpans || curStyle != style) { + while (curStart < stream.start) { + curStart = Math.min(stream.start, curStart + 5000) + f(curStart, curStyle) + } + curStyle = style + } + stream.start = stream.pos + } + while (curStart < stream.pos) { + // Webkit seems to refuse to render text nodes longer than 57444 + // characters, and returns inaccurate measurements in nodes + // starting around 5000 chars. + var pos = Math.min(stream.pos, curStart + 5000) + f(pos, curStyle) + curStart = pos + } +} + +// Finds the line to start with when starting a parse. Tries to +// find a line with a stateAfter, so that it can start with a +// valid state. If that fails, it returns the line with the +// smallest indentation, which tends to need the least context to +// parse correctly. +function findStartLine(cm, n, precise) { + var minindent, minline, doc = cm.doc + var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100) + for (var search = n; search > lim; --search) { + if (search <= doc.first) { return doc.first } + var line = getLine(doc, search - 1) + if (line.stateAfter && (!precise || search <= doc.frontier)) { return search } + var indented = countColumn(line.text, null, cm.options.tabSize) + if (minline == null || minindent > indented) { + minline = search - 1 + minindent = indented + } + } + return minline +} + +// LINE DATA STRUCTURE + +// Line objects. These hold state related to a line, including +// highlighting info (the styles array). +function Line(text, markedSpans, estimateHeight) { + this.text = text + attachMarkedSpans(this, markedSpans) + this.height = estimateHeight ? estimateHeight(this) : 1 +} +eventMixin(Line) +Line.prototype.lineNo = function() { return lineNo(this) } + +// Change the content (text, markers) of a line. Automatically +// invalidates cached information and tries to re-estimate the +// line's height. +function updateLine(line, text, markedSpans, estimateHeight) { + line.text = text + if (line.stateAfter) { line.stateAfter = null } + if (line.styles) { line.styles = null } + if (line.order != null) { line.order = null } + detachMarkedSpans(line) + attachMarkedSpans(line, markedSpans) + var estHeight = estimateHeight ? estimateHeight(line) : 1 + if (estHeight != line.height) { updateLineHeight(line, estHeight) } +} + +// Detach a line from the document tree and its markers. +function cleanUpLine(line) { + line.parent = null + detachMarkedSpans(line) +} + +// Convert a style as returned by a mode (either null, or a string +// containing one or more styles) to a CSS style. This is cached, +// and also looks for line-wide styles. +var styleToClassCache = {}; +var styleToClassCacheWithMode = {}; +function interpretTokenStyle(style, options) { + if (!style || /^\s*$/.test(style)) { return null } + var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache + return cache[style] || + (cache[style] = style.replace(/\S+/g, "cm-$&")) +} + +// Render the DOM representation of the text of a line. Also builds +// up a 'line map', which points at the DOM nodes that represent +// specific stretches of text, and is used by the measuring code. +// The returned object contains the DOM node, this map, and +// information about line-wide styles that were set by the mode. +function buildLineContent(cm, lineView) { + // The padding-right forces the element to have a 'border', which + // is needed on Webkit to be able to get line-level bounding + // rectangles for it (in measureChar). + var content = elt("span", null, null, webkit ? "padding-right: .1px" : null) + var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content, + col: 0, pos: 0, cm: cm, + trailingSpace: false, + splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")} + lineView.measure = {} + + // Iterate over the logical lines that make up this visual line. + for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { + var line = i ? lineView.rest[i - 1] : lineView.line, order = void 0 + builder.pos = 0 + builder.addToken = buildToken + // Optionally wire in some hacks into the token-rendering + // algorithm, to deal with browser quirks. + if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line))) + { builder.addToken = buildTokenBadBidi(builder.addToken, order) } + builder.map = [] + var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line) + insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)) + if (line.styleClasses) { + if (line.styleClasses.bgClass) + { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "") } + if (line.styleClasses.textClass) + { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "") } + } + + // Ensure at least a single node is present, for measuring. + if (builder.map.length == 0) + { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))) } + + // Store the map and a cache object for the current logical line + if (i == 0) { + lineView.measure.map = builder.map + lineView.measure.cache = {} + } else { + ;(lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map) + ;(lineView.measure.caches || (lineView.measure.caches = [])).push({}) + } + } + + // See issue #2901 + if (webkit) { + var last = builder.content.lastChild + if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab"))) + { builder.content.className = "cm-tab-wrap-hack" } + } + + signal(cm, "renderLine", cm, lineView.line, builder.pre) + if (builder.pre.className) + { builder.textClass = joinClasses(builder.pre.className, builder.textClass || "") } + + return builder +} + +function defaultSpecialCharPlaceholder(ch) { + var token = elt("span", "\u2022", "cm-invalidchar") + token.title = "\\u" + ch.charCodeAt(0).toString(16) + token.setAttribute("aria-label", token.title) + return token +} + +// Build up the DOM representation for a single token, and add it to +// the line map. Takes care to render special characters separately. +function buildToken(builder, text, style, startStyle, endStyle, title, css) { + if (!text) { return } + var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text + var special = builder.cm.state.specialChars, mustWrap = false + var content + if (!special.test(text)) { + builder.col += text.length + content = document.createTextNode(displayText) + builder.map.push(builder.pos, builder.pos + text.length, content) + if (ie && ie_version < 9) { mustWrap = true } + builder.pos += text.length + } else { + content = document.createDocumentFragment() + var pos = 0 + while (true) { + special.lastIndex = pos + var m = special.exec(text) + var skipped = m ? m.index - pos : text.length - pos + if (skipped) { + var txt = document.createTextNode(displayText.slice(pos, pos + skipped)) + if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])) } + else { content.appendChild(txt) } + builder.map.push(builder.pos, builder.pos + skipped, txt) + builder.col += skipped + builder.pos += skipped + } + if (!m) { break } + pos += skipped + 1 + var txt$1 = void 0 + if (m[0] == "\t") { + var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize + txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")) + txt$1.setAttribute("role", "presentation") + txt$1.setAttribute("cm-text", "\t") + builder.col += tabWidth + } else if (m[0] == "\r" || m[0] == "\n") { + txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar")) + txt$1.setAttribute("cm-text", m[0]) + builder.col += 1 + } else { + txt$1 = builder.cm.options.specialCharPlaceholder(m[0]) + txt$1.setAttribute("cm-text", m[0]) + if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])) } + else { content.appendChild(txt$1) } + builder.col += 1 + } + builder.map.push(builder.pos, builder.pos + 1, txt$1) + builder.pos++ + } + } + builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32 + if (style || startStyle || endStyle || mustWrap || css) { + var fullStyle = style || "" + if (startStyle) { fullStyle += startStyle } + if (endStyle) { fullStyle += endStyle } + var token = elt("span", [content], fullStyle, css) + if (title) { token.title = title } + return builder.content.appendChild(token) + } + builder.content.appendChild(content) +} + +function splitSpaces(text, trailingBefore) { + if (text.length > 1 && !/ /.test(text)) { return text } + var spaceBefore = trailingBefore, result = "" + for (var i = 0; i < text.length; i++) { + var ch = text.charAt(i) + if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32)) + { ch = "\u00a0" } + result += ch + spaceBefore = ch == " " + } + return result +} + +// Work around nonsense dimensions being reported for stretches of +// right-to-left text. +function buildTokenBadBidi(inner, order) { + return function (builder, text, style, startStyle, endStyle, title, css) { + style = style ? style + " cm-force-border" : "cm-force-border" + var start = builder.pos, end = start + text.length + for (;;) { + // Find the part that overlaps with the start of this text + var part = void 0 + for (var i = 0; i < order.length; i++) { + part = order[i] + if (part.to > start && part.from <= start) { break } + } + if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, title, css) } + inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css) + startStyle = null + text = text.slice(part.to - start) + start = part.to + } + } +} + +function buildCollapsedSpan(builder, size, marker, ignoreWidget) { + var widget = !ignoreWidget && marker.widgetNode + if (widget) { builder.map.push(builder.pos, builder.pos + size, widget) } + if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { + if (!widget) + { widget = builder.content.appendChild(document.createElement("span")) } + widget.setAttribute("cm-marker", marker.id) + } + if (widget) { + builder.cm.display.input.setUneditable(widget) + builder.content.appendChild(widget) + } + builder.pos += size + builder.trailingSpace = false +} + +// Outputs a number of spans to make up a line, taking highlighting +// and marked text into account. +function insertLineContent(line, builder, styles) { + var spans = line.markedSpans, allText = line.text, at = 0 + if (!spans) { + 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)) } + return + } + + var len = allText.length, pos = 0, i = 1, text = "", style, css + var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed + for (;;) { + if (nextChange == pos) { // Update current marker set + spanStyle = spanEndStyle = spanStartStyle = title = css = "" + collapsed = null; nextChange = Infinity + var foundBookmarks = [], endStyles = void 0 + for (var j = 0; j < spans.length; ++j) { + var sp = spans[j], m = sp.marker + if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { + foundBookmarks.push(m) + } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { + if (sp.to != null && sp.to != pos && nextChange > sp.to) { + nextChange = sp.to + spanEndStyle = "" + } + if (m.className) { spanStyle += " " + m.className } + if (m.css) { css = (css ? css + ";" : "") + m.css } + if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle } + if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to) } + if (m.title && !title) { title = m.title } + if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) + { collapsed = sp } + } else if (sp.from > pos && nextChange > sp.from) { + nextChange = sp.from + } } + if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2) + { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1] } } } - return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}; - }, - setScrollLeft: function(pos) { - if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos; - if (this.disableHoriz) this.enableZeroWidthBar(this.horiz, this.disableHoriz); - }, - setScrollTop: function(pos) { - if (this.vert.scrollTop != pos) this.vert.scrollTop = pos; - if (this.disableVert) this.enableZeroWidthBar(this.vert, this.disableVert); - }, - zeroWidthHack: function() { - var w = mac && !mac_geMountainLion ? "12px" : "18px"; - this.horiz.style.height = this.vert.style.width = w; - this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none"; - this.disableHoriz = new Delayed; - this.disableVert = new Delayed; - }, - enableZeroWidthBar: function(bar, delay) { - bar.style.pointerEvents = "auto"; - function maybeDisable() { - // To find out whether the scrollbar is still visible, we - // check whether the element under the pixel in the bottom - // left corner of the scrollbar box is the scrollbar box - // itself (when the bar is still visible) or its filler child - // (when the bar is hidden). If it is still visible, we keep - // it enabled, if it's hidden, we disable pointer events. - var box = bar.getBoundingClientRect(); - var elt = document.elementFromPoint(box.left + 1, box.bottom - 1); - if (elt != bar) bar.style.pointerEvents = "none"; - else delay.set(1000, maybeDisable); - } - delay.set(1000, maybeDisable); - }, - clear: function() { - var parent = this.horiz.parentNode; - parent.removeChild(this.horiz); - parent.removeChild(this.vert); - } - }, NativeScrollbars.prototype); - - function NullScrollbars() {} - - NullScrollbars.prototype = copyObj({ - update: function() { return {bottom: 0, right: 0}; }, - setScrollLeft: function() {}, - setScrollTop: function() {}, - clear: function() {} - }, NullScrollbars.prototype); - - CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars}; - - function initScrollbars(cm) { - if (cm.display.scrollbars) { - cm.display.scrollbars.clear(); - if (cm.display.scrollbars.addClass) - rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); - } - - cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) { - cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller); - // Prevent clicks in the scrollbars from killing focus - on(node, "mousedown", function() { - if (cm.state.focused) setTimeout(function() { cm.display.input.focus(); }, 0); - }); - node.setAttribute("cm-not-content", "true"); - }, function(pos, axis) { - if (axis == "horizontal") setScrollLeft(cm, pos); - else setScrollTop(cm, pos); - }, cm); - if (cm.display.scrollbars.addClass) - addClass(cm.display.wrapper, cm.display.scrollbars.addClass); - } - - function updateScrollbars(cm, measure) { - if (!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++) { - if (startWidth != cm.display.barWidth && cm.options.lineWrapping) - updateHeightsInViewport(cm); - updateScrollbarsInner(cm, measureForScrollbars(cm)); - startWidth = cm.display.barWidth; startHeight = cm.display.barHeight; - } - } - - // Re-synchronize the fake scrollbars with the actual size of the - // content. - function updateScrollbarsInner(cm, measure) { - var d = cm.display; - var 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" - - if (sizes.right && sizes.bottom) { - d.scrollbarFiller.style.display = "block"; - d.scrollbarFiller.style.height = sizes.bottom + "px"; - d.scrollbarFiller.style.width = sizes.right + "px"; - } else d.scrollbarFiller.style.display = ""; - if (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"; - } else d.gutterFiller.style.display = ""; - } - - // Compute the lines that are visible in a given viewport (defaults - // the the current scroll position). viewport may contain top, - // height, and ensure (see op.scrollToPos) properties. - function visibleLines(display, doc, viewport) { - var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop; - top = Math.floor(top - paddingTop(display)); - var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight; - - var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom); - // Ensure is a {from: {line, ch}, to: {line, ch}} object, and - // forces those lines into the viewport (if possible). - if (viewport && viewport.ensure) { - var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line; - if (ensureFrom < from) { - from = ensureFrom; - to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight); - } else if (Math.min(ensureTo, doc.lastLine()) >= to) { - from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight); - to = ensureTo; + 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) { + buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, + collapsed.marker, collapsed.from == null) + if (collapsed.to == null) { return } + if (collapsed.to == pos) { collapsed = false } } } - return {from: from, to: Math.max(to, from + 1)}; - } - - // LINE NUMBERS + if (pos >= len) { break } - // Re-align line numbers and gutter marks to compensate for - // horizontal scrolling. - function alignHorizontally(cm) { - var display = cm.display, view = display.view; - if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return; - var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; - var gutterW = display.gutters.offsetWidth, left = comp + "px"; - for (var i = 0; i < view.length; i++) if (!view[i].hidden) { - if (cm.options.fixedGutter) { - if (view[i].gutter) - view[i].gutter.style.left = left; - if (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; - } - if (cm.options.fixedGutter) - display.gutters.style.left = (comp + gutterW) + "px"; - } - - // Used to ensure that the line number gutter is still the right - // size for the current document size. Returns true when an update - // is needed. - function maybeUpdateLineNumberWidth(cm) { - if (!cm.options.lineNumbers) return false; - var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display; - if (last.length != display.lineNumChars) { - var test = display.measure.appendChild(elt("div", [elt("div", last)], - "CodeMirror-linenumber CodeMirror-gutter-elt")); - var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; - display.lineGutter.style.width = ""; - display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1; - display.lineNumWidth = display.lineNumInnerWidth + padding; - display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; - display.lineGutter.style.width = display.lineNumWidth + "px"; - updateGutterSpace(cm); - return true; - } - return false; - } - - function lineNumberFor(options, i) { - return String(options.lineNumberFormatter(i + options.firstLineNumber)); - } - - // Computes display.scroller.scrollLeft + display.gutters.offsetWidth, - // but using getBoundingClientRect to get a sub-pixel-accurate - // result. - function compensateForHScroll(display) { - return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left; - } - - // DISPLAY DRAWING - - function DisplayUpdate(cm, viewport, force) { - var display = cm.display; - - this.viewport = viewport; - // Store some values that we'll need later (but don't want to force a relayout for) - 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 = []; - } - - DisplayUpdate.prototype.signal = function(emitter, type) { - if (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 upto = Math.min(len, nextChange) + while (true) { + if (text) { + var end = pos + text.length + if (!collapsed) { + var tokenText = end > upto ? text.slice(0, upto - pos) : text + builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, + spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css) + } + if (end >= upto) {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) + } + } +} + + +// These objects are used to represent the visible (currently drawn) +// part of the document. A LineView may correspond to multiple +// logical lines, if those are connected by collapsed ranges. +function LineView(doc, line, lineN) { + // The starting line + this.line = line + // Continuing lines, if any + this.rest = visualLineContinued(line) + // Number of logical lines in this visual line + this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1 + this.node = this.text = null + this.hidden = lineIsHidden(doc, line) +} + +// Create a range of LineView objects for the given lines. +function buildViewArray(cm, from, to) { + var array = [], nextPos + for (var 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 pushOperation(op) { + if (operationGroup) { + operationGroup.ops.push(op) + } else { + op.ownsGroup = operationGroup = { + ops: [op], + delayedCallbacks: [] + } + } +} + +function fireCallbacksForOps(group) { + // Calls delayed callbacks and cursorActivity handlers until no + // new ones appear + 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) + { while (op.cursorActivityCalled < op.cursorActivityHandlers.length) + { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm) } } + } + } while (i < callbacks.length) +} + +function finishOperation(op, endCb) { + var group = op.ownsGroup + if (!group) { return } + + try { fireCallbacksForOps(group) } + finally { + operationGroup = null + endCb(group) + } +} + +var orphanDelayedCallbacks = null + +// Often, we want to signal events at a point where we are in the +// middle of some work, but don't want the handler to start calling +// other methods on the editor, which might be in an inconsistent +// state or simply not expect any other events to happen. +// signalLater looks whether there are any handlers, and schedules +// them to be executed when the last operation ends, or, if no +// operation is active, when a timeout fires. +function signalLater(emitter, type /*, values...*/) { + var arr = getHandlers(emitter, type, false) + if (!arr.length) { return } + var args = Array.prototype.slice.call(arguments, 2), list + if (operationGroup) { + list = operationGroup.delayedCallbacks + } else if (orphanDelayedCallbacks) { + list = orphanDelayedCallbacks + } else { + list = orphanDelayedCallbacks = [] + setTimeout(fireOrphanDelayed, 0) + } + var loop = function ( i ) { + list.push(function () { return arr[i].apply(null, args); }) }; - function maybeClipScrollbars(cm) { - var display = cm.display; - if (!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 = true; - } + for (var i = 0; i < arr.length; ++i) + loop( i ); +} + +function fireOrphanDelayed() { + var delayed = orphanDelayedCallbacks + orphanDelayedCallbacks = null + for (var i = 0; i < delayed.length; ++i) { delayed[i]() } +} + +// When an aspect of a line changes, a string is added to +// lineView.changes. This updates the relevant part of the line's +// DOM structure. +function updateLineForChanges(cm, lineView, lineN, dims) { + for (var j = 0; j < lineView.changes.length; j++) { + var type = lineView.changes[j] + if (type == "text") { updateLineText(cm, lineView) } + else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims) } + else if (type == "class") { updateLineClasses(lineView) } + else if (type == "widget") { updateLineWidgets(cm, lineView, dims) } + } + lineView.changes = null +} + +// Lines with gutter elements, widgets or a background class need to +// be wrapped, and have the extra elements added to the wrapper div +function ensureLineWrapped(lineView) { + if (lineView.node == lineView.text) { + lineView.node = elt("div", null, null, "position: relative") + if (lineView.text.parentNode) + { lineView.text.parentNode.replaceChild(lineView.node, lineView.text) } + lineView.node.appendChild(lineView.text) + if (ie && ie_version < 8) { lineView.node.style.zIndex = 2 } + } + return lineView.node +} + +function updateLineBackground(lineView) { + var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass + if (cls) { cls += " CodeMirror-linebackground" } + if (lineView.background) { + if (cls) { lineView.background.className = cls } + else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null } + } else if (cls) { + var wrap = ensureLineWrapped(lineView) + lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild) + } +} + +// Wrapper around buildLineContent which will reuse the structure +// in display.externalMeasured when possible. +function getLineContent(cm, lineView) { + var ext = cm.display.externalMeasured + if (ext && ext.line == lineView.line) { + cm.display.externalMeasured = null + lineView.measure = ext.measure + return ext.built + } + return buildLineContent(cm, lineView) +} + +// Redraw the line's text. Interacts with the background and text +// classes because the mode may output tokens that influence these +// classes. +function updateLineText(cm, lineView) { + var cls = lineView.text.className + var built = getLineContent(cm, lineView) + if (lineView.text == lineView.node) { lineView.node = built.pre } + lineView.text.parentNode.replaceChild(built.pre, lineView.text) + lineView.text = built.pre + if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { + lineView.bgClass = built.bgClass + lineView.textClass = built.textClass + updateLineClasses(lineView) + } else if (cls) { + lineView.text.className = cls + } +} + +function updateLineClasses(lineView) { + updateLineBackground(lineView) + if (lineView.line.wrapClass) + { ensureLineWrapped(lineView).className = lineView.line.wrapClass } + else if (lineView.node != lineView.text) + { lineView.node.className = "" } + var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass + lineView.text.className = textClass || "" +} + +function updateLineGutter(cm, lineView, lineN, dims) { + if (lineView.gutter) { + lineView.node.removeChild(lineView.gutter) + lineView.gutter = null + } + if (lineView.gutterBackground) { + lineView.node.removeChild(lineView.gutterBackground) + lineView.gutterBackground = null + } + if (lineView.line.gutterClass) { + var 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")) + wrap.insertBefore(lineView.gutterBackground, lineView.text) + } + var markers = lineView.line.gutterMarkers + if (cm.options.lineNumbers || markers) { + var wrap$1 = ensureLineWrapped(lineView) + var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px")) + cm.display.input.setUneditable(gutterWrap) + wrap$1.insertBefore(gutterWrap, lineView.text) + if (lineView.line.gutterClass) + { gutterWrap.className += " " + lineView.line.gutterClass } + if (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"))) } + if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) { + var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id] + if (found) + { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", + ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))) } + } } + } +} + +function updateLineWidgets(cm, lineView, dims) { + if (lineView.alignable) { lineView.alignable = null } + for (var node = lineView.node.firstChild, next = void 0; node; node = next) { + next = node.nextSibling + if (node.className == "CodeMirror-linewidget") + { lineView.node.removeChild(node) } + } + insertLineWidgets(cm, lineView, dims) +} + +// Build a line's DOM representation from scratch +function buildLineElement(cm, lineView, lineN, dims) { + var built = getLineContent(cm, lineView) + lineView.text = lineView.node = built.pre + if (built.bgClass) { lineView.bgClass = built.bgClass } + if (built.textClass) { lineView.textClass = built.textClass } + + updateLineClasses(lineView) + updateLineGutter(cm, lineView, lineN, dims) + insertLineWidgets(cm, lineView, dims) + return lineView.node +} + +// A lineView may contain multiple logical lines (when merged by +// collapsed spans). The widgets for all of them need to be drawn. +function insertLineWidgets(cm, lineView, dims) { + insertLineWidgetsFor(cm, lineView.line, lineView, dims, true) + if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++) + { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false) } } +} + +function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { + if (!line.widgets) { return } + var wrap = ensureLineWrapped(lineView) + for (var i = 0, ws = line.widgets; i < ws.length; ++i) { + var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget") + if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true") } + positionLineWidget(widget, node, lineView, dims) + cm.display.input.setUneditable(node) + if (allowAbove && widget.above) + { wrap.insertBefore(node, lineView.gutter || lineView.text) } + else + { wrap.appendChild(node) } + signalLater(widget, "redraw") + } +} + +function positionLineWidget(widget, node, lineView, dims) { + if (widget.noHScroll) { + ;(lineView.alignable || (lineView.alignable = [])).push(node) + var width = dims.wrapperWidth + node.style.left = dims.fixedPos + "px" + if (!widget.coverGutter) { + width -= dims.gutterTotalWidth + node.style.paddingLeft = dims.gutterTotalWidth + "px" + } + node.style.width = width + "px" + } + if (widget.coverGutter) { + node.style.zIndex = 5 + node.style.position = "relative" + if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px" } + } +} + +function widgetHeight(widget) { + if (widget.height != null) { return widget.height } + var cm = widget.doc.cm + if (!cm) { return 0 } + if (!contains(document.body, widget.node)) { + var parentStyle = "position: relative;" + if (widget.coverGutter) + { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;" } + if (widget.noHScroll) + { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;" } + removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)) + } + return widget.height = widget.node.parentNode.offsetHeight +} + +// Return true when the given mouse event happened in a widget +function eventInWidget(display, e) { + for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { + if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") || + (n.parentNode == display.sizer && n != display.mover)) + { return true } + } +} + +// POSITION MEASUREMENT + +function paddingTop(display) {return display.lineSpace.offsetTop} +function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight} +function paddingH(display) { + if (display.cachedPaddingH) { return display.cachedPaddingH } + var e = removeChildrenAndAdd(display.measure, elt("pre", "x")) + var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle + var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)} + if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data } + return data +} + +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 +} + +// Ensure the lineView.wrapping.heights array is populated. This is +// an array of bottom offsets for the lines that make up a drawn +// line. When lineWrapping is on, there might be more than one +// height. +function ensureLineHeights(cm, lineView, rect) { + var wrapping = cm.options.lineWrapping + var curWidth = wrapping && displayWidth(cm) + if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { + var heights = lineView.measure.heights = [] + if (wrapping) { + lineView.measure.width = curWidth + var rects = lineView.text.firstChild.getClientRects() + for (var i = 0; i < rects.length - 1; i++) { + var cur = rects[i], next = rects[i + 1] + if (Math.abs(cur.bottom - next.bottom) > 2) + { heights.push((cur.bottom + next.top) / 2 - rect.top) } + } + } + heights.push(rect.bottom - rect.top) + } +} + +// Find a line map (mapping character offsets to text nodes) and a +// measurement cache for the given line number. (A line view might +// contain multiple lines when collapsed ranges are present.) +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: true} } } +} + +// Render a line into the hidden node display.externalMeasured. Used +// when measurement is needed for a line that's not in the viewport. +function updateExternalMeasurement(cm, line) { + line = visualLine(line) + var lineN = lineNo(line) + var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN) + view.lineN = lineN + var built = view.built = buildLineContent(cm, view) + view.text = built.pre + removeChildrenAndAdd(cm.display.lineMeasure, built.pre) + return view +} + +// Get a {top, bottom, left, right} box (in line-local coordinates) +// for a given character. +function measureChar(cm, line, ch, bias) { + return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias) +} + +// Find a line view that corresponds to the given line number. +function findViewForLine(cm, lineN) { + if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) + { return cm.display.view[findViewIndex(cm, lineN)] } + var ext = cm.display.externalMeasured + if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) + { return ext } +} + +// Measurement can be split in two steps, the set-up work that +// applies to the whole line, and the measurement of the actual +// character. Functions like coordsChar, that need to do a lot of +// measurements in a row, can thus ensure that the set-up work is +// only done once. +function prepareMeasureForLine(cm, line) { + var lineN = lineNo(line) + var view = findViewForLine(cm, lineN) + if (view && !view.text) { + view = null + } else if (view && view.changes) { + updateLineForChanges(cm, view, lineN, getDimensions(cm)) + cm.curOp.forceUpdate = true + } + if (!view) + { view = updateExternalMeasurement(cm, line) } + + var info = mapFromLineView(view, line, lineN) + return { + line: line, view: view, rect: null, + map: info.map, cache: info.cache, before: info.before, + hasHeights: false + } +} + +// Given a prepared measurement object, measures the position of an +// actual character (or fetches it from the cache). +function measureCharPrepared(cm, prepared, ch, bias, varHeight) { + if (prepared.before) { ch = -1 } + var key = ch + (bias || ""), found + if (prepared.cache.hasOwnProperty(key)) { + found = prepared.cache[key] + } else { + if (!prepared.rect) + { prepared.rect = prepared.view.text.getBoundingClientRect() } + if (!prepared.hasHeights) { + ensureLineHeights(cm, prepared.view, prepared.rect) + prepared.hasHeights = true + } + found = measureCharInner(cm, prepared, ch, bias) + if (!found.bogus) { prepared.cache[key] = found } + } + return {left: found.left, right: found.right, + top: varHeight ? found.rtop : found.top, + bottom: varHeight ? found.rbottom : found.bottom} +} + +var nullRect = {left: 0, right: 0, top: 0, bottom: 0} + +function nodeAndOffsetInLineMap(map, ch, bias) { + var node, start, end, collapse, mStart, mEnd + // First, search the line map for the text node corresponding to, + // or closest to, the target character. + for (var i = 0; i < map.length; i += 3) { + mStart = map[i] + mEnd = map[i + 1] + if (ch < mStart) { + start = 0; end = 1 + collapse = "left" + } else if (ch < mEnd) { + start = ch - mStart + end = start + 1 + } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) { + end = mEnd - mStart + start = end - 1 + if (ch >= mEnd) { collapse = "right" } + } + if (start != null) { + node = map[i + 2] + if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) + { collapse = bias } + if (bias == "left" && start == 0) + { while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) { + node = map[(i -= 3) + 2] + collapse = "left" + } } + if (bias == "right" && start == mEnd - mStart) + { while (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 getUsefulRect(rects, bias) { + var rect = nullRect + if (bias == "left") { for (var i = 0; i < rects.length; i++) { + if ((rect = rects[i]).left != rect.right) { break } + } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) { + if ((rect = rects[i$1]).left != rect.right) { break } + } } + return rect +} + +function measureCharInner(cm, prepared, ch, bias) { + var place = nodeAndOffsetInLineMap(prepared.map, ch, bias) + var node = place.node, start = place.start, end = place.end, collapse = place.collapse + + var rect + if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates. + for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned + while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start } + while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end } + if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) + { rect = node.parentNode.getBoundingClientRect() } + else + { rect = getUsefulRect(range(node, start, end).getClientRects(), bias) } + if (rect.left || rect.right || start == 0) { break } + end = start + start = start - 1 + collapse = "right" + } + if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect) } + } else { // If it is a widget, simply get the box for the whole widget. + if (start > 0) { collapse = bias = "right" } + var rects + if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) + { rect = rects[bias == "right" ? rects.length - 1 : 0] } + else + { rect = node.getBoundingClientRect() } } - - // Does the actual updating of the line display. Bails out - // (returning false) when there is nothing to be done and forced is - // false. - function updateDisplayIfNeeded(cm, update) { - var display = cm.display, doc = cm.doc; - - if (update.editorIsHidden) { - resetView(cm); - return false; - } - - // Bail out if the visible area is already rendered and nothing changed. - if (!update.force && - update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && - (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && - display.renderedView == display.view && countDirtyView(cm) == 0) - return false; - - if (maybeUpdateLineNumberWidth(cm)) { - resetView(cm); - update.dims = getDimensions(cm); + if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { + var rSpan = node.parentNode.getClientRects()[0] + if (rSpan) + { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom} } + else + { rect = nullRect } + } + + var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top + var mid = (rtop + rbot) / 2 + var heights = prepared.view.measure.heights + var i = 0 + for (; i < heights.length - 1; i++) + { if (mid < heights[i]) { break } } + var top = i ? heights[i - 1] : 0, bot = heights[i] + var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, + right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, + top: top, bottom: bot} + if (!rect.left && !rect.right) { result.bogus = true } + if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot } + + return result +} + +// Work around problem with bounding client rects on ranges being +// returned incorrectly when zoomed on IE10 and below. +function maybeUpdateRectForZooming(measure, rect) { + if (!window.screen || screen.logicalXDPI == null || + screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) + { return rect } + var scaleX = screen.logicalXDPI / screen.deviceXDPI + var scaleY = screen.logicalYDPI / screen.deviceYDPI + return {left: rect.left * scaleX, right: rect.right * scaleX, + top: rect.top * scaleY, bottom: rect.bottom * scaleY} +} + +function clearLineMeasurementCacheFor(lineView) { + if (lineView.measure) { + lineView.measure.cache = {} + lineView.measure.heights = null + if (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 + if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true } + cm.display.lineNumChars = null +} + +function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft } +function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop } + +// Converts a {top, bottom, left, right} box from line-local +// coordinates into another coordinate system. Context may be one of +// "line", "div" (display.lineDiv), "local"./null (editor), "window", +// or "page". +function intoCoordSystem(cm, lineObj, rect, context) { + if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above) { + var size = widgetHeight(lineObj.widgets[i]) + rect.top += size; rect.bottom += size + } } } + if (context == "line") { return rect } + if (!context) { context = "local" } + var yOff = heightAtLine(lineObj) + if (context == "local") { yOff += paddingTop(cm.display) } + else { yOff -= cm.display.viewOffset } + if (context == "page" || context == "window") { + var lOff = cm.display.lineSpace.getBoundingClientRect() + yOff += lOff.top + (context == "window" ? 0 : pageScrollY()) + var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()) + rect.left += xOff; rect.right += xOff + } + rect.top += yOff; rect.bottom += yOff + return rect +} + +// Coverts a box from "div" coords to another coordinate system. +// Context may be "window", "page", "div", or "local"./null. +function fromCoordSystem(cm, coords, context) { + if (context == "div") { return coords } + var left = coords.left, top = coords.top + // First move into "page" coordinate system + if (context == "page") { + left -= pageScrollX() + top -= pageScrollY() + } else if (context == "local" || !context) { + var localBox = cm.display.sizer.getBoundingClientRect() + left += localBox.left + top += localBox.top + } + + var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect() + return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top} +} + +function charCoords(cm, pos, context, lineObj, bias) { + if (!lineObj) { lineObj = getLine(cm.doc, pos.line) } + return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context) +} + +// Returns a box for a given cursor position, which may have an +// 'other' property containing the position of the secondary cursor +// on a bidi boundary. +function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { + lineObj = lineObj || getLine(cm.doc, pos.line) + if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj) } + function get(ch, right) { + var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight) + if (right) { m.left = m.right; } else { m.right = m.left } + return intoCoordSystem(cm, lineObj, m, context) + } + function getBidi(ch, partPos) { + var part = order[partPos], right = part.level % 2 + if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) { + part = order[--partPos] + ch = bidiRight(part) - (part.level % 2 ? 0 : 1) + right = true + } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) { + part = order[++partPos] + ch = bidiLeft(part) - part.level % 2 + right = false + } + if (right && ch == part.to && ch > part.from) { return get(ch - 1) } + return get(ch, right) + } + var order = getOrder(lineObj), ch = pos.ch + if (!order) { return get(ch) } + var partPos = getBidiPartAt(order, ch) + var val = getBidi(ch, partPos) + if (bidiOther != null) { val.other = getBidi(ch, bidiOther) } + return val +} + +// Used to cheaply estimate the coordinates for a position. Used for +// intermediate scroll updates. +function estimateCoords(cm, pos) { + var left = 0 + pos = clipPos(cm.doc, pos) + if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch } + var lineObj = getLine(cm.doc, pos.line) + var top = heightAtLine(lineObj) + paddingTop(cm.display) + return {left: left, right: left, top: top, bottom: top + lineObj.height} +} + +// Positions returned by coordsChar contain some extra information. +// xRel is the relative x position of the input coordinates compared +// to the found position (so xRel > 0 means the coordinates are to +// the right of the character position, for example). When outside +// is true, that means the coordinates lie outside the line's +// vertical range. +function PosWithInfo(line, ch, outside, xRel) { + var pos = Pos(line, ch) + pos.xRel = xRel + if (outside) { pos.outside = true } + return pos +} + +// Compute the character position closest to the given coordinates. +// Input must be lineSpace-local ("div" coordinate system). +function coordsChar(cm, x, y) { + var doc = cm.doc + y += cm.display.viewOffset + if (y < 0) { return PosWithInfo(doc.first, 0, true, -1) } + var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1 + if (lineN > last) + { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1) } + if (x < 0) { x = 0 } + + var lineObj = getLine(doc, lineN) + for (;;) { + var found = coordsCharInner(cm, lineObj, lineN, x, y) + var merged = collapsedSpanAtEnd(lineObj) + var mergedPos = merged && merged.find(0, true) + if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0)) + { lineN = lineNo(lineObj = mergedPos.to.line) } + else + { return found } + } +} + +function coordsCharInner(cm, lineObj, lineNo, x, y) { + var innerOff = y - heightAtLine(lineObj) + var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth + var preparedMeasure = prepareMeasureForLine(cm, lineObj) + + function getX(ch) { + var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure) + wrongLine = true + if (innerOff > sp.bottom) { return sp.left - adjust } + else if (innerOff < sp.top) { return sp.left + adjust } + else { wrongLine = false } + return sp.left + } + + var bidi = getOrder(lineObj), dist = lineObj.text.length + var from = lineLeft(lineObj), to = lineRight(lineObj) + var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine + + if (x > toX) { return PosWithInfo(lineNo, to, toOutside, 1) } + // Do a binary search between these bounds. + for (;;) { + if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) { + var ch = x < fromX || x - fromX <= toX - x ? from : to + var outside = ch == from ? fromOutside : toOutside + var xDiff = x - (ch == from ? fromX : toX) + // This is a kludge to handle the case where the coordinates + // are after a line-wrapped line. We should replace it with a + // more general handling of cursor positions around line + // breaks. (Issue #4078) + if (toOutside && !bidi && !/\s/.test(lineObj.text.charAt(ch)) && xDiff > 0 && + ch < lineObj.text.length && preparedMeasure.view.measure.heights.length > 1) { + var charSize = measureCharPrepared(cm, preparedMeasure, ch, "right") + if (innerOff <= charSize.bottom && innerOff >= charSize.top && Math.abs(x - charSize.right) < xDiff) { + outside = false + ch++ + xDiff = x - charSize.right + } + } + while (isExtendingChar(lineObj.text.charAt(ch))) { ++ch } + var pos = PosWithInfo(lineNo, ch, outside, xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0) + return pos + } + var step = Math.ceil(dist / 2), middle = from + step + if (bidi) { + middle = from + for (var i = 0; i < step; ++i) { middle = moveVisually(lineObj, middle, 1) } + } + var middleX = getX(middle) + if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) { toX += 1000; } dist = step} + else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step} + } +} + +var measureText +// Compute the default text height. +function textHeight(display) { + if (display.cachedTextHeight != null) { return display.cachedTextHeight } + if (measureText == null) { + measureText = elt("pre") + // Measure a bunch of lines, for browsers that compute + // fractional heights. + 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 + if (height > 3) { display.cachedTextHeight = height } + removeChildren(display.measure) + return height || 1 +} + +// Compute the default character width. +function charWidth(display) { + if (display.cachedCharWidth != null) { return display.cachedCharWidth } + var anchor = elt("span", "xxxxxxxxxx") + var pre = elt("pre", [anchor]) + removeChildrenAndAdd(display.measure, pre) + var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10 + if (width > 2) { display.cachedCharWidth = width } + return width || 10 +} + +// Do a bulk-read of the DOM positions and sizes needed to draw the +// view, so that we don't interleave reading and writing to the DOM. +function getDimensions(cm) { + var d = cm.display, left = {}, width = {} + var gutterLeft = d.gutters.clientLeft + for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { + left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft + width[cm.options.gutters[i]] = n.clientWidth + } + return {fixedPos: compensateForHScroll(d), + gutterTotalWidth: d.gutters.offsetWidth, + gutterLeft: left, + gutterWidth: width, + wrapperWidth: d.wrapper.clientWidth} +} + +// Computes display.scroller.scrollLeft + display.gutters.offsetWidth, +// but using getBoundingClientRect to get a sub-pixel-accurate +// result. +function compensateForHScroll(display) { + return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left +} + +// Returns a function that estimates the height of a line, to use as +// first approximation until the line becomes visible (and is thus +// properly measurable). +function estimateHeight(cm) { + var th = textHeight(cm.display), wrapping = cm.options.lineWrapping + var 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++) { + if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height } + } } + + if (wrapping) + { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th } + else + { return widgetsHeight + th } + } +} + +function estimateLineHeights(cm) { + var doc = cm.doc, est = estimateHeight(cm) + doc.iter(function (line) { + var estHeight = est(line) + if (estHeight != line.height) { updateLineHeight(line, estHeight) } + }) +} + +// Given a mouse event, find the corresponding position. If liberal +// is false, it checks whether a gutter or scrollbar was clicked, +// and returns null if it was. forRect is used by rectangular +// selections, and tries to estimate a character position even for +// coordinates beyond the right of the text. +function posFromMouse(cm, e, liberal, forRect) { + var display = cm.display + if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null } + + var x, y, space = display.lineSpace.getBoundingClientRect() + // Fails unpredictably on IE[67] when mouse is dragged around quickly. + try { x = e.clientX - space.left; y = e.clientY - space.top } + catch (e) { return null } + var coords = coordsChar(cm, x, y), line + if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { + var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length + coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)) + } + return coords +} + +// Find the view element corresponding to a given line. Return null +// when the line isn't visible. +function findViewIndex(cm, n) { + if (n >= cm.display.viewTo) { return null } + n -= cm.display.viewFrom + if (n < 0) { return null } + var view = cm.display.view + for (var i = 0; i < view.length; i++) { + n -= view[i].size + if (n < 0) { return i } + } +} + +function updateSelection(cm) { + cm.display.input.showSelection(cm.display.input.prepareSelection()) +} + +function prepareSelection(cm, primary) { + var doc = cm.doc, result = {} + var curFragment = result.cursors = document.createDocumentFragment() + var selFragment = result.selection = document.createDocumentFragment() + + for (var i = 0; i < doc.sel.ranges.length; i++) { + if (primary === false && i == doc.sel.primIndex) { continue } + var range = doc.sel.ranges[i] + if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue } + var collapsed = range.empty() + if (collapsed || cm.options.showCursorWhenSelecting) + { drawSelectionCursor(cm, range.head, curFragment) } + if (!collapsed) + { drawSelectionRange(cm, range, selFragment) } + } + return result +} + +// Draws a cursor for the given range +function drawSelectionCursor(cm, head, output) { + var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine) + + var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")) + cursor.style.left = pos.left + "px" + cursor.style.top = pos.top + "px" + cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px" + + if (pos.other) { + // Secondary cursor, shown when on a 'jump' in bi-directional text + var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")) + otherCursor.style.display = "" + otherCursor.style.left = pos.other.left + "px" + otherCursor.style.top = pos.other.top + "px" + otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px" + } +} + +// Draws the given range as a highlighted selection +function drawSelectionRange(cm, range, output) { + var display = cm.display, doc = cm.doc + var fragment = document.createDocumentFragment() + var padding = paddingH(cm.display), leftSide = padding.left + var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right + + function add(left, top, width, bottom) { + if (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: " + (width == null ? rightSide - left : width) + "px;\n height: " + (bottom - top) + "px"))) + } + + function drawForLine(line, fromArg, toArg) { + var lineObj = getLine(doc, line) + var lineLen = lineObj.text.length + var start, end + function coords(ch, bias) { + return charCoords(cm, Pos(line, ch), "div", lineObj, bias) + } + + iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir) { + var leftPos = coords(from, "left"), rightPos, left, right + if (from == to) { + rightPos = leftPos + left = right = leftPos.left + } else { + rightPos = coords(to - 1, "right") + if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp } + left = leftPos.left + right = rightPos.right + } + if (fromArg == null && from == 0) { left = leftSide } + if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part + add(left, leftPos.top, null, leftPos.bottom) + left = leftSide + if (leftPos.bottom < rightPos.top) { add(left, leftPos.bottom, null, rightPos.top) } + } + if (toArg == null && to == lineLen) { right = rightSide } + if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left) + { start = leftPos } + if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right) + { end = rightPos } + if (left < leftSide + 1) { left = leftSide } + add(left, rightPos.top, right - left, rightPos.bottom) + }) + return {start: start, end: end} + } + + var sFrom = range.from(), sTo = range.to() + if (sFrom.line == sTo.line) { + drawForLine(sFrom.line, sFrom.ch, sTo.ch) + } else { + var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line) + var singleVLine = visualLine(fromLine) == visualLine(toLine) + var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end + var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start + if (singleVLine) { + if (leftEnd.top < rightStart.top - 2) { + add(leftEnd.right, leftEnd.top, null, leftEnd.bottom) + add(leftSide, rightStart.top, rightStart.left, rightStart.bottom) + } else { + add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom) + } + } + if (leftEnd.bottom < rightStart.top) + { add(leftSide, leftEnd.bottom, null, rightStart.top) } + } + + output.appendChild(fragment) +} + +// Cursor-blinking +function restartBlink(cm) { + if (!cm.state.focused) { return } + var display = cm.display + clearInterval(display.blinker) + var on = true + display.cursorDiv.style.visibility = "" + if (cm.options.cursorBlinkRate > 0) + { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; }, + cm.options.cursorBlinkRate) } + else if (cm.options.cursorBlinkRate < 0) + { display.cursorDiv.style.visibility = "hidden" } +} + +function ensureFocus(cm) { + if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm) } +} + +function delayBlurEvent(cm) { + cm.state.delayingBlurEvent = true + setTimeout(function () { if (cm.state.delayingBlurEvent) { + cm.state.delayingBlurEvent = false + onBlur(cm) + } }, 100) +} + +function onFocus(cm, e) { + if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false } + + if (cm.options.readOnly == "nocursor") { return } + if (!cm.state.focused) { + signal(cm, "focus", cm, e) + cm.state.focused = true + addClass(cm.display.wrapper, "CodeMirror-focused") + // This test prevents this from firing when a context + // menu is closed (since the input reset would kill the + // select-all detection hack) + if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { + cm.display.input.reset() + if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20) } // Issue #1730 + } + cm.display.input.receivedFocus() + } + restartBlink(cm) +} +function onBlur(cm, e) { + if (cm.state.delayingBlurEvent) { return } + + if (cm.state.focused) { + signal(cm, "blur", cm, e) + cm.state.focused = false + rmClass(cm.display.wrapper, "CodeMirror-focused") + } + clearInterval(cm.display.blinker) + setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false } }, 150) +} + +// Re-align line numbers and gutter marks to compensate for +// horizontal scrolling. +function alignHorizontally(cm) { + var display = cm.display, view = display.view + if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return } + var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft + var gutterW = display.gutters.offsetWidth, left = comp + "px" + for (var i = 0; i < view.length; i++) { if (!view[i].hidden) { + if (cm.options.fixedGutter) { + if (view[i].gutter) + { view[i].gutter.style.left = left } + if (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 } } + } } + if (cm.options.fixedGutter) + { display.gutters.style.left = (comp + gutterW) + "px" } +} + +// Used to ensure that the line number gutter is still the right +// size for the current document size. Returns true when an update +// is needed. +function maybeUpdateLineNumberWidth(cm) { + if (!cm.options.lineNumbers) { return false } + var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display + if (last.length != display.lineNumChars) { + var test = display.measure.appendChild(elt("div", [elt("div", last)], + "CodeMirror-linenumber CodeMirror-gutter-elt")) + var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW + display.lineGutter.style.width = "" + display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1 + display.lineNumWidth = display.lineNumInnerWidth + padding + display.lineNumChars = display.lineNumInnerWidth ? last.length : -1 + display.lineGutter.style.width = display.lineNumWidth + "px" + updateGutterSpace(cm) + return true + } + return false +} + +// Read the actual heights of the rendered lines, and update their +// stored heights to match. +function updateHeightsInViewport(cm) { + var display = cm.display + var prevBottom = display.lineDiv.offsetTop + for (var i = 0; i < display.view.length; i++) { + var cur = display.view[i], height = void 0 + if (cur.hidden) { continue } + if (ie && ie_version < 8) { + var bot = cur.node.offsetTop + cur.node.offsetHeight + height = bot - prevBottom + prevBottom = bot + } else { + var box = cur.node.getBoundingClientRect() + height = box.bottom - box.top + } + var diff = cur.line.height - height + if (height < 2) { height = textHeight(display) } + if (diff > .001 || diff < -.001) { + updateLineHeight(cur.line, height) + updateWidgetHeight(cur.line) + if (cur.rest) { for (var j = 0; j < cur.rest.length; j++) + { updateWidgetHeight(cur.rest[j]) } } + } + } +} + +// Read and store the height of line widgets associated with the +// given line. +function updateWidgetHeight(line) { + if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) + { line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight } } +} + +// Compute the lines that are visible in a given viewport (defaults +// the the current scroll position). viewport may contain top, +// height, and ensure (see op.scrollToPos) properties. +function visibleLines(display, doc, viewport) { + var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop + top = Math.floor(top - paddingTop(display)) + var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight + + var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom) + // Ensure is a {from: {line, ch}, to: {line, ch}} object, and + // forces those lines into the viewport (if possible). + if (viewport && viewport.ensure) { + var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line + if (ensureFrom < from) { + from = ensureFrom + to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight) + } else if (Math.min(ensureTo, doc.lastLine()) >= to) { + from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight) + to = ensureTo + } + } + return {from: from, to: Math.max(to, from + 1)} +} + +// Sync the scrollable area and scrollbars, ensure the viewport +// covers the visible area. +function setScrollTop(cm, val) { + if (Math.abs(cm.doc.scrollTop - val) < 2) { return } + cm.doc.scrollTop = val + if (!gecko) { updateDisplaySimple(cm, {top: val}) } + if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val } + cm.display.scrollbars.setScrollTop(val) + if (gecko) { updateDisplaySimple(cm) } + startWorker(cm, 100) +} +// Sync scroller and scrollbar, ensure the gutter elements are +// aligned. +function setScrollLeft(cm, val, isScroller) { + if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) { return } + val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth) + cm.doc.scrollLeft = val + alignHorizontally(cm) + if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val } + cm.display.scrollbars.setScrollLeft(val) +} + +// Since the delta values reported on mouse wheel events are +// unstandardized between browsers and even browser versions, and +// generally horribly unpredictable, this code starts by measuring +// the scroll effect that the first few mouse wheel events have, +// and, from that, detects the way it can convert deltas to pixel +// offsets afterwards. +// +// The reason we want to know the amount a wheel event will scroll +// is that it gives us a chance to update the display before the +// actual scrolling happens, reducing flickering. + +var wheelSamples = 0; +var wheelPixelsPerUnit = null; +// Fill in a browser-detected starting value on browsers where we +// know one. These don't have to be accurate -- the result of them +// being wrong would just be a slight flicker on the first wheel +// scroll (if it is large enough). +if (ie) { wheelPixelsPerUnit = -.53 } +else if (gecko) { wheelPixelsPerUnit = 15 } +else if (chrome) { wheelPixelsPerUnit = -.7 } +else if (safari) { wheelPixelsPerUnit = -1/3 } + +function wheelEventDelta(e) { + var dx = e.wheelDeltaX, dy = e.wheelDeltaY + if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail } + if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail } + else if (dy == null) { dy = e.wheelDelta } + return {x: dx, y: dy} +} +function wheelEventPixels(e) { + var delta = wheelEventDelta(e) + delta.x *= wheelPixelsPerUnit + delta.y *= wheelPixelsPerUnit + return delta +} + +function onScrollWheel(cm, e) { + var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y + + var display = cm.display, scroll = display.scroller + // Quit if there's nothing to scroll here + var canScrollX = scroll.scrollWidth > scroll.clientWidth + var canScrollY = scroll.scrollHeight > scroll.clientHeight + if (!(dx && canScrollX || dy && canScrollY)) { return } + + // Webkit browsers on OS X abort momentum scrolls when the target + // of the scroll event is removed from the scrollable element. + // This hack (see related code in patchDisplay) makes sure the + // element is kept around. + if (dy && 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 + } + } } + } - // Compute a suitable new viewport (from & to) - var end = doc.first + doc.size; - var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first); - var to = Math.min(end, update.visible.to + cm.options.viewportMargin); - if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom); - if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo); - if (sawCollapsedSpans) { - from = visualLineNo(cm.doc, from); - to = visualLineEndNo(cm.doc, to); + // On some browsers, horizontal scrolling will cause redraws to + // happen before the gutter has been realigned, causing it to + // wriggle around in a most unseemly way. When we have an + // estimated pixels/delta value, we just handle horizontal + // scrolling entirely here. It'll be slightly off from native, but + // better than glitching out. + if (dx && !gecko && !presto && wheelPixelsPerUnit != null) { + if (dy && canScrollY) + { setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight))) } + setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth))) + // Only prevent default scrolling if vertical scrolling is + // actually possible. Otherwise, it causes vertical scroll + // jitter on OSX trackpads when deltaX is small and deltaY + // is large (issue #3579) + if (!dy || (dy && canScrollY)) + { e_preventDefault(e) } + display.wheelStartX = null // Abort measurement, if in progress + return + } + + // 'Project' the visible viewport to cover the area that is being + // scrolled into view (if we know enough to estimate it). + if (dy && wheelPixelsPerUnit != null) { + var pixels = dy * wheelPixelsPerUnit + var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight + if (pixels < 0) { top = Math.max(0, top + pixels - 50) } + else { bot = Math.min(cm.doc.height, bot + pixels + 50) } + updateDisplaySimple(cm, {top: top, bottom: bot}) + } + + if (wheelSamples < 20) { + if (display.wheelStartX == null) { + display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop + display.wheelDX = dx; display.wheelDY = dy + setTimeout(function () { + if (display.wheelStartX == null) { return } + var movedX = scroll.scrollLeft - display.wheelStartX + var movedY = scroll.scrollTop - display.wheelStartY + var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || + (movedX && display.wheelDX && movedX / display.wheelDX) + display.wheelStartX = display.wheelStartY = null + if (!sample) { return } + wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1) + ++wheelSamples + }, 200) + } else { + display.wheelDX += dx; display.wheelDY += dy + } + } +} + +// SCROLLBARS + +// Prepare DOM reads needed to update the scrollbars. Done in one +// shot to minimize update/measure roundtrips. +function measureForScrollbars(cm) { + var d = cm.display, gutterW = d.gutters.offsetWidth + var 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") + var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar") + place(vert); place(horiz) + + on(vert, "scroll", function () { + if (vert.clientHeight) { scroll(vert.scrollTop, "vertical") } + }) + on(horiz, "scroll", function () { + if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal") } + }) + + this.checkedZeroWidth = false + // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). + if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px" } +} + +NativeScrollbars.prototype = copyObj({ + update: function(measure) { + var needsH = measure.scrollWidth > measure.clientWidth + 1 + var needsV = measure.scrollHeight > measure.clientHeight + 1 + var sWidth = measure.nativeBarWidth + + if (needsV) { + this.vert.style.display = "block" + this.vert.style.bottom = needsH ? sWidth + "px" : "0" + var totalHeight = measure.viewHeight - (needsH ? sWidth : 0) + // A bug in IE8 can cause this value to be negative, so guard it. + this.vert.firstChild.style.height = + Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px" + } else { + this.vert.style.display = "" + this.vert.firstChild.style.height = "0" } - var different = from != display.viewFrom || to != display.viewTo || - display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth; - adjustView(cm, from, to); - - display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); - // Position the mover div to align with the current scroll position - cm.display.mover.style.top = display.viewOffset + "px"; - - var toUpdate = countDirtyView(cm); - if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && - (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) - return false; - - // For big changes, we hide the enclosing element during the - // update, since that speeds up the operations on most browsers. - var focused = activeElt(); - if (toUpdate > 4) display.lineDiv.style.display = "none"; - patchDisplay(cm, display.updateLineNumbers, update.dims); - if (toUpdate > 4) display.lineDiv.style.display = ""; - display.renderedView = display.view; - // There might have been a widget with a focused element that got - // hidden or updated, if so re-focus it. - if (focused && activeElt() != focused && focused.offsetHeight) focused.focus(); - - // Prevent selection and cursors from interfering with the scroll - // width and height. - removeChildren(display.cursorDiv); - removeChildren(display.selectionDiv); - display.gutters.style.height = display.sizer.style.minHeight = 0; - - if (different) { - display.lastWrapHeight = update.wrapperHeight; - display.lastWrapWidth = update.wrapperWidth; - startWorker(cm, 400); + if (needsH) { + this.horiz.style.display = "block" + this.horiz.style.right = needsV ? sWidth + "px" : "0" + this.horiz.style.left = measure.barLeft + "px" + var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0) + this.horiz.firstChild.style.width = + (measure.scrollWidth - measure.clientWidth + totalWidth) + "px" + } else { + this.horiz.style.display = "" + this.horiz.firstChild.style.width = "0" + } + + if (!this.checkedZeroWidth && measure.clientHeight > 0) { + if (sWidth == 0) { this.zeroWidthHack() } + this.checkedZeroWidth = true + } + + return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0} + }, + setScrollLeft: function(pos) { + if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos } + if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz) } + }, + setScrollTop: function(pos) { + if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos } + if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert) } + }, + zeroWidthHack: function() { + var w = mac && !mac_geMountainLion ? "12px" : "18px" + this.horiz.style.height = this.vert.style.width = w + this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none" + this.disableHoriz = new Delayed + this.disableVert = new Delayed + }, + enableZeroWidthBar: function(bar, delay) { + bar.style.pointerEvents = "auto" + function maybeDisable() { + // To find out whether the scrollbar is still visible, we + // check whether the element under the pixel in the bottom + // left corner of the scrollbar box is the scrollbar box + // itself (when the bar is still visible) or its filler child + // (when the bar is hidden). If it is still visible, we keep + // it enabled, if it's hidden, we disable pointer events. + var box = bar.getBoundingClientRect() + var elt = document.elementFromPoint(box.left + 1, box.bottom - 1) + if (elt != bar) { bar.style.pointerEvents = "none" } + else { delay.set(1000, maybeDisable) } + } + delay.set(1000, maybeDisable) + }, + clear: function() { + var parent = this.horiz.parentNode + parent.removeChild(this.horiz) + parent.removeChild(this.vert) + } +}, NativeScrollbars.prototype) + +function NullScrollbars() {} + +NullScrollbars.prototype = copyObj({ + update: function() { return {bottom: 0, right: 0} }, + setScrollLeft: function() {}, + setScrollTop: function() {}, + clear: function() {} +}, NullScrollbars.prototype) + +function updateScrollbars(cm, measure) { + if (!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++) { + if (startWidth != cm.display.barWidth && cm.options.lineWrapping) + { updateHeightsInViewport(cm) } + updateScrollbarsInner(cm, measureForScrollbars(cm)) + startWidth = cm.display.barWidth; startHeight = cm.display.barHeight + } +} + +// Re-synchronize the fake scrollbars with the actual size of the +// content. +function updateScrollbarsInner(cm, measure) { + var d = cm.display + var 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" + + if (sizes.right && sizes.bottom) { + d.scrollbarFiller.style.display = "block" + d.scrollbarFiller.style.height = sizes.bottom + "px" + d.scrollbarFiller.style.width = sizes.right + "px" + } else { d.scrollbarFiller.style.display = "" } + if (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" + } else { d.gutterFiller.style.display = "" } +} + +var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars} + +function initScrollbars(cm) { + if (cm.display.scrollbars) { + cm.display.scrollbars.clear() + if (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) + // Prevent clicks in the scrollbars from killing focus + on(node, "mousedown", function () { + if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0) } + }) + node.setAttribute("cm-not-content", "true") + }, function (pos, axis) { + if (axis == "horizontal") { setScrollLeft(cm, pos) } + else { setScrollTop(cm, pos) } + }, cm) + if (cm.display.scrollbars.addClass) + { addClass(cm.display.wrapper, cm.display.scrollbars.addClass) } +} + +// SCROLLING THINGS INTO VIEW + +// If an editor sits on the top or bottom of the window, partially +// scrolled out of view, this ensures that the cursor is visible. +function maybeScrollWindow(cm, coords) { + if (signalDOMEvent(cm, "scrollCursorIntoView")) { return } + + var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null + if (coords.top + box.top < 0) { doScroll = true } + else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false } + if (doScroll != null && !phantom) { + var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (coords.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (coords.left) + "px; width: 2px;")) + cm.display.lineSpace.appendChild(scrollNode) + scrollNode.scrollIntoView(doScroll) + cm.display.lineSpace.removeChild(scrollNode) + } +} + +// Scroll a given position into view (immediately), verifying that +// it actually became visible (as line heights are accurately +// measured, the position of something may 'drift' during drawing). +function scrollPosIntoView(cm, pos, end, margin) { + if (margin == null) { margin = 0 } + var coords + for (var limit = 0; limit < 5; limit++) { + var changed = false + coords = cursorCoords(cm, pos) + var endCoords = !end || end == pos ? coords : cursorCoords(cm, end) + var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left), + Math.min(coords.top, endCoords.top) - margin, + Math.max(coords.left, endCoords.left), + Math.max(coords.bottom, endCoords.bottom) + margin) + var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft + if (scrollPos.scrollTop != null) { + setScrollTop(cm, scrollPos.scrollTop) + if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true } + } + if (scrollPos.scrollLeft != null) { + setScrollLeft(cm, scrollPos.scrollLeft) + if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true } + } + if (!changed) { break } + } + return coords +} + +// Scroll a given set of coordinates into view (immediately). +function scrollIntoView(cm, x1, y1, x2, y2) { + var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2) + if (scrollPos.scrollTop != null) { setScrollTop(cm, scrollPos.scrollTop) } + if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft) } +} + +// Calculate a new scroll position needed to scroll the given +// rectangle into view. Returns an object with scrollTop and +// scrollLeft properties. When these are undefined, the +// vertical/horizontal position does not need to be adjusted. +function calculateScrollPos(cm, x1, y1, x2, y2) { + var display = cm.display, snapMargin = textHeight(cm.display) + if (y1 < 0) { y1 = 0 } + var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop + var screen = displayHeight(cm), result = {} + if (y2 - y1 > screen) { y2 = y1 + screen } + var docBottom = cm.doc.height + paddingVert(display) + var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin + if (y1 < screentop) { + result.scrollTop = atTop ? 0 : y1 + } else if (y2 > screentop + screen) { + var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen) + if (newTop != screentop) { result.scrollTop = newTop } + } + + var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft + var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0) + var tooWide = x2 - x1 > screenw + if (tooWide) { x2 = x1 + screenw } + if (x1 < 10) + { result.scrollLeft = 0 } + else if (x1 < screenleft) + { result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10)) } + else if (x2 > screenw + screenleft - 3) + { result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw } + return result +} + +// Store a relative adjustment to the scroll position in the current +// operation (to be applied when the operation finishes). +function addToScrollPos(cm, left, top) { + if (left != null || top != null) { resolveScrollToPos(cm) } + if (left != null) + { cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left } + if (top != null) + { cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top } +} + +// Make sure that at the end of the operation the current cursor is +// shown. +function ensureCursorVisible(cm) { + resolveScrollToPos(cm) + var cur = cm.getCursor(), from = cur, to = cur + if (!cm.options.lineWrapping) { + from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur + to = Pos(cur.line, cur.ch + 1) + } + cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true} +} + +// When an operation has its scrollToPos property set, and another +// scroll action is applied before the end of the operation, this +// 'simulates' scrolling that position into view in a cheap way, so +// that the effect of intermediate scroll commands is not ignored. +function resolveScrollToPos(cm) { + var range = cm.curOp.scrollToPos + if (range) { + cm.curOp.scrollToPos = null + var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to) + var sPos = calculateScrollPos(cm, Math.min(from.left, to.left), + Math.min(from.top, to.top) - range.margin, + Math.max(from.right, to.right), + Math.max(from.bottom, to.bottom) + range.margin) + cm.scrollTo(sPos.scrollLeft, sPos.scrollTop) + } +} + +// Operations are used to wrap a series of changes to the editor +// state in such a way that each change won't have to update the +// cursor and display (which would be awkward, slow, and +// error-prone). Instead, display updates are batched and then all +// combined and executed at once. + +var nextOpId = 0 +// Start a new operation. +function startOperation(cm) { + cm.curOp = { + cm: cm, + viewChanged: false, // Flag that indicates that lines might need to be redrawn + startHeight: cm.doc.height, // Used to detect need to update scrollbar + forceUpdate: false, // Used to force a redraw + updateInput: null, // Whether to reset the input textarea + typing: false, // Whether this reset should be careful to leave existing text (for compositing) + changeObjs: null, // Accumulated changes, for firing change events + cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on + cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already + selectionChanged: false, // Whether the selection needs to be redrawn + updateMaxLine: false, // Set when the widest line needs to be determined anew + scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet + scrollToPos: null, // Used to scroll to a specific position + focus: false, + id: ++nextOpId // Unique ID + } + pushOperation(cm.curOp) +} + +// Finish an operation, updating the display and signalling delayed events +function endOperation(cm) { + var op = cm.curOp + finishOperation(op, function (group) { + for (var i = 0; i < group.ops.length; i++) + { group.ops[i].cm.curOp = null } + endOperations(group) + }) +} + +// The DOM updates done when an operation finishes are batched so +// that the minimum number of relayouts are required. +function endOperations(group) { + var ops = group.ops + for (var i = 0; i < ops.length; i++) // Read DOM + { endOperation_R1(ops[i]) } + for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe) + { endOperation_W1(ops[i$1]) } + for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM + { endOperation_R2(ops[i$2]) } + for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe) + { endOperation_W2(ops[i$3]) } + for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM + { endOperation_finish(ops[i$4]) } +} + +function endOperation_R1(op) { + var cm = op.cm, display = cm.display + maybeClipScrollbars(cm) + if (op.updateMaxLine) { findMaxLine(cm) } + + op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || + 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) +} + +function endOperation_W1(op) { + op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update) +} + +function endOperation_R2(op) { + var cm = op.cm, display = cm.display + if (op.updatedDisplay) { updateHeightsInViewport(cm) } + + op.barMeasure = measureForScrollbars(cm) + + // If the max line changed since it was last measured, measure it, + // and ensure the document's width matches it. + // updateDisplay_W2 will use these properties to do the actual resizing + if (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)) + } + + if (op.updatedDisplay || op.selectionChanged) + { op.preparedSelection = display.input.prepareSelection(op.focus) } +} + +function endOperation_W2(op) { + var cm = op.cm + + if (op.adjustWidthTo != null) { + cm.display.sizer.style.minWidth = op.adjustWidthTo + "px" + if (op.maxScrollLeft < cm.doc.scrollLeft) + { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true) } + cm.display.maxLineChanged = false + } + + var takeFocus = op.focus && op.focus == activeElt() && (!document.hasFocus || document.hasFocus()) + if (op.preparedSelection) + { cm.display.input.showSelection(op.preparedSelection, takeFocus) } + if (op.updatedDisplay || op.startHeight != cm.doc.height) + { updateScrollbars(cm, op.barMeasure) } + if (op.updatedDisplay) + { setDocumentHeight(cm, op.barMeasure) } + + if (op.selectionChanged) { restartBlink(cm) } + + if (cm.state.focused && op.updateInput) + { cm.display.input.reset(op.typing) } + if (takeFocus) { ensureFocus(op.cm) } +} + +function endOperation_finish(op) { + var cm = op.cm, display = cm.display, doc = cm.doc + + if (op.updatedDisplay) { postUpdateDisplay(cm, op.update) } + + // Abort mouse wheel delta measurement, when scrolling explicitly + if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) + { display.wheelStartX = display.wheelStartY = null } + + // Propagate the scroll position to the actual DOM scroller + if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) { + doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop)) + display.scrollbars.setScrollTop(doc.scrollTop) + display.scroller.scrollTop = doc.scrollTop + } + if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) { + doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft)) + display.scrollbars.setScrollLeft(doc.scrollLeft) + display.scroller.scrollLeft = doc.scrollLeft + alignHorizontally(cm) + } + // If we need to scroll a specific position into view, do so. + if (op.scrollToPos) { + var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), + clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin) + if (op.scrollToPos.isCursor && cm.state.focused) { maybeScrollWindow(cm, coords) } + } + + // Fire events for markers that are hidden/unidden by editing or + // undoing + var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers + if (hidden) { for (var i = 0; i < hidden.length; ++i) + { if (!hidden[i].lines.length) { signal(hidden[i], "hide") } } } + if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1) + { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide") } } } + + if (display.wrapper.offsetHeight) + { doc.scrollTop = cm.display.scroller.scrollTop } + + // Fire change events, and delayed event handlers + if (op.changeObjs) + { signal(cm, "changes", cm, op.changeObjs) } + if (op.update) + { op.update.finish() } +} + +// Run the given function in an operation +function runInOp(cm, f) { + if (cm.curOp) { return f() } + startOperation(cm) + try { return f() } + finally { endOperation(cm) } +} +// Wraps a function in an operation. Returns the wrapped function. +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) } + } +} +// Used to add methods to editor and doc instances, wrapping them in +// operations. +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) } + } +} + +// Updates the display.view data structure for a given change to the +// document. From and to are in pre-change coordinates. Lendiff is +// the amount of lines added or subtracted by the change. This is +// used for changes that span multiple lines, or change the way +// lines are divided into visual lines. regLineChange (below) +// registers single-line changes. +function regChange(cm, from, to, lendiff) { + if (from == null) { from = cm.doc.first } + if (to == null) { to = cm.doc.first + cm.doc.size } + if (!lendiff) { lendiff = 0 } + + var display = cm.display + if (lendiff && to < display.viewTo && + (display.updateLineNumbers == null || display.updateLineNumbers > from)) + { display.updateLineNumbers = from } + + cm.curOp.viewChanged = true + + if (from >= display.viewTo) { // Change after + if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) + { resetView(cm) } + } else if (to <= display.viewFrom) { // Change before + if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { + resetView(cm) + } else { + display.viewFrom += lendiff + display.viewTo += lendiff + } + } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap + resetView(cm) + } else if (from <= display.viewFrom) { // Top overlap + var cut = viewCuttingPoint(cm, to, to + lendiff, 1) + if (cut) { + display.view = display.view.slice(cut.index) + display.viewFrom = cut.lineN + display.viewTo += lendiff + } else { + resetView(cm) } - - display.updateLineNumbers = null; - - return true; + } else if (to >= display.viewTo) { // Bottom overlap + var cut$1 = viewCuttingPoint(cm, from, from, -1) + if (cut$1) { + display.view = display.view.slice(0, cut$1.index) + display.viewTo = cut$1.lineN + } else { + resetView(cm) + } + } else { // Gap in the middle + var cutTop = viewCuttingPoint(cm, from, from, -1) + var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1) + if (cutTop && cutBot) { + display.view = display.view.slice(0, cutTop.index) + .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) + .concat(display.view.slice(cutBot.index)) + display.viewTo += lendiff + } else { + resetView(cm) + } + } + + var ext = display.externalMeasured + if (ext) { + if (to < ext.lineN) + { ext.lineN += lendiff } + else if (from < ext.lineN + ext.size) + { display.externalMeasured = null } + } +} + +// Register a change to a single line. Type must be one of "text", +// "gutter", "class", "widget" +function regLineChange(cm, line, type) { + cm.curOp.viewChanged = true + var display = cm.display, ext = cm.display.externalMeasured + if (ext && line >= ext.lineN && line < ext.lineN + ext.size) + { display.externalMeasured = null } + + if (line < display.viewFrom || line >= display.viewTo) { return } + var lineView = display.view[findViewIndex(cm, line)] + if (lineView.node == null) { return } + var arr = lineView.changes || (lineView.changes = []) + if (indexOf(arr, type) == -1) { arr.push(type) } +} + +// Clear the view. +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 index = findViewIndex(cm, oldN), diff, view = cm.display.view + if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) + { return {index: index, lineN: newN} } + var n = cm.display.viewFrom + for (var i = 0; i < index; i++) + { n += view[i].size } + if (n != oldN) { + if (dir > 0) { + if (index == view.length - 1) { return null } + diff = (n + view[index].size) - oldN + index++ + } else { + diff = n - oldN + } + oldN += diff; newN += diff + } + while (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} +} + +// Force the view to cover a given range, adding empty view element +// or clipping off existing ones as needed. +function adjustView(cm, from, to) { + var display = cm.display, view = display.view + if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { + display.view = buildViewArray(cm, from, to) + display.viewFrom = from + } else { + if (display.viewFrom > from) + { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view) } + else if (display.viewFrom < from) + { display.view = display.view.slice(findViewIndex(cm, from)) } + display.viewFrom = from + if (display.viewTo < to) + { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)) } + else if (display.viewTo > to) + { display.view = display.view.slice(0, findViewIndex(cm, to)) } + } + display.viewTo = to +} + +// Count the number of lines in the view whose DOM representation is +// out of date (or nonexistent). +function countDirtyView(cm) { + var view = cm.display.view, dirty = 0 + for (var i = 0; i < view.length; i++) { + var lineView = view[i] + if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty } + } + return dirty +} + +// HIGHLIGHT WORKER + +function startWorker(cm, time) { + if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo) + { cm.state.highlight.set(time, bind(highlightWorker, cm)) } +} + +function highlightWorker(cm) { + var doc = cm.doc + if (doc.frontier < doc.first) { doc.frontier = doc.first } + if (doc.frontier >= cm.display.viewTo) { return } + var end = +new Date + cm.options.workTime + var state = copyState(doc.mode, getStateBefore(cm, doc.frontier)) + var changedLines = [] + + doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) { + if (doc.frontier >= cm.display.viewFrom) { // Visible + var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength + var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true) + line.styles = highlighted.styles + var oldCls = line.styleClasses, newCls = highlighted.classes + if (newCls) { line.styleClasses = newCls } + else if (oldCls) { line.styleClasses = null } + var ischange = !oldStyles || oldStyles.length != line.styles.length || + oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass) + for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i] } + if (ischange) { changedLines.push(doc.frontier) } + line.stateAfter = tooLong ? state : copyState(doc.mode, state) + } else { + if (line.text.length <= cm.options.maxHighlightLength) + { processLine(cm, line.text, state) } + line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null + } + ++doc.frontier + if (+new Date > end) { + startWorker(cm, cm.options.workDelay) + return true + } + }) + if (changedLines.length) { runInOp(cm, function () { + for (var i = 0; i < changedLines.length; i++) + { regLineChange(cm, changedLines[i], "text") } + }) } +} + +// DISPLAY DRAWING + +function DisplayUpdate(cm, viewport, force) { + var display = cm.display + + this.viewport = viewport + // Store some values that we'll need later (but don't want to force a relayout for) + 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 = [] +} + +DisplayUpdate.prototype.signal = function(emitter, type) { + if (hasHandler(emitter, type)) + { this.events.push(arguments) } +} +DisplayUpdate.prototype.finish = function() { + var this$1 = this; + + for (var i = 0; i < this.events.length; i++) + { signal.apply(null, this$1.events[i]) } +} + +function maybeClipScrollbars(cm) { + var display = cm.display + if (!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 = true + } +} + +// Does the actual updating of the line display. Bails out +// (returning false) when there is nothing to be done and forced is +// false. +function updateDisplayIfNeeded(cm, update) { + var display = cm.display, doc = cm.doc + + if (update.editorIsHidden) { + resetView(cm) + return false + } + + // Bail out if the visible area is already rendered and nothing changed. + if (!update.force && + update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && + (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && + display.renderedView == display.view && countDirtyView(cm) == 0) + { return false } + + if (maybeUpdateLineNumberWidth(cm)) { + resetView(cm) + update.dims = getDimensions(cm) + } + + // Compute a suitable new viewport (from & to) + var end = doc.first + doc.size + var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first) + var to = Math.min(end, update.visible.to + cm.options.viewportMargin) + if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom) } + if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo) } + if (sawCollapsedSpans) { + from = visualLineNo(cm.doc, from) + to = visualLineEndNo(cm.doc, to) + } + + var different = from != display.viewFrom || to != display.viewTo || + display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth + adjustView(cm, from, to) + + display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)) + // Position the mover div to align with the current scroll position + cm.display.mover.style.top = display.viewOffset + "px" + + var toUpdate = countDirtyView(cm) + if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && + (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) + { return false } + + // For big changes, we hide the enclosing element during the + // update, since that speeds up the operations on most browsers. + var focused = activeElt() + if (toUpdate > 4) { display.lineDiv.style.display = "none" } + patchDisplay(cm, display.updateLineNumbers, update.dims) + if (toUpdate > 4) { display.lineDiv.style.display = "" } + display.renderedView = display.view + // There might have been a widget with a focused element that got + // hidden or updated, if so re-focus it. + if (focused && activeElt() != focused && focused.offsetHeight) { focused.focus() } + + // Prevent selection and cursors from interfering with the scroll + // width and height. + removeChildren(display.cursorDiv) + removeChildren(display.selectionDiv) + display.gutters.style.height = display.sizer.style.minHeight = 0 + + if (different) { + display.lastWrapHeight = update.wrapperHeight + display.lastWrapWidth = update.wrapperWidth + startWorker(cm, 400) + } + + display.updateLineNumbers = null + + return true +} + +function postUpdateDisplay(cm, update) { + var viewport = update.viewport + + for (var first = true;; first = false) { + if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { + // Clip forced viewport to actual scrollable area. + if (viewport && viewport.top != null) + { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)} } + // Updated line heights might result in the drawn area not + // actually covering the viewport. Keep looping until it does. + update.visible = visibleLines(cm.display, cm.doc, viewport) + if (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.signal(cm, "update", cm) + if (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 update = new DisplayUpdate(cm, viewport) + if (updateDisplayIfNeeded(cm, update)) { + updateHeightsInViewport(cm) + postUpdateDisplay(cm, update) + var barMeasure = measureForScrollbars(cm) + updateSelection(cm) + updateScrollbars(cm, barMeasure) + setDocumentHeight(cm, barMeasure) + update.finish() + } +} + +// Sync the actual display DOM structure with display.view, removing +// nodes for lines that are no longer in view, and creating the ones +// that are not there yet, and updating the ones that are out of +// date. +function patchDisplay(cm, updateNumbersFrom, dims) { + var display = cm.display, lineNumbers = cm.options.lineNumbers + var container = display.lineDiv, cur = container.firstChild + + function rm(node) { + var next = node.nextSibling + // Works around a throw-scroll bug in OS X Webkit + if (webkit && mac && cm.display.currentWheelTarget == node) + { node.style.display = "none" } + else + { node.parentNode.removeChild(node) } + return next + } + + var view = display.view, lineN = display.viewFrom + // Loop over the elements in the view, syncing cur (the DOM nodes + // in display.lineDiv) with the view as we go. + for (var i = 0; i < view.length; i++) { + var lineView = view[i] + if (lineView.hidden) { + } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet + var node = buildLineElement(cm, lineView, lineN, dims) + container.insertBefore(node, cur) + } else { // Already drawn + while (cur != lineView.node) { cur = rm(cur) } + var updateNumber = lineNumbers && updateNumbersFrom != null && + updateNumbersFrom <= lineN && lineView.lineNumber + if (lineView.changes) { + if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false } + updateLineForChanges(cm, lineView, lineN, dims) + } + if (updateNumber) { + removeChildren(lineView.lineNumber) + lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))) + } + cur = lineView.node.nextSibling + } + lineN += lineView.size + } + while (cur) { cur = rm(cur) } +} + +function updateGutterSpace(cm) { + var width = cm.display.gutters.offsetWidth + cm.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" +} + +// Rebuild the gutter elements, ensure the margin to the left of the +// code matches their width. +function updateGutters(cm) { + var gutters = cm.display.gutters, specs = cm.options.gutters + removeChildren(gutters) + var i = 0 + for (; i < specs.length; ++i) { + var gutterClass = specs[i] + var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass)) + if (gutterClass == "CodeMirror-linenumbers") { + cm.display.lineGutter = gElt + gElt.style.width = (cm.display.lineNumWidth || 1) + "px" + } + } + gutters.style.display = i ? "" : "none" + updateGutterSpace(cm) +} + +// Make sure the gutters options contains the element +// "CodeMirror-linenumbers" when the lineNumbers option is true. +function setGuttersForLineNumbers(options) { + var found = indexOf(options.gutters, "CodeMirror-linenumbers") + if (found == -1 && options.lineNumbers) { + options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]) + } else if (found > -1 && !options.lineNumbers) { + options.gutters = options.gutters.slice(0) + options.gutters.splice(found, 1) + } +} + +// Selection objects are immutable. A new one is created every time +// the selection changes. A selection is one or more non-overlapping +// (and non-touching) ranges, sorted, and an integer that indicates +// which one is the primary selection (the one that's scrolled into +// view, that getCursor returns, etc). +function Selection(ranges, primIndex) { + this.ranges = ranges + this.primIndex = primIndex +} + +Selection.prototype = { + primary: function() { return this.ranges[this.primIndex] }, + equals: function(other) { + var this$1 = this; + + if (other == this) { return true } + if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false } + for (var i = 0; i < this.ranges.length; i++) { + var here = this$1.ranges[i], there = other.ranges[i] + if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) { return false } + } + return true + }, + deepCopy: function() { + var this$1 = this; + + var out = [] + for (var i = 0; i < this.ranges.length; i++) + { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)) } + return new Selection(out, this.primIndex) + }, + somethingSelected: function() { + var this$1 = this; + + for (var i = 0; i < this.ranges.length; i++) + { if (!this$1.ranges[i].empty()) { return true } } + return false + }, + contains: function(pos, end) { + var this$1 = this; + + if (!end) { end = pos } + for (var i = 0; i < this.ranges.length; i++) { + var range = this$1.ranges[i] + if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) + { return i } + } + return -1 + } +} + +function Range(anchor, head) { + this.anchor = anchor; this.head = head +} + +Range.prototype = { + from: function() { return minPos(this.anchor, this.head) }, + to: function() { return maxPos(this.anchor, this.head) }, + empty: function() { + return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch + } +} + +// Take an unsorted, potentially overlapping set of ranges, and +// build a selection out of it. 'Consumes' ranges array (modifying +// it). +function normalizeSelection(ranges, primIndex) { + var prim = ranges[primIndex] + ranges.sort(function (a, b) { return cmp(a.from(), b.from()); }) + primIndex = indexOf(ranges, prim) + for (var i = 1; i < ranges.length; i++) { + var cur = ranges[i], prev = ranges[i - 1] + if (cmp(prev.to(), cur.from()) >= 0) { + var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()) + var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head + if (i <= primIndex) { --primIndex } + ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)) + } + } + return new Selection(ranges, primIndex) +} + +function simpleSelection(anchor, head) { + return new Selection([new Range(anchor, head || anchor)], 0) +} + +// Compute the position of the end of a change (its 'to' property +// refers to the pre-change end). +function changeEnd(change) { + if (!change.text) { return change.to } + return Pos(change.from.line + change.text.length - 1, + lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)) +} + +// Adjust a position to refer to the post-change position of the +// same text, or the end of the change if the change covers it. +function adjustForChange(pos, change) { + if (cmp(pos, change.from) < 0) { return pos } + if (cmp(pos, change.to) <= 0) { return changeEnd(change) } + + var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch + if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch } + return Pos(line, ch) +} + +function computeSelAfterChange(doc, change) { + var out = [] + for (var 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(out, doc.sel.primIndex) +} + +function offsetPos(pos, old, nw) { + if (pos.line == old.line) + { return Pos(nw.line, pos.ch - old.ch + nw.ch) } + else + { return Pos(nw.line + (pos.line - old.line), pos.ch) } +} + +// Used by replaceSelections to allow moving the selection to the +// start or around the replaced test. Hint may be "start" or "around". +function computeReplacedSel(doc, changes, hint) { + var out = [] + var oldPrev = Pos(doc.first, 0), newPrev = oldPrev + for (var i = 0; i < changes.length; i++) { + var change = changes[i] + var from = offsetPos(change.from, oldPrev, newPrev) + var to = offsetPos(changeEnd(change), oldPrev, newPrev) + oldPrev = change.to + newPrev = to + if (hint == "around") { + var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0 + out[i] = new Range(inv ? to : from, inv ? from : to) + } else { + out[i] = new Range(from, from) + } + } + return new Selection(out, doc.sel.primIndex) +} + +// Used to get the editor into a consistent state again when options change. + +function loadMode(cm) { + cm.doc.mode = getMode(cm.options, cm.doc.modeOption) + resetModeState(cm) +} + +function resetModeState(cm) { + cm.doc.iter(function (line) { + if (line.stateAfter) { line.stateAfter = null } + if (line.styles) { line.styles = null } + }) + cm.doc.frontier = cm.doc.first + startWorker(cm, 100) + cm.state.modeGen++ + if (cm.curOp) { regChange(cm) } +} + +// DOCUMENT DATA STRUCTURE + +// By default, updates that start and end at the beginning of a line +// are treated specially, in order to make the association of line +// widgets and marker elements with the text behave more intuitive. +function isWholeLineUpdate(doc, change) { + return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && + (!doc.cm || doc.cm.options.wholeLineUpdateBefore) +} + +// Perform a change on the document data structure. +function updateDoc(doc, change, markedSpans, estimateHeight) { + function spansFor(n) {return markedSpans ? markedSpans[n] : null} + function update(line, text, spans) { + updateLine(line, text, spans, estimateHeight) + signalLater(line, "change", line, change) + } + function linesFor(start, end) { + var result = [] + for (var i = start; i < end; ++i) + { result.push(new Line(text[i], spansFor(i), estimateHeight)) } + return result } - function postUpdateDisplay(cm, update) { - var viewport = update.viewport; + var from = change.from, to = change.to, text = change.text + var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line) + var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line + + // Adjust the line structure + if (change.full) { + doc.insert(0, linesFor(0, text.length)) + doc.remove(text.length, doc.size - text.length) + } else if (isWholeLineUpdate(doc, change)) { + // This is a whole-line replace. Treated specially to make + // sure line objects move the way they are supposed to. + var added = linesFor(0, text.length - 1) + update(lastLine, lastLine.text, lastSpans) + if (nlines) { doc.remove(from.line, nlines) } + if (added.length) { doc.insert(from.line, added) } + } else if (firstLine == lastLine) { + if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans) + } else { + var added$1 = linesFor(1, text.length - 1) + added$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) + } + } else if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)) + doc.remove(from.line + 1, nlines) + } else { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)) + update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans) + var added$2 = linesFor(1, text.length - 1) + if (nlines > 1) { doc.remove(from.line + 1, nlines - 1) } + doc.insert(from.line + 1, added$2) + } + + signalLater(doc, "change", doc, change) +} + +// Call f for all linked documents. +function linkedDocs(doc, f, sharedHistOnly) { + function propagate(doc, skip, sharedHist) { + if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) { + var rel = doc.linked[i] + if (rel.doc == skip) { continue } + var shared = sharedHist && rel.sharedHist + if (sharedHistOnly && !shared) { continue } + f(rel.doc, shared) + propagate(rel.doc, doc, shared) + } } + } + propagate(doc, null, true) +} + +// Attach a document to an editor. +function attachDoc(cm, doc) { + if (doc.cm) { throw new Error("This document is already in use.") } + cm.doc = doc + doc.cm = cm + estimateLineHeights(cm) + loadMode(cm) + if (!cm.options.lineWrapping) { findMaxLine(cm) } + cm.options.mode = doc.modeOption + regChange(cm) +} + +function History(startGen) { + // Arrays of change events and selections. Doing something adds an + // event to done and clears undo. Undoing moves events from done + // to undone, redoing moves them in the other direction. + this.done = []; this.undone = [] + this.undoDepth = Infinity + // Used to track when changes can be merged into a single undo + // event + this.lastModTime = this.lastSelTime = 0 + this.lastOp = this.lastSelOp = null + this.lastOrigin = this.lastSelOrigin = null + // Used by the isClean() method + this.generation = this.maxGeneration = startGen || 1 +} + +// Create a history change event from an updateDoc-style change +// object. +function historyChangeFromChange(doc, change) { + var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)} + 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); }, true) + return histChange +} + +// Pop all selection events off the end of a history array. Stop at +// a change event. +function clearSelectionEvents(array) { + while (array.length) { + var last = lst(array) + if (last.ranges) { array.pop() } + else { break } + } +} + +// Find the top change event in the history. Pop off selection +// events that are in the way. +function lastChangeEvent(hist, force) { + if (force) { + clearSelectionEvents(hist.done) + return lst(hist.done) + } else if (hist.done.length && !lst(hist.done).ranges) { + return lst(hist.done) + } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { + hist.done.pop() + return lst(hist.done) + } +} + +// Register a change in the history. Merges changes that are within +// a single operation, or are close together with an origin that +// allows merging (starting with "+") into a single event. +function addChangeToHistory(doc, change, selAfter, opId) { + var hist = doc.history + hist.undone.length = 0 + var time = +new Date, cur + var last + + if ((hist.lastOp == opId || + hist.lastOrigin == change.origin && change.origin && + ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) || + change.origin.charAt(0) == "*")) && + (cur = lastChangeEvent(hist, hist.lastOp == opId))) { + // Merge this change into the last event + last = lst(cur.changes) + if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { + // Optimized case for simple insertion -- don't want to add + // new changesets for every character typed + last.to = changeEnd(change) + } else { + // Add new sub-event + cur.changes.push(historyChangeFromChange(doc, change)) + } + } else { + // Can not be merged, start a new event. + var before = lst(hist.done) + if (!before || !before.ranges) + { pushSelectionToHistory(doc.sel, hist.done) } + cur = {changes: [historyChangeFromChange(doc, change)], + generation: hist.generation} + hist.done.push(cur) + while (hist.done.length > hist.undoDepth) { + hist.done.shift() + if (!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 + + if (!last) { signal(doc, "historyAdded") } +} + +function selectionEventCanBeMerged(doc, origin, prev, sel) { + var ch = origin.charAt(0) + return ch == "*" || + ch == "+" && + prev.ranges.length == sel.ranges.length && + prev.somethingSelected() == sel.somethingSelected() && + new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500) +} + +// Called whenever the selection changes, sets the new selection as +// the pending selection in the history, and pushes the old pending +// selection into the 'done' array when it was significantly +// different (in number of selected ranges, emptiness, or time). +function addSelectionToHistory(doc, sel, opId, options) { + var hist = doc.history, origin = options && options.origin + + // A new event is started when the previous origin does not match + // the current, or the origins don't allow matching. Origins + // starting with * are always merged, those starting with + are + // merged when similar and close together in time. + if (opId == hist.lastSelOp || + (origin && hist.lastSelOrigin == origin && + (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || + selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) + { hist.done[hist.done.length - 1] = sel } + else + { pushSelectionToHistory(sel, hist.done) } + + hist.lastSelTime = +new Date + hist.lastSelOrigin = origin + hist.lastSelOp = opId + if (options && options.clearRedo !== false) + { clearSelectionEvents(hist.undone) } +} + +function pushSelectionToHistory(sel, dest) { + var top = lst(dest) + if (!(top && top.ranges && top.equals(sel))) + { dest.push(sel) } +} + +// Used to store marked span information in the history. +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) { + if (line.markedSpans) + { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans } + ++n + }) +} + +// When un/re-doing restores text containing marked spans, those +// that have been explicitly cleared should not be restored. +function removeClearedSpans(spans) { + if (!spans) { return null } + var out + for (var i = 0; i < spans.length; ++i) { + if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i) } } + else if (out) { out.push(spans[i]) } + } + return !out ? spans : out.length ? out : null +} + +// Retrieve and filter the old marked spans stored in a change event. +function getOldSpans(doc, change) { + var found = change["spans_" + doc.id] + if (!found) { return null } + var nw = [] + for (var i = 0; i < change.text.length; ++i) + { nw.push(removeClearedSpans(found[i])) } + return nw +} + +// Used for un/re-doing changes from the history. Combines the +// result of computing the existing spans with the set of spans that +// existed in the history (so that deleting around a span and then +// undoing brings back the span). +function mergeOldSpans(doc, change) { + var old = getOldSpans(doc, change) + var stretched = stretchSpansOverChange(doc, change) + if (!old) { return stretched } + if (!stretched) { return old } + + 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) { + var span = stretchCur[j] + for (var k = 0; k < oldCur.length; ++k) + { if (oldCur[k].marker == span.marker) { continue spans } } + oldCur.push(span) + } + } else if (stretchCur) { + old[i] = stretchCur + } + } + return old +} + +// Used both to provide a JSON-safe object in .getHistory, and, when +// detaching a document, to split the history in two +function copyHistoryArray(events, newGroup, instantiateSel) { + var copy = [] + for (var i = 0; i < events.length; ++i) { + var event = events[i] + if (event.ranges) { + copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event) + continue + } + var changes = event.changes, newChanges = [] + copy.push({changes: newChanges}) + for (var j = 0; j < changes.length; ++j) { + var change = changes[j], m = void 0 + newChanges.push({from: change.from, to: change.to, text: change.text}) + if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) { + if (indexOf(newGroup, Number(m[1])) > -1) { + lst(newChanges)[prop] = change[prop] + delete change[prop] + } + } } } + } + } + return copy +} + +// The 'scroll' parameter given to many of these indicated whether +// the new cursor position should be scrolled into view after +// modifying the selection. + +// If shift is held or the extend flag is set, extends a range to +// include a given position (and optionally a second position). +// Otherwise, simply returns the range between the given positions. +// Used for cursor motion and such. +function extendRange(doc, range, head, other) { + if (doc.cm && doc.cm.display.shift || doc.extend) { + var anchor = range.anchor + if (other) { + var posBefore = cmp(head, anchor) < 0 + if (posBefore != (cmp(other, anchor) < 0)) { + anchor = head + head = other + } else if (posBefore != (cmp(head, other) < 0)) { + head = other + } + } + return new Range(anchor, head) + } else { + return new Range(other || head, head) + } +} + +// Extend the primary selection range, discard the rest. +function extendSelection(doc, head, other, options) { + setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options) +} + +// Extend all selections (pos is an array of selections with length +// equal the number of selections) +function extendSelections(doc, heads, options) { + var out = [] + for (var i = 0; i < doc.sel.ranges.length; i++) + { out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null) } + var newSel = normalizeSelection(out, doc.sel.primIndex) + setSelection(doc, newSel, options) +} + +// Updates a single range in the selection. +function replaceOneSelection(doc, i, range, options) { + var ranges = doc.sel.ranges.slice(0) + ranges[i] = range + setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options) +} + +// Reset the selection to a single range. +function setSimpleSelection(doc, anchor, head, options) { + setSelection(doc, simpleSelection(anchor, head), options) +} + +// Give beforeSelectionChange handlers a change to influence a +// selection update. +function filterSelectionChange(doc, sel, options) { + var obj = { + ranges: sel.ranges, + update: function(ranges) { + var this$1 = this; + + this.ranges = [] + for (var i = 0; i < ranges.length; i++) + { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), + clipPos(doc, ranges[i].head)) } + }, + origin: options && options.origin + } + signal(doc, "beforeSelectionChange", doc, obj) + if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj) } + if (obj.ranges != sel.ranges) { return normalizeSelection(obj.ranges, obj.ranges.length - 1) } + else { return sel } +} + +function setSelectionReplaceHistory(doc, sel, options) { + var done = doc.history.done, last = lst(done) + if (last && last.ranges) { + done[done.length - 1] = sel + setSelectionNoUndo(doc, sel, options) + } else { + setSelection(doc, sel, options) + } +} + +// Set a new selection. +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) { + if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) + { sel = filterSelectionChange(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, true)) + + if (!(options && options.scroll === false) && doc.cm) + { ensureCursorVisible(doc.cm) } +} + +function setSelectionInner(doc, sel) { + if (sel.equals(doc.sel)) { return } + + doc.sel = sel + + if (doc.cm) { + doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true + signalCursorActivity(doc.cm) + } + signalLater(doc, "cursorActivity", doc) +} + +// Verify that the selection does not partially select any atomic +// marked ranges. +function reCheckSelection(doc) { + setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll) +} + +// Return a selection that does not partially select any atomic +// ranges. +function skipAtomicInSelection(doc, sel, bias, mayClear) { + var out + for (var i = 0; i < sel.ranges.length; i++) { + var range = sel.ranges[i] + var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i] + var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear) + var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear) + if (out || newAnchor != range.anchor || newHead != range.head) { + if (!out) { out = sel.ranges.slice(0, i) } + out[i] = new Range(newAnchor, newHead) + } + } + return out ? normalizeSelection(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 + if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) && + (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) { + if (mayClear) { + signal(m, "beforeCursorEnter") + if (m.explicitlyCleared) { + if (!line.markedSpans) { break } + else {--i; continue} + } + } + if (!m.atomic) { continue } + + if (oldPos) { + var near = m.find(dir < 0 ? 1 : -1), diff = void 0 + if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft) + { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null) } + if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) + { return skipAtomicInner(doc, near, pos, dir, mayClear) } + } + + var far = m.find(dir < 0 ? -1 : 1) + if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight) + { far = movePos(doc, far, dir, far.line == pos.line ? line : null) } + return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null + } + } } + return pos +} + +// Ensure a given position is not inside an atomic range. +function skipAtomic(doc, pos, oldPos, bias, mayClear) { + var dir = bias || 1 + var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) || + (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) || + skipAtomicInner(doc, pos, oldPos, -dir, mayClear) || + (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true)) + if (!found) { + doc.cantEdit = true + return Pos(doc.first, 0) + } + return found +} + +function movePos(doc, pos, dir, line) { + if (dir < 0 && pos.ch == 0) { + if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) } + else { return null } + } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) { + if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) } + else { return null } + } else { + return new Pos(pos.line, pos.ch + dir) + } +} + +function selectAll(cm) { + cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll) +} + +// UPDATING + +// Allow "beforeChange" event handlers to influence a change +function filterChange(doc, change, update) { + var obj = { + canceled: false, + from: change.from, + to: change.to, + text: change.text, + origin: change.origin, + cancel: function () { return obj.canceled = true; } + } + if (update) { obj.update = function (from, to, text, origin) { + if (from) { obj.from = clipPos(doc, from) } + if (to) { obj.to = clipPos(doc, to) } + if (text) { obj.text = text } + if (origin !== undefined) { obj.origin = origin } + } } + signal(doc, "beforeChange", doc, obj) + if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj) } + + if (obj.canceled) { return null } + return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin} +} + +// Apply a change to a document, and add it to the document's +// history, and propagating it to all linked documents. +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, true) + if (!change) { return } + } + + // Possibly split or suppress the update based on the presence + // of read-only spans in its range. + var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to) + if (split) { + for (var i = split.length - 1; i >= 0; --i) + { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text}) } + } else { + makeChangeInner(doc, change) + } +} + +function makeChangeInner(doc, change) { + if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return } + var selAfter = computeSelAfterChange(doc, change) + addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN) + + makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)) + var rebased = [] + + linkedDocs(doc, function (doc, sharedHist) { + if (!sharedHist && indexOf(rebased, doc.history) == -1) { + rebaseHist(doc.history, change) + rebased.push(doc.history) + } + makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)) + }) +} + +// Revert a change stored in a document's history. +function makeChangeFromHistory(doc, type, allowSelectionOnly) { + if (doc.cm && doc.cm.state.suppressEdits && !allowSelectionOnly) { return } + + var hist = doc.history, event, selAfter = doc.sel + var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done + + // Verify that there is a useable event (so that ctrl-z won't + // needlessly clear selection events) + var i = 0 + for (; i < source.length; i++) { + event = source[i] + if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) + { break } + } + if (i == source.length) { return } + hist.lastOrigin = hist.lastSelOrigin = null + + for (;;) { + event = source.pop() + if (event.ranges) { + pushSelectionToHistory(event, dest) + if (allowSelectionOnly && !event.equals(doc.sel)) { + setSelection(doc, event, {clearRedo: false}) + return + } + selAfter = event + } + else { break } + } + + // Build up a reverse change object to add to the opposite history + // stack (redo when undoing, and vice versa). + var antiChanges = [] + pushSelectionToHistory(selAfter, dest) + dest.push({changes: antiChanges, generation: hist.generation}) + hist.generation = event.generation || ++hist.maxGeneration + + var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange") + + var loop = function ( i ) { + var change = event.changes[i] + change.origin = type + if (filter && !filterChange(doc, change, false)) { + source.length = 0 + return {} + } + + antiChanges.push(historyChangeFromChange(doc, change)) + + var after = i ? computeSelAfterChange(doc, change) : lst(source) + makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)) + if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}) } + var rebased = [] - for (var first = true;; first = false) { - if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { - // Clip forced viewport to actual scrollable area. - if (viewport && viewport.top != null) - viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; - // Updated line heights might result in the drawn area not - // actually covering the viewport. Keep looping until it does. - update.visible = visibleLines(cm.display, cm.doc, viewport); - if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) - break; + // Propagate to the linked documents + linkedDocs(doc, function (doc, sharedHist) { + if (!sharedHist && indexOf(rebased, doc.history) == -1) { + rebaseHist(doc.history, change) + rebased.push(doc.history) } - if (!updateDisplayIfNeeded(cm, update)) break; - updateHeightsInViewport(cm); - var barMeasure = measureForScrollbars(cm); - updateSelection(cm); - updateScrollbars(cm, barMeasure); - setDocumentHeight(cm, barMeasure); - } - - update.signal(cm, "update", cm); - if (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 update = new DisplayUpdate(cm, viewport); - if (updateDisplayIfNeeded(cm, update)) { - updateHeightsInViewport(cm); - postUpdateDisplay(cm, update); - var barMeasure = measureForScrollbars(cm); - updateSelection(cm); - updateScrollbars(cm, barMeasure); - setDocumentHeight(cm, barMeasure); - update.finish(); - } - } - - 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"; - } - - // Read the actual heights of the rendered lines, and update their - // stored heights to match. - function updateHeightsInViewport(cm) { - var display = cm.display; - var prevBottom = display.lineDiv.offsetTop; - for (var i = 0; i < display.view.length; i++) { - var cur = display.view[i], height; - if (cur.hidden) continue; - if (ie && ie_version < 8) { - var bot = cur.node.offsetTop + cur.node.offsetHeight; - height = bot - prevBottom; - prevBottom = bot; - } else { - var box = cur.node.getBoundingClientRect(); - height = box.bottom - box.top; + makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)) + }) + }; + + for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) { + var returned = loop( i$1 ); + + if ( returned ) return returned.v; + } +} + +// Sub-views need their line numbers shifted when text is added +// above or below them in the parent document. +function shiftDoc(doc, distance) { + if (distance == 0) { return } + 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) + if (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") } + } +} + +// More lower-level change function, handling only a single document +// (not linked ones). +function makeChangeSingleDoc(doc, change, selAfter, spans) { + if (doc.cm && !doc.cm.curOp) + { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) } + + if (change.to.line < doc.first) { + shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)) + return + } + if (change.from.line > doc.lastLine()) { return } + + // Clip the change to the size of this doc + if (change.from.line < doc.first) { + var shift = change.text.length - 1 - (doc.first - change.from.line) + shiftDoc(doc, shift) + change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), + text: [lst(change.text)], origin: change.origin} + } + var last = doc.lastLine() + if (change.to.line > last) { + change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), + text: [change.text[0]], origin: change.origin} + } + + change.removed = getBetween(doc, change.from, change.to) + + if (!selAfter) { selAfter = computeSelAfterChange(doc, change) } + if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans) } + else { updateDoc(doc, change, spans) } + setSelectionNoUndo(doc, selAfter, sel_dontScroll) +} + +// Handle the interaction of a change to a document with the editor +// that this document is part of. +function makeChangeSingleDocInEditor(cm, change, spans) { + var doc = cm.doc, display = cm.display, from = change.from, to = change.to + + var recomputeMaxLength = false, checkWidthStart = from.line + if (!cm.options.lineWrapping) { + checkWidthStart = lineNo(visualLine(getLine(doc, from.line))) + doc.iter(checkWidthStart, to.line + 1, function (line) { + if (line == display.maxLine) { + recomputeMaxLength = true + return true + } + }) + } + + if (doc.sel.contains(change.from, change.to) > -1) + { signalCursorActivity(cm) } + + updateDoc(doc, change, spans, estimateHeight(cm)) + + if (!cm.options.lineWrapping) { + doc.iter(checkWidthStart, from.line + change.text.length, function (line) { + var len = lineLength(line) + if (len > display.maxLineLength) { + display.maxLine = line + display.maxLineLength = len + display.maxLineChanged = true + recomputeMaxLength = false + } + }) + if (recomputeMaxLength) { cm.curOp.updateMaxLine = true } + } + + // Adjust frontier, schedule worker + doc.frontier = Math.min(doc.frontier, from.line) + startWorker(cm, 400) + + var lendiff = change.text.length - (to.line - from.line) - 1 + // Remember that these lines changed, for updating the display + if (change.full) + { regChange(cm) } + else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) + { regLineChange(cm, from.line, "text") } + else + { regChange(cm, from.line, to.line + 1, lendiff) } + + var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change") + if (changeHandler || changesHandler) { + var obj = { + from: from, to: to, + text: change.text, + removed: change.removed, + origin: change.origin + } + if (changeHandler) { signalLater(cm, "change", cm, obj) } + if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj) } + } + cm.display.selForContextMenu = null +} + +function replaceRange(doc, code, from, to, origin) { + if (!to) { to = from } + if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp } + if (typeof code == "string") { code = doc.splitLines(code) } + makeChange(doc, {from: from, to: to, text: code, origin: origin}) +} + +// Rebasing/resetting history to deal with externally-sourced changes + +function rebaseHistSelSingle(pos, from, to, diff) { + if (to < pos.line) { + pos.line += diff + } else if (from < pos.line) { + pos.line = from + pos.ch = 0 + } +} + +// Tries to rebase an array of history events given a change in the +// document. If the change touches the same lines as the event, the +// event, and everything 'behind' it, is discarded. If the change is +// before the event, the event's positions are updated. Uses a +// copy-on-write scheme for the positions, to avoid having to +// reallocate them all on every rebase, but also avoid problems with +// shared position objects being unsafely updated. +function rebaseHistArray(array, from, to, diff) { + for (var i = 0; i < array.length; ++i) { + var sub = array[i], ok = true + if (sub.ranges) { + if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true } + 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) + } + continue + } + 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 = false + break + } + } + if (!ok) { + array.splice(0, i + 1) + i = 0 + } + } +} + +function rebaseHist(hist, change) { + var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1 + rebaseHistArray(hist.done, from, to, diff) + rebaseHistArray(hist.undone, from, to, diff) +} + +// Utility for applying a change to a line by handle or number, +// returning the number and optionally registering the line as +// changed. +function changeLine(doc, handle, changeType, op) { + var no = handle, line = handle + if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)) } + else { no = lineNo(handle) } + if (no == null) { return null } + if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType) } + return line +} + +// The document is represented as a BTree consisting of leaves, with +// chunk of lines in them, and branches, with up to ten leaves or +// other branch nodes below them. The top node is always a branch +// node, and is the document object itself (meaning it has +// additional methods and properties). +// +// All nodes have parent links. The tree is used both to go from +// line numbers to line objects, and to go from objects to numbers. +// It also indexes by height, and is used to convert between height +// and line object, and to find the total height of the document. +// +// See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html + +function LeafChunk(lines) { + var this$1 = this; + + this.lines = lines + this.parent = null + var height = 0 + for (var i = 0; i < lines.length; ++i) { + lines[i].parent = this$1 + height += lines[i].height + } + this.height = height +} + +LeafChunk.prototype = { + chunkSize: function() { return this.lines.length }, + // Remove the n lines at offset 'at'. + removeInner: function(at, n) { + var this$1 = this; + + for (var i = at, e = at + n; i < e; ++i) { + var line = this$1.lines[i] + this$1.height -= line.height + cleanUpLine(line) + signalLater(line, "delete") + } + this.lines.splice(at, n) + }, + // Helper used to collapse a small branch into a single leaf. + collapse: function(lines) { + lines.push.apply(lines, this.lines) + }, + // Insert the given array of lines at offset 'at', count them as + // having the given height. + insertInner: function(at, lines, height) { + var this$1 = this; + + 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$1 } + }, + // Used to iterate over a part of the tree. + iterN: function(at, n, op) { + var this$1 = this; + + for (var e = at + n; at < e; ++at) + { if (op(this$1.lines[at])) { return true } } + } +} + +function BranchChunk(children) { + var this$1 = this; + + this.children = children + var size = 0, height = 0 + for (var i = 0; i < children.length; ++i) { + var ch = children[i] + size += ch.chunkSize(); height += ch.height + ch.parent = this$1 + } + this.size = size + this.height = height + this.parent = null +} + +BranchChunk.prototype = { + chunkSize: function() { return this.size }, + removeInner: function(at, n) { + var this$1 = this; + + this.size -= n + for (var i = 0; i < this.children.length; ++i) { + var child = this$1.children[i], sz = child.chunkSize() + if (at < sz) { + var rm = Math.min(n, sz - at), oldHeight = child.height + child.removeInner(at, rm) + this$1.height -= oldHeight - child.height + if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null } + if ((n -= rm) == 0) { break } + at = 0 + } else { at -= sz } + } + // If the result is smaller than 25 lines, ensure that it is a + // single leaf node. + if (this.size - n < 25 && + (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { + var lines = [] + this.collapse(lines) + this.children = [new LeafChunk(lines)] + this.children[0].parent = this + } + }, + collapse: function(lines) { + var this$1 = this; + + for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines) } + }, + insertInner: function(at, lines, height) { + var this$1 = this; + + this.size += lines.length + this.height += height + for (var i = 0; i < this.children.length; ++i) { + var child = this$1.children[i], sz = child.chunkSize() + if (at <= sz) { + child.insertInner(at, lines, height) + if (child.lines && child.lines.length > 50) { + // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced. + // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest. + var remaining = child.lines.length % 25 + 25 + for (var pos = remaining; pos < child.lines.length;) { + var leaf = new LeafChunk(child.lines.slice(pos, pos += 25)) + child.height -= leaf.height + this$1.children.splice(++i, 0, leaf) + leaf.parent = this$1 + } + child.lines = child.lines.slice(0, remaining) + this$1.maybeSpill() + } + break } - var diff = cur.line.height - height; - if (height < 2) height = textHeight(display); - if (diff > .001 || diff < -.001) { - updateLineHeight(cur.line, height); - updateWidgetHeight(cur.line); - if (cur.rest) for (var j = 0; j < cur.rest.length; j++) - updateWidgetHeight(cur.rest[j]); + at -= sz + } + }, + // When a node has grown, check whether it should be split. + maybeSpill: function() { + if (this.children.length <= 10) { return } + var me = this + do { + var spilled = me.children.splice(me.children.length - 5, 5) + var sibling = new BranchChunk(spilled) + if (!me.parent) { // Become the parent node + var copy = new BranchChunk(me.children) + copy.parent = me + me.children = [copy, sibling] + me = copy + } else { + me.size -= sibling.size + me.height -= sibling.height + var myIndex = indexOf(me.parent.children, me) + me.parent.children.splice(myIndex + 1, 0, sibling) + } + sibling.parent = me.parent + } while (me.children.length > 10) + me.parent.maybeSpill() + }, + iterN: function(at, n, op) { + var this$1 = this; + + for (var i = 0; i < this.children.length; ++i) { + var child = this$1.children[i], sz = child.chunkSize() + if (at < sz) { + var used = Math.min(n, sz - at) + if (child.iterN(at, used, op)) { return true } + if ((n -= used) == 0) { break } + at = 0 + } else { at -= sz } + } + } +} + +// Line widgets are block elements displayed above or below a line. + +function LineWidget(doc, node, options) { + var this$1 = this; + + if (options) { for (var opt in options) { if (options.hasOwnProperty(opt)) + { this$1[opt] = options[opt] } } } + this.doc = doc + this.node = node +} +eventMixin(LineWidget) + +function adjustScrollWhenAboveVisible(cm, line, diff) { + if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) + { addToScrollPos(cm, null, diff) } +} + +LineWidget.prototype.clear = function() { + var this$1 = this; + + var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line) + if (no == null || !ws) { return } + for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1) } } + if (!ws.length) { line.widgets = null } + var height = widgetHeight(this) + updateLineHeight(line, Math.max(0, line.height - height)) + if (cm) { runInOp(cm, function () { + adjustScrollWhenAboveVisible(cm, line, -height) + regLineChange(cm, no, "widget") + }) } +} +LineWidget.prototype.changed = function() { + var oldH = this.height, cm = this.doc.cm, line = this.line + this.height = null + var diff = widgetHeight(this) - oldH + if (!diff) { return } + updateLineHeight(line, line.height + diff) + if (cm) { runInOp(cm, function () { + cm.curOp.forceUpdate = true + adjustScrollWhenAboveVisible(cm, line, diff) + }) } +} + +function addLineWidget(doc, handle, node, options) { + var widget = new LineWidget(doc, node, options) + var cm = doc.cm + if (cm && widget.noHScroll) { cm.display.alignWidgets = true } + changeLine(doc, handle, "widget", function (line) { + var widgets = line.widgets || (line.widgets = []) + if (widget.insertAt == null) { widgets.push(widget) } + else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget) } + widget.line = line + if (cm && !lineIsHidden(doc, line)) { + var aboveVisible = heightAtLine(line) < doc.scrollTop + updateLineHeight(line, line.height + widgetHeight(widget)) + if (aboveVisible) { addToScrollPos(cm, null, widget.height) } + cm.curOp.forceUpdate = true + } + return true + }) + return widget +} + +// TEXTMARKERS + +// Created with markText and setBookmark methods. A TextMarker is a +// handle that can be used to clear or find a marked position in the +// document. Line objects hold arrays (markedSpans) containing +// {from, to, marker} object pointing to such marker objects, and +// indicating that such a marker is present on that line. Multiple +// lines may point to the same marker when it spans across lines. +// The spans will have null for their from/to properties when the +// marker continues beyond the start/end of the line. Markers have +// links back to the lines they currently touch. + +// Collapsed markers have unique ids, in order to be able to order +// them, which is needed for uniquely determining an outer marker +// when they overlap (they may nest, but not partially overlap). +var nextMarkerId = 0 + +function TextMarker(doc, type) { + this.lines = [] + this.type = type + this.doc = doc + this.id = ++nextMarkerId +} +eventMixin(TextMarker) + +// Clear the marker. +TextMarker.prototype.clear = function() { + var this$1 = this; + + if (this.explicitlyCleared) { return } + var cm = this.doc.cm, withOp = cm && !cm.curOp + if (withOp) { startOperation(cm) } + if (hasHandler(this, "clear")) { + var found = this.find() + if (found) { signalLater(this, "clear", found.from, found.to) } + } + var min = null, max = null + for (var i = 0; i < this.lines.length; ++i) { + var line = this$1.lines[i] + var span = getMarkedSpanFor(line.markedSpans, this$1) + if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text") } + else if (cm) { + if (span.to != null) { max = lineNo(line) } + if (span.from != null) { min = lineNo(line) } + } + line.markedSpans = removeMarkedSpan(line.markedSpans, span) + if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.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$1.lines[i$1]), len = lineLength(visual) + if (len > cm.display.maxLineLength) { + cm.display.maxLine = visual + cm.display.maxLineLength = len + cm.display.maxLineChanged = true + } + } } + + if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1) } + this.lines.length = 0 + this.explicitlyCleared = true + if (this.atomic && this.doc.cantEdit) { + this.doc.cantEdit = false + if (cm) { reCheckSelection(cm.doc) } + } + if (cm) { signalLater(cm, "markerCleared", cm, this) } + if (withOp) { endOperation(cm) } + if (this.parent) { this.parent.clear() } +} + +// Find the position of the marker in the document. Returns a {from, +// to} object by default. Side can be passed to get a specific side +// -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the +// Pos objects returned contain a line object, rather than a line +// number (used to prevent looking up the same line twice). +TextMarker.prototype.find = function(side, lineObj) { + var this$1 = this; + + if (side == null && this.type == "bookmark") { side = 1 } + var from, to + for (var i = 0; i < this.lines.length; ++i) { + var line = this$1.lines[i] + var span = getMarkedSpanFor(line.markedSpans, this$1) + if (span.from != null) { + from = Pos(lineObj ? line : lineNo(line), span.from) + if (side == -1) { return from } + } + if (span.to != null) { + to = Pos(lineObj ? line : lineNo(line), span.to) + if (side == 1) { return to } + } + } + return from && {from: from, to: to} +} + +// Signals that the marker's widget changed, and surrounding layout +// should be recomputed. +TextMarker.prototype.changed = function() { + var pos = this.find(-1, true), widget = this, cm = this.doc.cm + if (!pos || !cm) { return } + runInOp(cm, function () { + var line = pos.line, lineN = lineNo(pos.line) + var view = findViewForLine(cm, lineN) + if (view) { + clearLineMeasurementCacheFor(view) + cm.curOp.selectionChanged = cm.curOp.forceUpdate = true + } + cm.curOp.updateMaxLine = true + if (!lineIsHidden(widget.doc, line) && widget.height != null) { + var oldHeight = widget.height + widget.height = null + var dHeight = widgetHeight(widget) - oldHeight + if (dHeight) + { updateLineHeight(line, line.height + dHeight) } + } + }) +} + +TextMarker.prototype.attachLine = function(line) { + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp + if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) + { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this) } + } + this.lines.push(line) +} +TextMarker.prototype.detachLine = function(line) { + this.lines.splice(indexOf(this.lines, line), 1) + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp + ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this) + } +} + +// Create a marker, wire it up to the right lines, and +function markText(doc, from, to, options, type) { + // Shared markers (across linked documents) are handled separately + // (markTextShared will call out to this again, once per + // document). + if (options && options.shared) { return markTextShared(doc, from, to, options, type) } + // Ensure we are in an operation. + if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) } + + var marker = new TextMarker(doc, type), diff = cmp(from, to) + if (options) { copyObj(options, marker, false) } + // Don't connect empty markers unless clearWhenEmpty is false + if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) + { return marker } + if (marker.replacedWith) { + // Showing up as a widget implies collapsed (widget replaces text) + marker.collapsed = true + marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget") + if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true") } + if (options.insertLeft) { marker.widgetNode.insertLeft = true } + } + if (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") } + seeCollapsedSpans() + } + + if (marker.addToHistory) + { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN) } + + var curLine = from.line, cm = doc.cm, updateMaxLine + doc.iter(curLine, to.line + 1, function (line) { + if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) + { updateMaxLine = true } + if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0) } + addMarkedSpan(line, new MarkedSpan(marker, + curLine == from.line ? from.ch : null, + curLine == to.line ? to.ch : null)) + ++curLine + }) + // lineIsHidden depends on the presence of the spans, so needs a second pass + if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) { + if (lineIsHidden(doc, line)) { updateLineHeight(line, 0) } + }) } + + if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }) } + + if (marker.readOnly) { + seeReadOnlySpans() + if (doc.history.done.length || doc.history.undone.length) + { doc.clearHistory() } + } + if (marker.collapsed) { + marker.id = ++nextMarkerId + marker.atomic = true + } + if (cm) { + // Sync editor state + if (updateMaxLine) { cm.curOp.updateMaxLine = true } + if (marker.collapsed) + { regChange(cm, from.line, to.line + 1) } + else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css) + { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text") } } + if (marker.atomic) { reCheckSelection(cm.doc) } + signalLater(cm, "markerAdded", cm, marker) + } + return marker +} + +// SHARED TEXTMARKERS + +// A shared marker spans multiple linked documents. It is +// implemented as a meta-marker-object controlling multiple normal +// markers. +function SharedTextMarker(markers, primary) { + var this$1 = this; + + this.markers = markers + this.primary = primary + for (var i = 0; i < markers.length; ++i) + { markers[i].parent = this$1 } +} +eventMixin(SharedTextMarker) + +SharedTextMarker.prototype.clear = function() { + var this$1 = this; + + if (this.explicitlyCleared) { return } + this.explicitlyCleared = true + for (var i = 0; i < this.markers.length; ++i) + { this$1.markers[i].clear() } + signalLater(this, "clear") +} +SharedTextMarker.prototype.find = function(side, lineObj) { + return this.primary.find(side, lineObj) +} + +function markTextShared(doc, from, to, options, type) { + options = copyObj(options) + options.shared = false + var markers = [markText(doc, from, to, options, type)], primary = markers[0] + var widget = options.widgetNode + linkedDocs(doc, function (doc) { + if (widget) { options.widgetNode = widget.cloneNode(true) } + 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) + }) + return new SharedTextMarker(markers, primary) +} + +function findSharedMarkers(doc) { + return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; }) +} + +function copySharedMarkers(doc, markers) { + for (var i = 0; i < markers.length; i++) { + var marker = markers[i], pos = marker.find() + var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to) + if (cmp(mFrom, mTo)) { + var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type) + marker.markers.push(subMark) + subMark.parent = marker + } + } +} + +function detachSharedMarkers(markers) { + var loop = function ( 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] + if (indexOf(linked, subMarker.doc) == -1) { + subMarker.parent = null + marker.markers.splice(j--, 1) } } - } - - // Read and store the height of line widgets associated with the - // given line. - function updateWidgetHeight(line) { - if (line.widgets) for (var i = 0; i < line.widgets.length; ++i) - line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight; - } + }; - // Do a bulk-read of the DOM positions and sizes needed to draw the - // view, so that we don't interleave reading and writing to the DOM. - function getDimensions(cm) { - var d = cm.display, left = {}, width = {}; - var gutterLeft = d.gutters.clientLeft; - for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { - left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft; - width[cm.options.gutters[i]] = n.clientWidth; + for (var i = 0; i < markers.length; i++) loop( i ); +} + +var nextDocId = 0 +var Doc = function(text, mode, firstLine, lineSep) { + if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep) } + if (firstLine == null) { firstLine = 0 } + + BranchChunk.call(this, [new LeafChunk([new Line("", null)])]) + this.first = firstLine + this.scrollTop = this.scrollLeft = 0 + this.cantEdit = false + this.cleanGeneration = 1 + this.frontier = firstLine + var start = Pos(firstLine, 0) + this.sel = simpleSelection(start) + this.history = new History(null) + this.id = ++nextDocId + this.modeOption = mode + this.lineSep = lineSep + this.extend = false + + if (typeof text == "string") { text = this.splitLines(text) } + updateDoc(this, {from: start, to: start, text: text}) + setSelection(this, simpleSelection(start), sel_dontScroll) +} + +Doc.prototype = createObj(BranchChunk.prototype, { + constructor: Doc, + // Iterate over the document. Supports two forms -- with only one + // argument, it calls that for each line in the document. With + // three, it iterates over the range given by the first two (with + // the second being non-inclusive). + iter: function(from, to, op) { + if (op) { this.iterN(from - this.first, to - from, op) } + else { this.iterN(this.first, this.first + this.size, from) } + }, + + // Non-public interface for adding and removing lines. + insert: function(at, lines) { + var height = 0 + for (var 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) }, + + // From here, the methods are part of the public interface. Most + // are also available from CodeMirror (editor) instances. + + getValue: function(lineSep) { + var lines = getLines(this, this.first, this.first + this.size) + if (lineSep === false) { return lines } + return 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: true}, true) + setSelection(this, simpleSelection(top)) + }), + replaceRange: function(code, from, to, origin) { + from = clipPos(this, from) + to = to ? clipPos(this, to) : from + replaceRange(this, code, from, to, origin) + }, + getRange: function(from, to, lineSep) { + var lines = getBetween(this, clipPos(this, from), clipPos(this, to)) + if (lineSep === false) { return lines } + return lines.join(lineSep || this.lineSeparator()) + }, + + getLine: function(line) {var l = this.getLineHandle(line); return l && l.text}, + + getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }}, + getLineNumber: function(line) {return lineNo(line)}, + + getLineHandleVisualStart: function(line) { + if (typeof line == "number") { line = getLine(this, line) } + return visualLine(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(), pos + if (start == null || start == "head") { pos = range.head } + else if (start == "anchor") { pos = range.anchor } + else if (start == "end" || start == "to" || start === false) { pos = range.to() } + else { pos = range.from() } + return pos + }, + listSelections: function() { return this.sel.ranges }, + somethingSelected: function() {return this.sel.somethingSelected()}, + + setCursor: docMethodOp(function(line, ch, options) { + setSimpleSelection(this, clipPos(this, typeof line == "number" ? 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) { + var heads = map(this.sel.ranges, f) + extendSelections(this, clipPosArray(this, heads), options) + }), + setSelections: docMethodOp(function(ranges, primary, options) { + var this$1 = this; + + if (!ranges.length) { return } + var out = [] + for (var i = 0; i < ranges.length; i++) + { out[i] = new Range(clipPos(this$1, ranges[i].anchor), + clipPos(this$1, ranges[i].head)) } + if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex) } + setSelection(this, normalizeSelection(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(ranges, ranges.length - 1), options) + }), + + getSelection: function(lineSep) { + var this$1 = this; + + var ranges = this.sel.ranges, lines + for (var i = 0; i < ranges.length; i++) { + var sel = getBetween(this$1, ranges[i].from(), ranges[i].to()) + lines = lines ? lines.concat(sel) : sel } - return {fixedPos: compensateForHScroll(d), - gutterTotalWidth: d.gutters.offsetWidth, - gutterLeft: left, - gutterWidth: width, - wrapperWidth: d.wrapper.clientWidth}; - } + if (lineSep === false) { return lines } + else { return lines.join(lineSep || this.lineSeparator()) } + }, + getSelections: function(lineSep) { + var this$1 = this; - // Sync the actual display DOM structure with display.view, removing - // nodes for lines that are no longer in view, and creating the ones - // that are not there yet, and updating the ones that are out of - // date. - function patchDisplay(cm, updateNumbersFrom, dims) { - var display = cm.display, lineNumbers = cm.options.lineNumbers; - var container = display.lineDiv, cur = container.firstChild; - - function rm(node) { - var next = node.nextSibling; - // Works around a throw-scroll bug in OS X Webkit - if (webkit && mac && cm.display.currentWheelTarget == node) - node.style.display = "none"; - else - node.parentNode.removeChild(node); - return next; - } - - var view = display.view, lineN = display.viewFrom; - // Loop over the elements in the view, syncing cur (the DOM nodes - // in display.lineDiv) with the view as we go. - for (var i = 0; i < view.length; i++) { - var lineView = view[i]; - if (lineView.hidden) { - } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet - var node = buildLineElement(cm, lineView, lineN, dims); - container.insertBefore(node, cur); - } else { // Already drawn - while (cur != lineView.node) cur = rm(cur); - var updateNumber = lineNumbers && updateNumbersFrom != null && - updateNumbersFrom <= lineN && lineView.lineNumber; - if (lineView.changes) { - if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false; - updateLineForChanges(cm, lineView, lineN, dims); + var parts = [], ranges = this.sel.ranges + for (var i = 0; i < ranges.length; i++) { + var sel = getBetween(this$1, ranges[i].from(), ranges[i].to()) + if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()) } + parts[i] = sel + } + return parts + }, + replaceSelection: function(code, collapse, origin) { + var dup = [] + for (var i = 0; i < this.sel.ranges.length; i++) + { dup[i] = code } + this.replaceSelections(dup, collapse, origin || "+input") + }, + replaceSelections: docMethodOp(function(code, collapse, origin) { + var this$1 = this; + + var changes = [], sel = this.sel + for (var i = 0; i < sel.ranges.length; i++) { + var range = sel.ranges[i] + changes[i] = {from: range.from(), to: range.to(), text: this$1.splitLines(code[i]), origin: origin} + } + var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse) + for (var i$1 = changes.length - 1; i$1 >= 0; i$1--) + { makeChange(this$1, changes[i$1]) } + if (newSel) { setSelectionReplaceHistory(this, newSel) } + else if (this.cm) { ensureCursorVisible(this.cm) } + }), + undo: docMethodOp(function() {makeChangeFromHistory(this, "undo")}), + redo: docMethodOp(function() {makeChangeFromHistory(this, "redo")}), + undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true)}), + redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true)}), + + setExtending: function(val) {this.extend = val}, + getExtending: function() {return this.extend}, + + historySize: function() { + var hist = this.history, done = 0, undone = 0 + for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done } } + for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone } } + return {undo: done, redo: undone} + }, + clearHistory: function() {this.history = new History(this.history.maxGeneration)}, + + markClean: function() { + this.cleanGeneration = this.changeGeneration(true) + }, + changeGeneration: function(forceSplit) { + if (forceSplit) + { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null } + return 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, true) + hist.undone = copyHistoryArray(histData.undone.slice(0), null, true) + }, + + addLineClass: docMethodOp(function(handle, where, cls) { + return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { + var prop = where == "text" ? "textClass" + : where == "background" ? "bgClass" + : where == "gutter" ? "gutterClass" : "wrapClass" + if (!line[prop]) { line[prop] = cls } + else if (classTest(cls).test(line[prop])) { return false } + else { line[prop] += " " + cls } + return true + }) + }), + removeLineClass: docMethodOp(function(handle, where, cls) { + return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { + var prop = where == "text" ? "textClass" + : where == "background" ? "bgClass" + : where == "gutter" ? "gutterClass" : "wrapClass" + var cur = line[prop] + if (!cur) { return false } + else if (cls == null) { line[prop] = null } + else { + var found = cur.match(classTest(cls)) + if (!found) { return false } + var end = found.index + found[0].length + line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null + } + return true + }) + }), + + addLineWidget: docMethodOp(function(handle, node, options) { + return addLineWidget(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) { + var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), + insertLeft: options && options.insertLeft, + clearWhenEmpty: false, shared: options && options.shared, + handleMouseEvents: options && options.handleMouseEvents} + pos = clipPos(this, pos) + return markText(this, pos, pos, realOpts, "bookmark") + }, + findMarksAt: function(pos) { + pos = clipPos(this, pos) + var markers = [], spans = getLine(this, pos.line).markedSpans + if (spans) { for (var i = 0; i < spans.length; ++i) { + var span = spans[i] + if ((span.from == null || span.from <= pos.ch) && + (span.to == null || 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 + 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] + if (!(span.to != null && lineNo == from.line && from.ch >= span.to || + span.from == null && lineNo != from.line || + span.from != null && lineNo == to.line && span.from >= to.ch) && + (!filter || filter(span.marker))) + { found.push(span.marker.parent || span.marker) } + } } + ++lineNo + }) + return found + }, + getAllMarks: function() { + var markers = [] + this.iter(function (line) { + var sps = line.markedSpans + if (sps) { for (var i = 0; i < sps.length; ++i) + { if (sps[i].from != null) { markers.push(sps[i].marker) } } } + }) + return markers + }, + + posFromIndex: function(off) { + var ch, lineNo = this.first, sepSize = this.lineSeparator().length + this.iter(function (line) { + var sz = line.text.length + sepSize + if (sz > off) { ch = off; return true } + off -= sz + ++lineNo + }) + return clipPos(this, Pos(lineNo, ch)) + }, + indexFromPos: function (coords) { + coords = clipPos(this, coords) + var index = coords.ch + if (coords.line < this.first || coords.ch < 0) { return 0 } + var sepSize = this.lineSeparator().length + this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value + index += line.text.length + sepSize + }) + return index + }, + + copy: function(copyHistory) { + var doc = new Doc(getLines(this, this.first, this.first + this.size), + this.modeOption, this.first, this.lineSep) + doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft + doc.sel = this.sel + doc.extend = false + if (copyHistory) { + doc.history.undoDepth = this.history.undoDepth + doc.setHistory(this.getHistory()) + } + return doc + }, + + linkedDoc: function(options) { + if (!options) { options = {} } + var from = this.first, to = this.first + this.size + if (options.from != null && options.from > from) { from = options.from } + if (options.to != null && options.to < to) { to = options.to } + var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep) + if (options.sharedHist) { copy.history = this.history + ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}) + copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}] + copySharedMarkers(copy, findSharedMarkers(this)) + return copy + }, + unlinkDoc: function(other) { + var this$1 = this; + + if (other instanceof CodeMirror) { other = other.doc } + if (this.linked) { for (var i = 0; i < this.linked.length; ++i) { + var link = this$1.linked[i] + if (link.doc != other) { continue } + this$1.linked.splice(i, 1) + other.unlinkDoc(this$1) + detachSharedMarkers(findSharedMarkers(this$1)) + break + } } + // If the histories were shared, split them again + if (other.history == this.history) { + var splitIds = [other.id] + linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true) + 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) { + if (this.lineSep) { return str.split(this.lineSep) } + return splitLinesAuto(str) + }, + lineSeparator: function() { return this.lineSep || "\n" } +}) + +// Public alias. +Doc.prototype.eachLine = Doc.prototype.iter + +// Kludge to work around strange IE behavior where it'll sometimes +// re-fire a series of drag-related events right after the drop (#1551) +var lastDrop = 0 + +function onDrop(e) { + var cm = this + clearDragCursor(cm) + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) + { return } + e_preventDefault(e) + if (ie) { lastDrop = +new Date } + var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files + if (!pos || cm.isReadOnly()) { return } + // Might be a file drop, in which case we simply extract the text + // and insert it. + if (files && files.length && window.FileReader && window.File) { + var n = files.length, text = Array(n), read = 0 + var loadFile = function (file, i) { + if (cm.options.allowDropFileTypes && + indexOf(cm.options.allowDropFileTypes, file.type) == -1) + { return } + + var reader = new FileReader + reader.onload = operation(cm, function () { + var content = reader.result + if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = "" } + text[i] = content + if (++read == n) { + pos = clipPos(cm.doc, pos) + var change = {from: pos, to: pos, + text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())), + origin: "paste"} + makeChange(cm.doc, change) + setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change))) } - if (updateNumber) { - removeChildren(lineView.lineNumber); - lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); + }) + reader.readAsText(file) + } + for (var i = 0; i < n; ++i) { loadFile(files[i], i) } + } else { // Normal drop + // Don't do a replace if the drop happened inside of the selected text. + if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { + cm.state.draggingText(e) + // Ensure the editor is re-focused + setTimeout(function () { return cm.display.input.focus(); }, 20) + return + } + try { + var text$1 = e.dataTransfer.getData("Text") + if (text$1) { + var selected + if (cm.state.draggingText && !cm.state.draggingText.copy) + { selected = cm.listSelections() } + setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)) + if (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){} + } +} + +function onDragStart(cm, e) { + if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return } + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return } + + e.dataTransfer.setData("Text", cm.getSelection()) + e.dataTransfer.effectAllowed = "copyMove" + + // Use dummy image instead of default browsers image. + // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. + if (e.dataTransfer.setDragImage && !safari) { + var img = elt("img", null, null, "position: fixed; left: 0; top: 0;") + img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" + if (presto) { + img.width = img.height = 1 + cm.display.wrapper.appendChild(img) + // Force a relayout, or Opera won't use our image for some obscure reason + img._top = img.offsetTop + } + e.dataTransfer.setDragImage(img, 0, 0) + if (presto) { img.parentNode.removeChild(img) } + } +} + +function onDragOver(cm, e) { + var pos = posFromMouse(cm, e) + if (!pos) { return } + var frag = document.createDocumentFragment() + drawSelectionCursor(cm, pos, frag) + if (!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, frag) +} + +function clearDragCursor(cm) { + if (cm.display.dragCursor) { + cm.display.lineSpace.removeChild(cm.display.dragCursor) + cm.display.dragCursor = null + } +} + +// These must be handled carefully, because naively registering a +// handler for each editor will cause the editors to never be +// garbage collected. + +function forEachCodeMirror(f) { + if (!document.body.getElementsByClassName) { return } + var byClass = document.body.getElementsByClassName("CodeMirror") + for (var i = 0; i < byClass.length; i++) { + var cm = byClass[i].CodeMirror + if (cm) { f(cm) } + } +} + +var globalsRegistered = false +function ensureGlobalHandlers() { + if (globalsRegistered) { return } + registerGlobalHandlers() + globalsRegistered = true +} +function registerGlobalHandlers() { + // When the window resizes, we need to refresh active editors. + var resizeTimer + on(window, "resize", function () { + if (resizeTimer == null) { resizeTimer = setTimeout(function () { + resizeTimer = null + forEachCodeMirror(onResize) + }, 100) } + }) + // When the window loses focus, we want to show the editor as blurred + on(window, "blur", function () { return forEachCodeMirror(onBlur); }) +} +// Called when the window resizes +function onResize(cm) { + var d = cm.display + if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth) + { return } + // Might be a text scaling operation, clear size caches. + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null + d.scrollbarsClipped = false + cm.setSize() +} + +var keyNames = { + 3: "Enter", 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: "/", 127: "Delete", + 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", + 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", + 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert" +} + +// Number keys +for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i) } +// Alphabetic keys +for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1) } +// Function keys +for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2 } + +var keyMap = {} + +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" +} +// Note that the save and find-related commands aren't defined by +// default. User code or addons can define them. Unknown commands +// are simply ignored. +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" +} +// Very basic readline/emacs-style bindings, which are standard on Mac. +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 + +// KEYMAP DISPATCH + +function normalizeKeyName(name) { + var parts = name.split(/-(?!$)/) + name = parts[parts.length - 1] + var alt, ctrl, shift, cmd + for (var i = 0; i < parts.length - 1; i++) { + var mod = parts[i] + if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true } + else if (/^a(lt)?$/i.test(mod)) { alt = true } + else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true } + else if (/^s(hift)?$/i.test(mod)) { shift = true } + else { throw new Error("Unrecognized modifier name: " + mod) } + } + if (alt) { name = "Alt-" + name } + if (ctrl) { name = "Ctrl-" + name } + if (cmd) { name = "Cmd-" + name } + if (shift) { name = "Shift-" + name } + return name +} + +// This is a kludge to keep keymaps mostly working as raw objects +// (backwards compatibility) while at the same time support features +// like normalization and multi-stroke key bindings. It compiles a +// new normalized keymap, and then updates the old object to reflect +// this. +function normalizeKeyMap(keymap) { + var copy = {} + for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) { + var value = keymap[keyname] + if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue } + if (value == "...") { delete keymap[keyname]; continue } + + var keys = map(keyname.split(" "), normalizeKeyName) + for (var i = 0; i < keys.length; i++) { + var val = void 0, name = void 0 + if (i == keys.length - 1) { + name = keys.join(" ") + val = value + } else { + name = keys.slice(0, i + 1).join(" ") + val = "..." + } + var prev = copy[name] + if (!prev) { copy[name] = val } + else if (prev != val) { throw new Error("Inconsistent bindings for " + name) } + } + delete keymap[keyname] + } } + for (var prop in copy) { keymap[prop] = copy[prop] } + return keymap +} + +function lookupKey(key, map, handle, context) { + map = getKeyMap(map) + var found = map.call ? map.call(key, context) : map[key] + if (found === false) { return "nothing" } + if (found === "...") { return "multi" } + if (found != null && handle(found)) { return "handled" } + + if (map.fallthrough) { + if (Object.prototype.toString.call(map.fallthrough) != "[object Array]") + { 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 } + } + } +} + +// Modifier key presses don't count as 'real' key presses for the +// purpose of keymap fallthrough. +function isModifierKey(value) { + var name = typeof value == "string" ? value : keyNames[value.keyCode] + return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod" +} + +// Look up the name of a key as indicated by an event object. +function keyName(event, noShift) { + if (presto && event.keyCode == 34 && event["char"]) { return false } + var base = keyNames[event.keyCode], name = base + if (name == null || event.altGraphKey) { return false } + if (event.altKey && base != "Alt") { name = "Alt-" + name } + if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name } + if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name } + if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name } + return name +} + +function getKeyMap(val) { + return typeof val == "string" ? keyMap[val] : val +} + +// Helper for deleting text near the selection(s), used to implement +// backspace, delete, and similar functionality. +function deleteNearSelection(cm, compute) { + var ranges = cm.doc.sel.ranges, kill = [] + // Build up a set of ranges to kill first, merging overlapping + // ranges. + for (var i = 0; i < ranges.length; i++) { + var toKill = compute(ranges[i]) + while (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) + } + // Next, remove those actual ranges. + runInOp(cm, function () { + for (var i = kill.length - 1; i >= 0; i--) + { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete") } + ensureCursorVisible(cm) + }) +} + +// Commands are parameter-less actions that can be performed on an +// editor, mostly used for keybindings. +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) { + if (range.empty()) { + var len = getLine(cm.doc, range.head.line).text.length + if (range.head.ch == len && range.head.line < cm.lastLine()) + { return {from: range.head, to: Pos(range.head.line + 1, 0)} } + else + { return {from: range.head, to: Pos(range.head.line, len)} } + } else { + return {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 + var leftPos = cm.coordsChar({left: 0, top: top}, "div") + return {from: leftPos, to: range.from()} + }); }, + delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) { + var top = cm.charCoords(range.head, "div").top + 5 + var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div") + return {from: range.from(), to: rightPos } + }); }, + 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 lineEnd(cm, range.head.line); }, + {origin: "+move", bias: -1} + ); }, + goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) { + var top = cm.charCoords(range.head, "div").top + 5 + return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div") + }, sel_move); }, + goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) { + var top = cm.charCoords(range.head, "div").top + 5 + return cm.coordsChar({left: 0, top: top}, "div") + }, sel_move); }, + goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) { + var top = cm.charCoords(range.head, "div").top + 5 + var pos = cm.coordsChar({left: 0, top: top}, "div") + if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) } + return pos + }, 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, "char"); }, + 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) { + var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize + for (var i = 0; i < ranges.length; i++) { + var pos = ranges[i].from() + var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize) + spaces.push(spaceStr(tabSize - col % tabSize)) + } + cm.replaceSelections(spaces) + }, + defaultTab: function (cm) { + if (cm.somethingSelected()) { cm.indentSelection("add") } + else { cm.execCommand("insertTab") } + }, + // Swap the two chars left and right of each selection's head. + // Move cursor behind the two swapped characters afterwards. + // + // Doesn't consider line feeds a character. + // Doesn't scan more than one line above to find a character. + // Doesn't do anything on an empty line. + // Doesn't do anything with non-empty selections. + transposeChars: function (cm) { return runInOp(cm, function () { + var ranges = cm.listSelections(), newSel = [] + for (var i = 0; i < ranges.length; i++) { + if (!ranges[i].empty()) { continue } + var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text + if (line) { + if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1) } + if (cur.ch > 0) { + 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") + } else if (cur.line > cm.doc.first) { + var prev = getLine(cm.doc, cur.line - 1).text + if (prev) { + 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") + } } - cur = lineView.node.nextSibling; } - lineN += lineView.size; - } - while (cur) cur = rm(cur); - } - - // When an aspect of a line changes, a string is added to - // lineView.changes. This updates the relevant part of the line's - // DOM structure. - function updateLineForChanges(cm, lineView, lineN, dims) { - for (var j = 0; j < lineView.changes.length; j++) { - var type = lineView.changes[j]; - if (type == "text") updateLineText(cm, lineView); - else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims); - else if (type == "class") updateLineClasses(lineView); - else if (type == "widget") updateLineWidgets(cm, lineView, dims); - } - lineView.changes = null; - } - - // Lines with gutter elements, widgets or a background class need to - // be wrapped, and have the extra elements added to the wrapper div - function ensureLineWrapped(lineView) { - if (lineView.node == lineView.text) { - lineView.node = elt("div", null, null, "position: relative"); - if (lineView.text.parentNode) - lineView.text.parentNode.replaceChild(lineView.node, lineView.text); - lineView.node.appendChild(lineView.text); - if (ie && ie_version < 8) lineView.node.style.zIndex = 2; - } - return lineView.node; - } - - function updateLineBackground(lineView) { - var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; - if (cls) cls += " CodeMirror-linebackground"; - if (lineView.background) { - if (cls) lineView.background.className = cls; - else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; } - } else if (cls) { - var wrap = ensureLineWrapped(lineView); - lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); - } - } - - // Wrapper around buildLineContent which will reuse the structure - // in display.externalMeasured when possible. - function getLineContent(cm, lineView) { - var ext = cm.display.externalMeasured; - if (ext && ext.line == lineView.line) { - cm.display.externalMeasured = null; - lineView.measure = ext.measure; - return ext.built; - } - return buildLineContent(cm, lineView); - } - - // Redraw the line's text. Interacts with the background and text - // classes because the mode may output tokens that influence these - // classes. - function updateLineText(cm, lineView) { - var cls = lineView.text.className; - var built = getLineContent(cm, lineView); - if (lineView.text == lineView.node) lineView.node = built.pre; - lineView.text.parentNode.replaceChild(built.pre, lineView.text); - lineView.text = built.pre; - if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { - lineView.bgClass = built.bgClass; - lineView.textClass = built.textClass; - updateLineClasses(lineView); - } else if (cls) { - lineView.text.className = cls; - } - } - - function updateLineClasses(lineView) { - updateLineBackground(lineView); - if (lineView.line.wrapClass) - ensureLineWrapped(lineView).className = lineView.line.wrapClass; - else if (lineView.node != lineView.text) - lineView.node.className = ""; - var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; - lineView.text.className = textClass || ""; - } - - function updateLineGutter(cm, lineView, lineN, dims) { - if (lineView.gutter) { - lineView.node.removeChild(lineView.gutter); - lineView.gutter = null; - } - if (lineView.gutterBackground) { - lineView.node.removeChild(lineView.gutterBackground); - lineView.gutterBackground = null; - } - if (lineView.line.gutterClass) { - var 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"); - wrap.insertBefore(lineView.gutterBackground, lineView.text); - } - var markers = lineView.line.gutterMarkers; - if (cm.options.lineNumbers || markers) { - var wrap = ensureLineWrapped(lineView); - var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " + - (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"); - cm.display.input.setUneditable(gutterWrap); - wrap.insertBefore(gutterWrap, lineView.text); - if (lineView.line.gutterClass) - gutterWrap.className += " " + lineView.line.gutterClass; - if (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")); - if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) { - var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]; - if (found) - gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " + - dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px")); + newSel.push(new Range(cur, cur)) + } + cm.setSelections(newSel) + }); }, + newlineAndIndent: function (cm) { return runInOp(cm, function () { + var sels = cm.listSelections() + for (var i = sels.length - 1; i >= 0; i--) + { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input") } + sels = cm.listSelections() + for (var i$1 = 0; i$1 < sels.length; i$1++) + { cm.indentLine(sels[i$1].from().line, null, true) } + 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) + var visual = visualLine(line) + if (visual != line) { lineN = lineNo(visual) } + var order = getOrder(visual) + var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual) + return Pos(lineN, ch) +} +function lineEnd(cm, lineN) { + var merged, line = getLine(cm.doc, lineN) + while (merged = collapsedSpanAtEnd(line)) { + line = merged.find(1, true).line + lineN = null + } + var order = getOrder(line) + var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line) + return Pos(lineN == null ? lineNo(line) : lineN, ch) +} +function lineStartSmart(cm, pos) { + var start = lineStart(cm, pos.line) + var line = getLine(cm.doc, start.line) + var order = getOrder(line) + if (!order || order[0].level == 0) { + var firstNonWS = Math.max(0, line.text.search(/\S/)) + var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch + return Pos(start.line, inWS ? 0 : firstNonWS) + } + return start +} + +// Run a handler that was bound to a key. +function doHandleBinding(cm, bound, dropShift) { + if (typeof bound == "string") { + bound = commands[bound] + if (!bound) { return false } + } + // Ensure previous input has been read, so that the handler sees a + // consistent view of the document + cm.display.input.ensurePolled() + var prevShift = cm.display.shift, done = false + try { + if (cm.isReadOnly()) { cm.state.suppressEdits = true } + if (dropShift) { cm.display.shift = false } + done = bound(cm) != Pass + } finally { + cm.display.shift = prevShift + cm.state.suppressEdits = false + } + return done +} + +function lookupKeyForEditor(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) +} + +var stopSeq = new Delayed +function dispatchKey(cm, name, e, handle) { + var seq = cm.state.keySeq + if (seq) { + if (isModifierKey(name)) { return "handled" } + stopSeq.set(50, function () { + if (cm.state.keySeq == seq) { + cm.state.keySeq = null + cm.display.input.reset() + } + }) + name = seq + " " + name + } + var result = lookupKeyForEditor(cm, name, handle) + + if (result == "multi") + { cm.state.keySeq = name } + if (result == "handled") + { signalLater(cm, "keyHandled", cm, name, e) } + + if (result == "handled" || result == "multi") { + e_preventDefault(e) + restartBlink(cm) + } + + if (seq && !result && /\'$/.test(name)) { + e_preventDefault(e) + return true + } + return !!result +} + +// Handle a key from the keydown event. +function handleKeyBinding(cm, e) { + var name = keyName(e, true) + if (!name) { return false } + + if (e.shiftKey && !cm.state.keySeq) { + // First try to resolve full name (including 'Shift-'). Failing + // that, see if there is a cursor-motion command (starting with + // 'go') bound to the keyname without 'Shift-'. + return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); }) + || dispatchKey(cm, name, e, function (b) { + if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) + { return doHandleBinding(cm, b) } + }) + } else { + return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); }) + } +} + +// Handle a key from the keypress event +function handleCharBinding(cm, e, ch) { + return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); }) +} + +var lastStoppedKey = null +function onKeyDown(e) { + var cm = this + cm.curOp.focus = activeElt() + if (signalDOMEvent(cm, e)) { return } + // IE does strange things with escape. + if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false } + var code = e.keyCode + cm.display.shift = code == 16 || e.shiftKey + var handled = handleKeyBinding(cm, e) + if (presto) { + lastStoppedKey = handled ? code : null + // Opera has no cut event... we try to at least catch the key combo + if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) + { cm.replaceSelection("", null, "cut") } + } + + // Turn mouse into crosshair when Alt is held on Mac. + if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) + { showCrossHair(cm) } +} + +function showCrossHair(cm) { + var lineDiv = cm.display.lineDiv + addClass(lineDiv, "CodeMirror-crosshair") + + function up(e) { + if (e.keyCode == 18 || !e.altKey) { + rmClass(lineDiv, "CodeMirror-crosshair") + off(document, "keyup", up) + off(document, "mouseover", up) + } + } + on(document, "keyup", up) + on(document, "mouseover", up) +} + +function onKeyUp(e) { + if (e.keyCode == 16) { this.doc.sel.shift = false } + signalDOMEvent(this, e) +} + +function onKeyPress(e) { + var cm = this + if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return } + var keyCode = e.keyCode, charCode = e.charCode + if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return} + if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return } + var ch = String.fromCharCode(charCode == null ? keyCode : charCode) + // Some browsers fire keypress events for backspace + if (ch == "\x08") { return } + if (handleCharBinding(cm, e, ch)) { return } + cm.display.input.onKeyPress(e) +} + +// A mouse down can be a single click, double click, triple click, +// start of selection drag, start of text drag, new cursor +// (ctrl-click), rectangle drag (alt-drag), or xwin +// middle-click-paste. Or it might be a click on something we should +// not interfere with, such as a scrollbar or widget. +function onMouseDown(e) { + var cm = this, display = cm.display + if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return } + display.shift = e.shiftKey + + if (eventInWidget(display, e)) { + if (!webkit) { + // Briefly turn off draggability, to allow widgets to do + // normal dragging things. + display.scroller.draggable = false + setTimeout(function () { return display.scroller.draggable = true; }, 100) + } + return + } + if (clickInGutter(cm, e)) { return } + var start = posFromMouse(cm, e) + window.focus() + + switch (e_button(e)) { + case 1: + // #3261: make sure, that we're not starting a second selection + if (cm.state.selectingText) + { cm.state.selectingText(e) } + else if (start) + { leftButtonDown(cm, e, start) } + else if (e_target(e) == display.scroller) + { e_preventDefault(e) } + break + case 2: + if (webkit) { cm.state.lastMiddleDown = +new Date } + if (start) { extendSelection(cm.doc, start) } + setTimeout(function () { return display.input.focus(); }, 20) + e_preventDefault(e) + break + case 3: + if (captureRightClick) { onContextMenu(cm, e) } + else { delayBlurEvent(cm) } + break + } +} + +var lastClick; +var lastDoubleClick; +function leftButtonDown(cm, e, start) { + if (ie) { setTimeout(bind(ensureFocus, cm), 0) } + else { cm.curOp.focus = activeElt() } + + var now = +new Date, type + if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) { + type = "triple" + } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) { + type = "double" + lastDoubleClick = {time: now, pos: start} + } else { + type = "single" + lastClick = {time: now, pos: start} + } + + var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained + if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() && + type == "single" && (contained = sel.contains(start)) > -1 && + (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) && + (cmp(contained.to(), start) > 0 || start.xRel < 0)) + { leftButtonStartDrag(cm, e, start, modifier) } + else + { leftButtonSelect(cm, e, start, type, modifier) } +} + +// Start a text drag. When it ends, see if any dragging actually +// happen, and treat as a click if it didn't. +function leftButtonStartDrag(cm, e, start, modifier) { + var display = cm.display, startTime = +new Date + var dragEnd = operation(cm, function (e2) { + if (webkit) { display.scroller.draggable = false } + cm.state.draggingText = false + off(document, "mouseup", dragEnd) + off(display.scroller, "drop", dragEnd) + if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) { + e_preventDefault(e2) + if (!modifier && +new Date - 200 < startTime) + { extendSelection(cm.doc, start) } + // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081) + if (webkit || ie && ie_version == 9) + { setTimeout(function () {document.body.focus(); display.input.focus()}, 20) } + else + { display.input.focus() } + } + }) + // Let the drag handler handle this. + if (webkit) { display.scroller.draggable = true } + cm.state.draggingText = dragEnd + dragEnd.copy = mac ? e.altKey : e.ctrlKey + // IE's approach to draggable + if (display.scroller.dragDrop) { display.scroller.dragDrop() } + on(document, "mouseup", dragEnd) + on(display.scroller, "drop", dragEnd) +} + +// Normal selection, as opposed to text dragging. +function leftButtonSelect(cm, e, start, type, addNew) { + var display = cm.display, doc = cm.doc + e_preventDefault(e) + + var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges + if (addNew && !e.shiftKey) { + ourIndex = doc.sel.contains(start) + if (ourIndex > -1) + { ourRange = ranges[ourIndex] } + else + { ourRange = new Range(start, start) } + } else { + ourRange = doc.sel.primary() + ourIndex = doc.sel.primIndex + } + + if (chromeOS ? e.shiftKey && e.metaKey : e.altKey) { + type = "rect" + if (!addNew) { ourRange = new Range(start, start) } + start = posFromMouse(cm, e, true, true) + ourIndex = -1 + } else if (type == "double") { + var word = cm.findWordAt(start) + if (cm.display.shift || doc.extend) + { ourRange = extendRange(doc, ourRange, word.anchor, word.head) } + else + { ourRange = word } + } else if (type == "triple") { + var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0))) + if (cm.display.shift || doc.extend) + { ourRange = extendRange(doc, ourRange, line.anchor, line.head) } + else + { ourRange = line } + } else { + ourRange = extendRange(doc, ourRange, start) + } + + if (!addNew) { + ourIndex = 0 + setSelection(doc, new Selection([ourRange], 0), sel_mouse) + startSel = doc.sel + } else if (ourIndex == -1) { + ourIndex = ranges.length + setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex), + {scroll: false, origin: "*mouse"}) + } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) { + setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), + {scroll: false, origin: "*mouse"}) + startSel = doc.sel + } else { + replaceOneSelection(doc, ourIndex, ourRange, sel_mouse) + } + + var lastPos = start + function extendTo(pos) { + if (cmp(lastPos, pos) == 0) { return } + lastPos = pos + + if (type == "rect") { + var ranges = [], tabSize = cm.options.tabSize + var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize) + var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize) + var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol) + for (var 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) + if (left == right) + { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))) } + else if (text.length > leftPos) + { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))) } + } + if (!ranges.length) { ranges.push(new Range(start, start)) } + setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), + {origin: "*mouse", scroll: false}) + cm.scrollIntoView(pos) + } else { + var oldRange = ourRange + var anchor = oldRange.anchor, head = pos + if (type != "single") { + var range + if (type == "double") + { range = cm.findWordAt(pos) } + else + { range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0))) } + if (cmp(range.anchor, anchor) > 0) { + head = range.head + anchor = minPos(oldRange.from(), range.anchor) + } else { + head = range.anchor + anchor = maxPos(oldRange.to(), range.head) + } } - } - } - - function updateLineWidgets(cm, lineView, dims) { - if (lineView.alignable) lineView.alignable = null; - for (var node = lineView.node.firstChild, next; node; node = next) { - var next = node.nextSibling; - if (node.className == "CodeMirror-linewidget") - lineView.node.removeChild(node); - } - insertLineWidgets(cm, lineView, dims); - } - - // Build a line's DOM representation from scratch - function buildLineElement(cm, lineView, lineN, dims) { - var built = getLineContent(cm, lineView); - lineView.text = lineView.node = built.pre; - if (built.bgClass) lineView.bgClass = built.bgClass; - if (built.textClass) lineView.textClass = built.textClass; + var ranges$1 = startSel.ranges.slice(0) + ranges$1[ourIndex] = new Range(clipPos(doc, anchor), head) + setSelection(doc, normalizeSelection(ranges$1, ourIndex), sel_mouse) + } + } + + var editorSize = display.wrapper.getBoundingClientRect() + // Used to ensure timeout re-tries don't fire when another extend + // happened in the meantime (clearTimeout isn't reliable -- at + // least on Chrome, the timeouts still happen even when cleared, + // if the clear happens after their scheduled firing time). + var counter = 0 + + function extend(e) { + var curCount = ++counter + var cur = posFromMouse(cm, e, true, type == "rect") + if (!cur) { return } + if (cmp(cur, lastPos) != 0) { + cm.curOp.focus = activeElt() + extendTo(cur) + var visible = visibleLines(display, doc) + if (cur.line >= visible.to || cur.line < visible.from) + { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e) }}), 150) } + } else { + var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0 + if (outside) { setTimeout(operation(cm, function () { + if (counter != curCount) { return } + display.scroller.scrollTop += outside + extend(e) + }), 50) } + } + } + + function done(e) { + cm.state.selectingText = false + counter = Infinity + e_preventDefault(e) + display.input.focus() + off(document, "mousemove", move) + off(document, "mouseup", up) + doc.history.lastSelOrigin = null + } + + var move = operation(cm, function (e) { + if (!e_button(e)) { done(e) } + else { extend(e) } + }) + var up = operation(cm, done) + cm.state.selectingText = up + on(document, "mousemove", move) + on(document, "mouseup", up) +} + + +// Determines whether an event happened in the gutter, and fires the +// handlers for the corresponding event. +function gutterEvent(cm, e, type, prevent) { + var mX, mY + try { mX = e.clientX; mY = e.clientY } + catch(e) { return false } + if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false } + if (prevent) { e_preventDefault(e) } + + var display = cm.display + var lineBox = display.lineDiv.getBoundingClientRect() + + if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) } + mY -= lineBox.top - display.viewOffset + + for (var i = 0; i < cm.options.gutters.length; ++i) { + var g = display.gutters.childNodes[i] + if (g && g.getBoundingClientRect().right >= mX) { + var line = lineAtHeight(cm.doc, mY) + var gutter = cm.options.gutters[i] + signal(cm, type, cm, line, gutter, e) + return e_defaultPrevented(e) + } + } +} + +function clickInGutter(cm, e) { + return gutterEvent(cm, e, "gutterClick", true) +} + +// CONTEXT MENU HANDLING + +// To make the context menu work, we need to briefly unhide the +// textarea (making it as unobtrusive as possible) to let the +// right-click take effect on it. +function onContextMenu(cm, e) { + if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return } + if (signalDOMEvent(cm, e, "contextmenu")) { return } + cm.display.input.onContextMenu(e) +} + +function contextMenuInGutter(cm, e) { + if (!hasHandler(cm, "gutterContextMenu")) { return false } + return gutterEvent(cm, e, "gutterContextMenu", false) +} + +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) +} + +var Init = {toString: function(){return "CodeMirror.Init"}} + +var defaults = {} +var optionHandlers = {} + +function defineOptions(CodeMirror) { + var optionHandlers = CodeMirror.optionHandlers - updateLineClasses(lineView); - updateLineGutter(cm, lineView, lineN, dims); - insertLineWidgets(cm, lineView, dims); - return lineView.node; + function option(name, deflt, handle, notOnInit) { + CodeMirror.defaults[name] = deflt + if (handle) { optionHandlers[name] = + notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old) }} : handle } } - // A lineView may contain multiple logical lines (when merged by - // collapsed spans). The widgets for all of them need to be drawn. - function insertLineWidgets(cm, lineView, dims) { - insertLineWidgetsFor(cm, lineView.line, lineView, dims, true); - if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++) - insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); - } + CodeMirror.defineOption = option - function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { - if (!line.widgets) return; - var wrap = ensureLineWrapped(lineView); - for (var i = 0, ws = line.widgets; i < ws.length; ++i) { - var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget"); - if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true"); - positionLineWidget(widget, node, lineView, dims); - cm.display.input.setUneditable(node); - if (allowAbove && widget.above) - wrap.insertBefore(node, lineView.gutter || lineView.text); - else - wrap.appendChild(node); - signalLater(widget, "redraw"); - } - } + // Passed to option handlers when there is no old value. + CodeMirror.Init = Init - function positionLineWidget(widget, node, lineView, dims) { - if (widget.noHScroll) { - (lineView.alignable || (lineView.alignable = [])).push(node); - var width = dims.wrapperWidth; - node.style.left = dims.fixedPos + "px"; - if (!widget.coverGutter) { - width -= dims.gutterTotalWidth; - node.style.paddingLeft = dims.gutterTotalWidth + "px"; + // These two are, on init, called from the constructor because they + // have to be initialized before the editor can start at all. + option("value", "", function (cm, val) { return cm.setValue(val); }, true) + option("mode", null, function (cm, val) { + cm.doc.modeOption = val + loadMode(cm) + }, true) + + option("indentUnit", 2, loadMode, true) + option("indentWithTabs", false) + option("smartIndent", true) + option("tabSize", 4, function (cm) { + resetModeState(cm) + clearCaches(cm) + regChange(cm) + }, true) + option("lineSeparator", null, function (cm, val) { + cm.doc.lineSep = val + if (!val) { return } + var newBreaks = [], lineNo = cm.doc.first + cm.doc.iter(function (line) { + for (var pos = 0;;) { + var found = line.text.indexOf(val, pos) + if (found == -1) { break } + pos = found + val.length + newBreaks.push(Pos(lineNo, found)) } - node.style.width = width + "px"; - } - if (widget.coverGutter) { - node.style.zIndex = 5; - node.style.position = "relative"; - if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px"; + lineNo++ + }) + for (var i = newBreaks.length - 1; i >= 0; i--) + { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)) } + }) + option("specialChars", /[\u0000-\u001f\u007f\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) { + cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g") + if (old != Init) { cm.refresh() } + }) + option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true) + option("electricChars", true) + option("inputStyle", mobile ? "contenteditable" : "textarea", function () { + throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME + }, true) + option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true) + option("rtlMoveVisually", !windows) + option("wholeLineUpdateBefore", true) + + option("theme", "default", function (cm) { + themeChanged(cm) + guttersChanged(cm) + }, true) + option("keyMap", "default", function (cm, val, old) { + var next = getKeyMap(val) + var prev = old != Init && getKeyMap(old) + if (prev && prev.detach) { prev.detach(cm, next) } + if (next.attach) { next.attach(cm, prev || null) } + }) + option("extraKeys", null) + + option("lineWrapping", false, wrappingChanged, true) + option("gutters", [], function (cm) { + setGuttersForLineNumbers(cm.options) + guttersChanged(cm) + }, true) + option("fixedGutter", true, function (cm, val) { + cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0" + cm.refresh() + }, true) + option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true) + option("scrollbarStyle", "native", function (cm) { + initScrollbars(cm) + updateScrollbars(cm) + cm.display.scrollbars.setScrollTop(cm.doc.scrollTop) + cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft) + }, true) + option("lineNumbers", false, function (cm) { + setGuttersForLineNumbers(cm.options) + guttersChanged(cm) + }, true) + option("firstLineNumber", 1, guttersChanged, true) + option("lineNumberFormatter", function (integer) { return integer; }, guttersChanged, true) + option("showCursorWhenSelecting", false, updateSelection, true) + + option("resetSelectionOnContextMenu", true) + option("lineWiseCopyCut", true) + + option("readOnly", false, function (cm, val) { + if (val == "nocursor") { + onBlur(cm) + cm.display.input.blur() + cm.display.disabled = true + } else { + cm.display.disabled = false } - } - - // POSITION OBJECT - - // A Pos instance represents a position within the text. - var Pos = CodeMirror.Pos = function(line, ch) { - if (!(this instanceof Pos)) return new Pos(line, ch); - this.line = line; this.ch = ch; - }; - - // Compare two positions, return 0 if they are the same, a negative - // number when a is less, and a positive number otherwise. - var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; }; + cm.display.input.readOnlyChanged(val) + }) + option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset() }}, true) + option("dragDrop", true, dragDropChanged) + option("allowDropFileTypes", null) + + option("cursorBlinkRate", 530) + option("cursorScrollMargin", 0) + option("cursorHeight", 1, updateSelection, true) + option("singleCursorHeightPerLine", true, updateSelection, true) + option("workTime", 100) + option("workDelay", 100) + option("flattenSpans", true, resetModeState, true) + option("addModeClass", false, resetModeState, true) + 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(); }, true) + option("maxHighlightLength", 10000, resetModeState, true) + option("moveInputWithCursor", true, function (cm, val) { + if (!val) { cm.display.input.resetPosition() } + }) + + option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; }) + option("autofocus", null) +} + +function guttersChanged(cm) { + updateGutters(cm) + regChange(cm) + setTimeout(function () { return alignHorizontally(cm); }, 20) +} + +function dragDropChanged(cm, value, old) { + var wasOn = old && old != Init + if (!value != !wasOn) { + var funcs = cm.display.dragFunctions + var toggle = value ? on : off + toggle(cm.display.scroller, "dragstart", funcs.start) + toggle(cm.display.scroller, "dragenter", funcs.enter) + toggle(cm.display.scroller, "dragover", funcs.over) + toggle(cm.display.scroller, "dragleave", funcs.leave) + toggle(cm.display.scroller, "drop", funcs.drop) + } +} + +function wrappingChanged(cm) { + if (cm.options.lineWrapping) { + addClass(cm.display.wrapper, "CodeMirror-wrap") + cm.display.sizer.style.minWidth = "" + cm.display.sizerWidth = null + } else { + rmClass(cm.display.wrapper, "CodeMirror-wrap") + findMaxLine(cm) + } + estimateLineHeights(cm) + regChange(cm) + clearCaches(cm) + setTimeout(function () { return updateScrollbars(cm); }, 100) +} + +// A CodeMirror instance represents an editor. This is the object +// that user code is usually dealing with. + +function CodeMirror(place, options) { + var this$1 = this; + + if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) } + + this.options = options = options ? copyObj(options) : {} + // Determine effective options based on given values and defaults. + copyObj(defaults, options, false) + setGuttersForLineNumbers(options) + + var doc = options.value + if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator) } + this.doc = doc + + var input = new CodeMirror.inputStyles[options.inputStyle](this) + var display = this.display = new Display(place, doc, input) + display.wrapper.CodeMirror = this + updateGutters(this) + themeChanged(this) + if (options.lineWrapping) + { this.display.wrapper.className += " CodeMirror-wrap" } + if (options.autofocus && !mobile) { display.input.focus() } + initScrollbars(this) + + this.state = { + keyMaps: [], // stores maps added by addKeyMap + overlays: [], // highlighting overlays, as added by addOverlay + modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info + overwrite: false, + delayingBlurEvent: false, + focused: false, + suppressEdits: false, // used to disable editing during key handlers when in readOnly mode + pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll + selectingText: false, + draggingText: false, + highlight: new Delayed(), // stores highlight worker timeout + keySeq: null, // Unfinished key sequence + specialChars: null + } + + // Override magic textarea content restore that IE sometimes does + // on our hidden textarea on reload + if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20) } + + registerEventHandlers(this) + ensureGlobalHandlers() + + startOperation(this) + this.curOp.forceUpdate = true + attachDoc(this, doc) + + if ((options.autofocus && !mobile) || this.hasFocus()) + { setTimeout(bind(onFocus, this), 20) } + else + { onBlur(this) } + + for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt)) + { optionHandlers[opt](this$1, options[opt], Init) } } + maybeUpdateLineNumberWidth(this) + if (options.finishInit) { options.finishInit(this) } + for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1) } + endOperation(this) + // Suppress optimizelegibility in Webkit, since it breaks text + // measuring on line wrapping boundaries. + if (webkit && options.lineWrapping && + getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") + { display.lineDiv.style.textRendering = "auto" } +} + +// The default configuration options. +CodeMirror.defaults = defaults +// Functions to run when options are changed. +CodeMirror.optionHandlers = optionHandlers + +// Attach the necessary event handlers when initializing the editor +function registerEventHandlers(cm) { + var d = cm.display + on(d.scroller, "mousedown", operation(cm, onMouseDown)) + // Older IE's will not fire a second mousedown for a double click + if (ie && ie_version < 11) + { on(d.scroller, "dblclick", operation(cm, function (e) { + if (signalDOMEvent(cm, e)) { return } + var pos = posFromMouse(cm, e) + if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return } + e_preventDefault(e) + var word = cm.findWordAt(pos) + extendSelection(cm.doc, word.anchor, word.head) + })) } + else + { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }) } + // Some browsers fire contextmenu *after* opening the menu, at + // which point we can't mess with it anymore. Context menu is + // handled in onMouseDown for these browsers. + if (!captureRightClick) { on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }) } + + // Used to suppress mouse event handling when a touch happens + var touchFinished, prevTouch = {end: 0} + function finishTouch() { + if (d.activeTouch) { + touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000) + prevTouch = d.activeTouch + prevTouch.end = +new Date + } + } + function isMouseLikeTouchEvent(e) { + if (e.touches.length != 1) { return false } + var touch = e.touches[0] + return touch.radiusX <= 1 && touch.radiusY <= 1 + } + function farAway(touch, other) { + if (other.left == null) { return true } + var dx = other.left - touch.left, dy = other.top - touch.top + return dx * dx + dy * dy > 20 * 20 + } + on(d.scroller, "touchstart", function (e) { + if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e)) { + clearTimeout(touchFinished) + var now = +new Date + d.activeTouch = {start: now, moved: false, + prev: now - prevTouch.end <= 300 ? prevTouch : null} + if (e.touches.length == 1) { + d.activeTouch.left = e.touches[0].pageX + d.activeTouch.top = e.touches[0].pageY + } + } + }) + on(d.scroller, "touchmove", function () { + if (d.activeTouch) { d.activeTouch.moved = true } + }) + on(d.scroller, "touchend", function (e) { + var touch = d.activeTouch + if (touch && !eventInWidget(d, e) && touch.left != null && + !touch.moved && new Date - touch.start < 300) { + var pos = cm.coordsChar(d.activeTouch, "page"), range + if (!touch.prev || farAway(touch, touch.prev)) // Single tap + { range = new Range(pos, pos) } + else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap + { range = cm.findWordAt(pos) } + else // Triple tap + { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) } + cm.setSelection(range.anchor, range.head) + cm.focus() + e_preventDefault(e) + } + finishTouch() + }) + on(d.scroller, "touchcancel", finishTouch) + + // Sync scrolling between fake scrollbars and real scrollable + // area, ensure viewport is updated when scrolling. + on(d.scroller, "scroll", function () { + if (d.scroller.clientHeight) { + setScrollTop(cm, d.scroller.scrollTop) + setScrollLeft(cm, d.scroller.scrollLeft, true) + signal(cm, "scroll", cm) + } + }) + + // Listen to wheel events in order to try and update the viewport on time. + on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); }) + on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); }) + + // Prevent wrapper from ever scrolling + on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }) + + d.dragFunctions = { + enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e) }}, + over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e) }}, + start: function (e) { return onDragStart(cm, e); }, + drop: operation(cm, onDrop), + leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm) }} + } + + var inp = d.input.getField() + on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); }) + on(inp, "keydown", operation(cm, onKeyDown)) + on(inp, "keypress", operation(cm, onKeyPress)) + on(inp, "focus", function (e) { return onFocus(cm, e); }) + on(inp, "blur", function (e) { return onBlur(cm, e); }) +} + +var initHooks = [] +CodeMirror.defineInitHook = function (f) { return initHooks.push(f); } + +// Indent the given line. The how parameter can be "smart", +// "add"/null, "subtract", or "prev". When aggressive is false +// (typically set to true for forced single-line indents), empty +// lines are not indented, and places where the mode returns Pass +// are left alone. +function indentLine(cm, n, how, aggressive) { + var doc = cm.doc, state + if (how == null) { how = "add" } + if (how == "smart") { + // Fall back to "prev" when the mode doesn't have an indentation + // method. + if (!doc.mode.indent) { how = "prev" } + else { state = getStateBefore(cm, n) } + } + + var tabSize = cm.options.tabSize + var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize) + if (line.stateAfter) { line.stateAfter = null } + var curSpaceString = line.text.match(/^\s*/)[0], indentation + if (!aggressive && !/\S/.test(line.text)) { + indentation = 0 + how = "not" + } else if (how == "smart") { + indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text) + if (indentation == Pass || indentation > 150) { + if (!aggressive) { return } + how = "prev" + } + } + if (how == "prev") { + if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize) } + else { indentation = 0 } + } else if (how == "add") { + indentation = curSpace + cm.options.indentUnit + } else if (how == "subtract") { + indentation = curSpace - cm.options.indentUnit + } else if (typeof how == "number") { + indentation = curSpace + how + } + indentation = Math.max(0, indentation) + + var 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) } + + if (indentString != curSpaceString) { + replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input") + line.stateAfter = null + return true + } else { + // Ensure that, if the cursor was in the whitespace at the start + // of the line, it is moved to the end of that space. + 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) { + var pos$1 = Pos(n, curSpaceString.length) + replaceOneSelection(doc, i$1, new Range(pos$1, pos$1)) + break + } + } + } +} + +// This will be set to a {lineWise: bool, text: [string]} object, so +// that, when pasting, we know what kind of selections the copied +// text was made out of. +var lastCopied = null + +function setLastCopied(newLastCopied) { + lastCopied = newLastCopied +} + +function applyTextInput(cm, inserted, deleted, sel, origin) { + var doc = cm.doc + cm.display.shift = false + if (!sel) { sel = doc.sel } + + var paste = cm.state.pasteIncoming || origin == "paste" + var textLines = splitLinesAuto(inserted), multiPaste = null + // When pasing N lines into N selections, insert one line per selection + if (paste && sel.ranges.length > 1) { + if (lastCopied && lastCopied.text.join("\n") == inserted) { + if (sel.ranges.length % lastCopied.text.length == 0) { + multiPaste = [] + for (var i = 0; i < lastCopied.text.length; i++) + { multiPaste.push(doc.splitLines(lastCopied.text[i])) } + } + } else if (textLines.length == sel.ranges.length) { + multiPaste = map(textLines, function (l) { return [l]; }) + } + } + + var updateInput + // Normal behavior is to insert the new text into every selection + for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) { + var range = sel.ranges[i$1] + var from = range.from(), to = range.to() + if (range.empty()) { + if (deleted && deleted > 0) // Handle deletion + { from = Pos(from.line, from.ch - deleted) } + else if (cm.state.overwrite && !paste) // Handle overwrite + { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)) } + else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted) + { from = to = Pos(from.line, 0) } + } + updateInput = cm.curOp.updateInput + var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines, + origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")} + makeChange(cm.doc, changeEvent) + signalLater(cm, "inputRead", cm, changeEvent) + } + if (inserted && !paste) + { triggerElectric(cm, inserted) } + + ensureCursorVisible(cm) + cm.curOp.updateInput = updateInput + cm.curOp.typing = true + cm.state.pasteIncoming = cm.state.cutIncoming = false +} + +function handlePaste(e, cm) { + var pasted = e.clipboardData && e.clipboardData.getData("Text") + if (pasted) { + e.preventDefault() + if (!cm.isReadOnly() && !cm.options.disableInput) + { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }) } + return true + } +} + +function triggerElectric(cm, inserted) { + // When an 'electric' character is inserted, immediately trigger a reindent + if (!cm.options.electricChars || !cm.options.smartIndent) { return } + var sel = cm.doc.sel + + for (var i = sel.ranges.length - 1; i >= 0; i--) { + var range = sel.ranges[i] + if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue } + var mode = cm.getModeAt(range.head) + var indented = false + if (mode.electricChars) { + for (var j = 0; j < mode.electricChars.length; j++) + { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { + indented = indentLine(cm, range.head.line, "smart") + break + } } + } else if (mode.electricInput) { + if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch))) + { indented = indentLine(cm, range.head.line, "smart") } + } + if (indented) { signalLater(cm, "electricInput", cm, range.head.line) } + } +} + +function copyableRanges(cm) { + var text = [], ranges = [] + for (var i = 0; i < cm.doc.sel.ranges.length; i++) { + var line = cm.doc.sel.ranges[i].head.line + var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)} + ranges.push(lineRange) + text.push(cm.getRange(lineRange.anchor, lineRange.head)) + } + return {text: text, ranges: ranges} +} + +function disableBrowserMagic(field, spellcheck) { + field.setAttribute("autocorrect", "off") + field.setAttribute("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") + var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;") + // The textarea is kept positioned near the cursor to prevent the + // fact that it'll be scrolled into view on input from scrolling + // our fake cursor out of view. On webkit, when wrap=off, paste is + // very slow. So make the area wide instead. + if (webkit) { te.style.width = "1000px" } + else { te.setAttribute("wrap", "off") } + // If border: 0; -- iOS fails to open keyboard (issue #1287) + if (ios) { te.style.border = "1px solid black" } + disableBrowserMagic(te) + return div +} + +// The publicly visible API. Note that methodOp(f) means +// 'wrap f in an operation, performed on its `this` parameter'. + +// This is not the complete set of editor methods. Most of the +// methods defined on the Doc type are also injected into +// CodeMirror.prototype, for backwards compatibility and +// convenience. + +function addEditorMethods(CodeMirror) { + var optionHandlers = CodeMirror.optionHandlers + + var helpers = CodeMirror.helpers = {} - 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; } + CodeMirror.prototype = { + constructor: CodeMirror, + focus: function(){window.focus(); this.display.input.focus()}, - // INPUT HANDLING + setOption: function(option, value) { + var options = this.options, old = options[option] + if (options[option] == value && option != "mode") { return } + options[option] = value + if (optionHandlers.hasOwnProperty(option)) + { operation(this, optionHandlers[option])(this, value, old) } + }, - function ensureFocus(cm) { - if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); } - } + getOption: function(option) {return this.options[option]}, + getDoc: function() {return this.doc}, - // This will be set to a {lineWise: bool, text: [string]} object, so - // that, when pasting, we know what kind of selections the copied - // text was made out of. - var lastCopied = null; + addKeyMap: function(map, bottom) { + this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map)) + }, + removeKeyMap: function(map) { + var maps = this.state.keyMaps + for (var i = 0; i < maps.length; ++i) + { if (maps[i] == map || maps[i].name == map) { + maps.splice(i, 1) + return true + } } + }, - function applyTextInput(cm, inserted, deleted, sel, origin) { - var doc = cm.doc; - cm.display.shift = false; - if (!sel) sel = doc.sel; + 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.") } + insertSorted(this.state.overlays, + {mode: mode, modeSpec: spec, opaque: options && options.opaque, + priority: (options && options.priority) || 0}, + function (overlay) { return overlay.priority; }) + this.state.modeGen++ + regChange(this) + }), + removeOverlay: methodOp(function(spec) { + var this$1 = this; - var paste = cm.state.pasteIncoming || origin == "paste"; - var textLines = doc.splitLines(inserted), multiPaste = null - // When pasing N lines into N selections, insert one line per selection - if (paste && sel.ranges.length > 1) { - if (lastCopied && lastCopied.text.join("\n") == inserted) { - if (sel.ranges.length % lastCopied.text.length == 0) { - multiPaste = []; - for (var i = 0; i < lastCopied.text.length; i++) - multiPaste.push(doc.splitLines(lastCopied.text[i])); + var overlays = this.state.overlays + for (var i = 0; i < overlays.length; ++i) { + var cur = overlays[i].modeSpec + if (cur == spec || typeof spec == "string" && cur.name == spec) { + overlays.splice(i, 1) + this$1.state.modeGen++ + regChange(this$1) + return } - } else if (textLines.length == sel.ranges.length) { - multiPaste = map(textLines, function(l) { return [l]; }); } - } + }), - // Normal behavior is to insert the new text into every selection - for (var i = sel.ranges.length - 1; i >= 0; i--) { - var range = sel.ranges[i]; - var from = range.from(), to = range.to(); - if (range.empty()) { - if (deleted && deleted > 0) // Handle deletion - from = Pos(from.line, from.ch - deleted); - else if (cm.state.overwrite && !paste) // Handle overwrite - to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); - else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted) - from = to = Pos(from.line, 0) - } - var updateInput = cm.curOp.updateInput; - var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines, - origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")}; - makeChange(cm.doc, changeEvent); - signalLater(cm, "inputRead", cm, changeEvent); - } - if (inserted && !paste) - triggerElectric(cm, inserted); - - ensureCursorVisible(cm); - cm.curOp.updateInput = updateInput; - cm.curOp.typing = true; - cm.state.pasteIncoming = cm.state.cutIncoming = false; - } - - function handlePaste(e, cm) { - var pasted = e.clipboardData && e.clipboardData.getData("Text"); - if (pasted) { - e.preventDefault(); - if (!cm.isReadOnly() && !cm.options.disableInput) - runInOp(cm, function() { applyTextInput(cm, pasted, 0, null, "paste"); }); - return true; - } - } - - function triggerElectric(cm, inserted) { - // When an 'electric' character is inserted, immediately trigger a reindent - if (!cm.options.electricChars || !cm.options.smartIndent) return; - var sel = cm.doc.sel; - - for (var i = sel.ranges.length - 1; i >= 0; i--) { - var range = sel.ranges[i]; - if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue; - var mode = cm.getModeAt(range.head); - var indented = false; - if (mode.electricChars) { - for (var j = 0; j < mode.electricChars.length; j++) - if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { - indented = indentLine(cm, range.head.line, "smart"); - break; - } - } else if (mode.electricInput) { - if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch))) - indented = indentLine(cm, range.head.line, "smart"); + indentLine: methodOp(function(n, dir, aggressive) { + if (typeof dir != "string" && typeof dir != "number") { + if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev" } + else { dir = dir ? "add" : "subtract" } } - if (indented) signalLater(cm, "electricInput", cm, range.head.line); - } - } - - function copyableRanges(cm) { - var text = [], ranges = []; - for (var i = 0; i < cm.doc.sel.ranges.length; i++) { - var line = cm.doc.sel.ranges[i].head.line; - var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}; - ranges.push(lineRange); - text.push(cm.getRange(lineRange.anchor, lineRange.head)); - } - return {text: text, ranges: ranges}; - } - - function disableBrowserMagic(field, spellcheck) { - field.setAttribute("autocorrect", "off"); - field.setAttribute("autocapitalize", "off"); - field.setAttribute("spellcheck", !!spellcheck); - } - - // TEXTAREA INPUT STYLE - - function TextareaInput(cm) { - this.cm = cm; - // See input.poll and input.reset - this.prevInput = ""; - - // Flag that indicates whether we expect input to appear real soon - // now (after some event like 'keypress' or 'input') and are - // polling intensively. - this.pollingFast = false; - // Self-resetting timeout for the poller - this.polling = new Delayed(); - // Tracks when input.reset has punted to just putting a short - // string into the textarea instead of the full selection. - this.inaccurateSelection = false; - // Used to work around IE issue with selection being forgotten when focus moves away from textarea - this.hasSelection = false; - this.composing = null; - }; + if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive) } + }), + indentSelection: methodOp(function(how) { + var this$1 = this; - function hiddenTextarea() { - var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none"); - var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); - // The textarea is kept positioned near the cursor to prevent the - // fact that it'll be scrolled into view on input from scrolling - // our fake cursor out of view. On webkit, when wrap=off, paste is - // very slow. So make the area wide instead. - if (webkit) te.style.width = "1000px"; - else te.setAttribute("wrap", "off"); - // If border: 0; -- iOS fails to open keyboard (issue #1287) - if (ios) te.style.border = "1px solid black"; - disableBrowserMagic(te); - return div; - } - - TextareaInput.prototype = copyObj({ - init: function(display) { - var input = this, cm = this.cm; - - // Wraps and hides input textarea - var div = this.wrapper = hiddenTextarea(); - // The semihidden textarea that is focused when the editor is - // focused, and receives input. - var te = this.textarea = div.firstChild; - display.wrapper.insertBefore(div, display.wrapper.firstChild); - - // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore) - if (ios) te.style.width = "0px"; - - on(te, "input", function() { - if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null; - input.poll(); - }); - - on(te, "paste", function(e) { - if (signalDOMEvent(cm, e) || handlePaste(e, cm)) return - - cm.state.pasteIncoming = true; - input.fastPoll(); - }); - - function prepareCopyCut(e) { - if (signalDOMEvent(cm, e)) return - if (cm.somethingSelected()) { - lastCopied = {lineWise: false, text: cm.getSelections()}; - if (input.inaccurateSelection) { - input.prevInput = ""; - input.inaccurateSelection = false; - te.value = lastCopied.text.join("\n"); - selectInput(te); - } - } else if (!cm.options.lineWiseCopyCut) { - return; - } else { - var ranges = copyableRanges(cm); - lastCopied = {lineWise: true, text: ranges.text}; - if (e.type == "cut") { - cm.setSelections(ranges.ranges, null, sel_dontScroll); - } else { - input.prevInput = ""; - te.value = ranges.text.join("\n"); - selectInput(te); - } - } - if (e.type == "cut") cm.state.cutIncoming = true; - } - on(te, "cut", prepareCopyCut); - on(te, "copy", prepareCopyCut); - - on(display.scroller, "paste", function(e) { - if (eventInWidget(display, e) || signalDOMEvent(cm, e)) return; - cm.state.pasteIncoming = true; - input.focus(); - }); - - // Prevent normal selection in the editor (we handle our own) - on(display.lineSpace, "selectstart", function(e) { - if (!eventInWidget(display, e)) e_preventDefault(e); - }); - - on(te, "compositionstart", function() { - var start = cm.getCursor("from"); - if (input.composing) input.composing.range.clear() - input.composing = { - start: start, - range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"}) - }; - }); - on(te, "compositionend", function() { - if (input.composing) { - input.poll(); - input.composing.range.clear(); - input.composing = null; + var ranges = this.doc.sel.ranges, end = -1 + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i] + if (!range.empty()) { + var from = range.from(), to = range.to() + var start = Math.max(end, from.line) + end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1 + for (var j = start; j < end; ++j) + { indentLine(this$1, j, how) } + var newRanges = this$1.doc.sel.ranges + if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) + { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll) } + } else if (range.head.line > end) { + indentLine(this$1, range.head.line, how, true) + end = range.head.line + if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1) } } - }); - }, - - prepareSelection: function() { - // Redraw the selection and/or cursor - var cm = this.cm, display = cm.display, doc = cm.doc; - var result = prepareSelection(cm); - - // Move the hidden textarea near the cursor to prevent scrolling artifacts - if (cm.options.moveInputWithCursor) { - var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); - var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect(); - result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, - headPos.top + lineOff.top - wrapOff.top)); - result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, - headPos.left + lineOff.left - wrapOff.left)); } + }), - return result; + // Fetch the parser token for a given character. Useful for hacks + // that want to inspect the mode state (say, for completion). + getTokenAt: function(pos, precise) { + return takeToken(this, pos, precise) }, - showSelection: function(drawn) { - var cm = this.cm, display = cm.display; - removeChildrenAndAdd(display.cursorDiv, drawn.cursors); - removeChildrenAndAdd(display.selectionDiv, drawn.selection); - if (drawn.teTop != null) { - this.wrapper.style.top = drawn.teTop + "px"; - this.wrapper.style.left = drawn.teLeft + "px"; - } + getLineTokens: function(line, precise) { + return takeToken(this, Pos(line), precise, true) }, - // Reset the input to correspond to the selection (or to be empty, - // when not typing and nothing is selected) - reset: function(typing) { - if (this.contextMenuPending) return; - var minimal, selected, cm = this.cm, doc = cm.doc; - if (cm.somethingSelected()) { - this.prevInput = ""; - var range = doc.sel.primary(); - minimal = hasCopyEvent && - (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000); - var content = minimal ? "-" : selected || cm.getSelection(); - this.textarea.value = content; - if (cm.state.focused) selectInput(this.textarea); - if (ie && ie_version >= 9) this.hasSelection = content; - } else if (!typing) { - this.prevInput = this.textarea.value = ""; - if (ie && ie_version >= 9) this.hasSelection = null; - } - this.inaccurateSelection = minimal; + getTokenTypeAt: function(pos) { + pos = clipPos(this.doc, pos) + var styles = getLineStyles(this, getLine(this.doc, pos.line)) + var before = 0, after = (styles.length - 1) / 2, ch = pos.ch + var type + if (ch == 0) { type = styles[2] } + else { for (;;) { + var mid = (before + after) >> 1 + if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid } + else if (styles[mid * 2 + 1] < ch) { before = mid + 1 } + else { type = styles[mid * 2 + 2]; break } + } } + var cut = type ? type.indexOf("overlay ") : -1 + return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1) }, - getField: function() { return this.textarea; }, - - supportsTouch: function() { return false; }, - - focus: function() { - if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { - try { this.textarea.focus(); } - catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM - } + getModeAt: function(pos) { + var mode = this.doc.mode + if (!mode.innerMode) { return mode } + return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode }, - blur: function() { this.textarea.blur(); }, - - resetPosition: function() { - this.wrapper.style.top = this.wrapper.style.left = 0; + getHelper: function(pos, type) { + return this.getHelpers(pos, type)[0] }, - receivedFocus: function() { this.slowPoll(); }, - - // Poll for input changes, using the normal rate of polling. This - // runs as long as the editor is focused. - slowPoll: function() { - var input = this; - if (input.pollingFast) return; - input.polling.set(this.cm.options.pollInterval, function() { - input.poll(); - if (input.cm.state.focused) input.slowPoll(); - }); - }, + getHelpers: function(pos, type) { + var this$1 = this; - // When an event has just come in that is likely to add or change - // something in the input textarea, we poll faster, to ensure that - // the change appears on the screen quickly. - fastPoll: function() { - var missed = false, input = this; - input.pollingFast = true; - function p() { - var changed = input.poll(); - if (!changed && !missed) {missed = true; input.polling.set(60, p);} - else {input.pollingFast = false; input.slowPoll();} + var found = [] + if (!helpers.hasOwnProperty(type)) { return found } + var help = helpers[type], mode = this.getModeAt(pos) + if (typeof mode[type] == "string") { + if (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]] + if (val) { found.push(val) } + } + } else if (mode.helperType && help[mode.helperType]) { + found.push(help[mode.helperType]) + } else if (help[mode.name]) { + found.push(help[mode.name]) } - input.polling.set(20, p); - }, - - // Read input from the textarea, and update the document to match. - // When something is selected, it is present in the textarea, and - // selected (unless it is huge, in which case a placeholder is - // used). When nothing is selected, the cursor sits after previously - // seen text (can be empty), which is stored in prevInput (we must - // not reset the textarea when typing, because that breaks IME). - poll: function() { - var cm = this.cm, input = this.textarea, prevInput = this.prevInput; - // Since this is called a *lot*, try to bail out as cheaply as - // possible when it is clear that nothing happened. hasSelection - // will be the case when there is a lot of text in the textarea, - // in which case reading its value would be expensive. - if (this.contextMenuPending || !cm.state.focused || - (hasSelection(input) && !prevInput && !this.composing) || - cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) - return false; - - var text = input.value; - // If nothing changed, bail. - if (text == prevInput && !cm.somethingSelected()) return false; - // Work around nonsensical selection resetting in IE9/10, and - // inexplicable appearance of private area unicode characters on - // some key combos in Mac (#2689). - if (ie && ie_version >= 9 && this.hasSelection === text || - mac && /[\uf700-\uf7ff]/.test(text)) { - cm.display.input.reset(); - return false; + for (var i$1 = 0; i$1 < help._global.length; i$1++) { + var cur = help._global[i$1] + if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1) + { found.push(cur.val) } } + return found + }, - if (cm.doc.sel == cm.display.selForContextMenu) { - var first = text.charCodeAt(0); - if (first == 0x200b && !prevInput) prevInput = "\u200b"; - if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); } - } - // Find the part of the input that is actually new - var same = 0, l = Math.min(prevInput.length, text.length); - while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same; - - var self = this; - runInOp(cm, function() { - applyTextInput(cm, text.slice(same), prevInput.length - same, - null, self.composing ? "*compose" : null); - - // Don't leave long text in the textarea, since it makes further polling slow - if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = ""; - else self.prevInput = text; - - if (self.composing) { - self.composing.range.clear(); - self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"), - {className: "CodeMirror-composing"}); - } - }); - return true; + getStateAfter: function(line, precise) { + var doc = this.doc + line = clipLine(doc, line == null ? doc.first + doc.size - 1: line) + return getStateBefore(this, line + 1, precise) }, - ensurePolled: function() { - if (this.pollingFast && this.poll()) this.pollingFast = false; + cursorCoords: function(start, mode) { + var pos, range = this.doc.sel.primary() + if (start == null) { pos = range.head } + else if (typeof start == "object") { pos = clipPos(this.doc, start) } + else { pos = start ? range.from() : range.to() } + return cursorCoords(this, pos, mode || "page") }, - onKeyPress: function() { - if (ie && ie_version >= 9) this.hasSelection = null; - this.fastPoll(); + charCoords: function(pos, mode) { + return charCoords(this, clipPos(this.doc, pos), mode || "page") }, - onContextMenu: function(e) { - var input = this, cm = input.cm, display = cm.display, te = input.textarea; - var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; - if (!pos || presto) return; // Opera is difficult. - - // Reset the current text selection only if the click is done outside of the selection - // and 'resetSelectionOnContextMenu' option is true. - var reset = cm.options.resetSelectionOnContextMenu; - if (reset && cm.doc.sel.contains(pos) == -1) - operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); - - var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText; - input.wrapper.style.cssText = "position: absolute" - var wrapperBox = input.wrapper.getBoundingClientRect() - te.style.cssText = "position: absolute; width: 30px; height: 30px; top: " + (e.clientY - wrapperBox.top - 5) + - "px; left: " + (e.clientX - wrapperBox.left - 5) + "px; z-index: 1000; background: " + - (ie ? "rgba(255, 255, 255, .05)" : "transparent") + - "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; - if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712) - display.input.focus(); - if (webkit) window.scrollTo(null, oldScrollY); - display.input.reset(); - // Adds "Select all" to context menu in FF - if (!cm.somethingSelected()) te.value = input.prevInput = " "; - input.contextMenuPending = true; - display.selForContextMenu = cm.doc.sel; - clearTimeout(display.detectingSelectAll); - - // Select-all will be greyed out if there's nothing to select, so - // this adds a zero-width space so that we can later check whether - // it got selected. - function prepareSelectAllHack() { - if (te.selectionStart != null) { - var selected = cm.somethingSelected(); - var extval = "\u200b" + (selected ? te.value : ""); - te.value = "\u21da"; // Used to catch context-menu undo - te.value = extval; - input.prevInput = selected ? "" : "\u200b"; - te.selectionStart = 1; te.selectionEnd = extval.length; - // Re-set this, in case some other handler touched the - // selection in the meantime. - display.selForContextMenu = cm.doc.sel; - } - } - function rehide() { - input.contextMenuPending = false; - input.wrapper.style.cssText = oldWrapperCSS - te.style.cssText = oldCSS; - if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); - - // Try to detect the user choosing select-all - if (te.selectionStart != null) { - if (!ie || (ie && ie_version < 9)) prepareSelectAllHack(); - var i = 0, poll = function() { - if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && - te.selectionEnd > 0 && input.prevInput == "\u200b") - operation(cm, commands.selectAll)(cm); - else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500); - else display.input.reset(); - }; - display.detectingSelectAll = setTimeout(poll, 200); - } - } + coordsChar: function(coords, mode) { + coords = fromCoordSystem(this, coords, mode || "page") + return coordsChar(this, coords.left, coords.top) + }, - if (ie && ie_version >= 9) prepareSelectAllHack(); - if (captureRightClick) { - e_stop(e); - var mouseup = function() { - off(window, "mouseup", mouseup); - setTimeout(rehide, 20); - }; - on(window, "mouseup", mouseup); + lineAtHeight: function(height, mode) { + height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top + return lineAtHeight(this.doc, height + this.display.viewOffset) + }, + heightAtLine: function(line, mode) { + var end = false, lineObj + if (typeof line == "number") { + var last = this.doc.first + this.doc.size - 1 + if (line < this.doc.first) { line = this.doc.first } + else if (line > last) { line = last; end = true } + lineObj = getLine(this.doc, line) } else { - setTimeout(rehide, 50); + lineObj = line } + return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top + + (end ? this.doc.height - heightAtLine(lineObj) : 0) }, - readOnlyChanged: function(val) { - if (!val) this.reset(); - }, + defaultTextHeight: function() { return textHeight(this.display) }, + defaultCharWidth: function() { return charWidth(this.display) }, - setUneditable: nothing, + setGutterMarker: methodOp(function(line, gutterID, value) { + return changeLine(this.doc, line, "gutter", function (line) { + var markers = line.gutterMarkers || (line.gutterMarkers = {}) + markers[gutterID] = value + if (!value && isEmpty(markers)) { line.gutterMarkers = null } + return true + }) + }), - needsContentAttribute: false - }, TextareaInput.prototype); - - // CONTENTEDITABLE INPUT STYLE - - function ContentEditableInput(cm) { - this.cm = cm; - this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null; - this.polling = new Delayed(); - this.gracePeriod = false; - } - - ContentEditableInput.prototype = copyObj({ - init: function(display) { - var input = this, cm = input.cm; - var div = input.div = display.lineDiv; - disableBrowserMagic(div, cm.options.spellcheck); + clearGutter: methodOp(function(gutterID) { + var this$1 = this; - on(div, "paste", function(e) { - if (signalDOMEvent(cm, e) || handlePaste(e, cm)) return - // IE doesn't fire input events, so we schedule a read for the pasted content in this way - if (ie_version <= 11) setTimeout(operation(cm, function() { - if (!input.pollContent()) regChange(cm); - }), 20) + var doc = this.doc, i = doc.first + doc.iter(function (line) { + if (line.gutterMarkers && line.gutterMarkers[gutterID]) { + line.gutterMarkers[gutterID] = null + regLineChange(this$1, i, "gutter") + if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null } + } + ++i }) + }), - on(div, "compositionstart", function(e) { - var data = e.data; - input.composing = {sel: cm.doc.sel, data: data, startData: data}; - if (!data) return; - var prim = cm.doc.sel.primary(); - var line = cm.getLine(prim.head.line); - var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length)); - if (found > -1 && found <= prim.head.ch) - input.composing.sel = simpleSelection(Pos(prim.head.line, found), - Pos(prim.head.line, found + data.length)); - }); - on(div, "compositionupdate", function(e) { - input.composing.data = e.data; - }); - on(div, "compositionend", function(e) { - var ours = input.composing; - if (!ours) return; - if (e.data != ours.startData && !/\u200b/.test(e.data)) - ours.data = e.data; - // Need a small delay to prevent other code (input event, - // selection polling) from doing damage when fired right after - // compositionend. - setTimeout(function() { - if (!ours.handled) - input.applyComposition(ours); - if (input.composing == ours) - input.composing = null; - }, 50); - }); - - on(div, "touchstart", function() { - input.forceCompositionEnd(); - }); - - on(div, "input", function() { - if (input.composing) return; - if (cm.isReadOnly() || !input.pollContent()) - runInOp(input.cm, function() {regChange(cm);}); - }); - - function onCopyCut(e) { - if (signalDOMEvent(cm, e)) return - if (cm.somethingSelected()) { - lastCopied = {lineWise: false, text: cm.getSelections()}; - if (e.type == "cut") cm.replaceSelection("", null, "cut"); - } else if (!cm.options.lineWiseCopyCut) { - return; - } else { - var ranges = copyableRanges(cm); - lastCopied = {lineWise: true, text: ranges.text}; - if (e.type == "cut") { - 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") - // iOS exposes the clipboard API, but seems to discard content inserted into it - e.clipboardData.setData("Text", content); - if (e.clipboardData.getData("Text") == content) { - e.preventDefault(); - return - } - } - // Old-fashioned briefly-focus-a-textarea hack - var kludge = hiddenTextarea(), te = kludge.firstChild; - cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild); - te.value = lastCopied.text.join("\n"); - var hadFocus = document.activeElement; - selectInput(te); - setTimeout(function() { - cm.display.lineSpace.removeChild(kludge); - hadFocus.focus(); - if (hadFocus == div) input.showPrimarySelection() - }, 50); + lineInfo: function(line) { + var n + if (typeof line == "number") { + if (!isLine(this.doc, line)) { return null } + n = line + line = getLine(this.doc, line) + if (!line) { return null } + } else { + n = lineNo(line) + if (n == null) { return null } } - on(div, "copy", onCopyCut); - on(div, "cut", onCopyCut); - }, - - prepareSelection: function() { - var result = prepareSelection(this.cm, false); - result.focus = this.cm.state.focused; - return result; + return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, + textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, + widgets: line.widgets} }, - showSelection: function(info, takeFocus) { - if (!info || !this.cm.display.view.length) return; - if (info.focus || takeFocus) this.showPrimarySelection(); - this.showMultipleSelections(info); - }, + getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}}, - showPrimarySelection: function() { - var sel = window.getSelection(), prim = this.cm.doc.sel.primary(); - var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset); - var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset); - if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && - cmp(minPos(curAnchor, curFocus), prim.from()) == 0 && - cmp(maxPos(curAnchor, curFocus), prim.to()) == 0) - return; - - var start = posToDOM(this.cm, prim.from()); - var end = posToDOM(this.cm, prim.to()); - if (!start && !end) return; - - var view = this.cm.display.view; - var old = sel.rangeCount && sel.getRangeAt(0); - if (!start) { - start = {node: view[0].measure.map[2], offset: 0}; - } else if (!end) { // FIXME dangerously hacky - var measure = view[view.length - 1].measure; - var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map; - end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]}; + addWidget: function(pos, node, scroll, vert, horiz) { + var display = this.display + pos = cursorCoords(this, clipPos(this.doc, pos)) + var top = pos.bottom, left = pos.left + node.style.position = "absolute" + node.setAttribute("cm-ignore-events", "true") + this.display.input.setUneditable(node) + display.sizer.appendChild(node) + if (vert == "over") { + top = pos.top + } else if (vert == "above" || vert == "near") { + var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), + hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth) + // Default to positioning above (if specified and possible); otherwise default to positioning below + if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) + { top = pos.top - node.offsetHeight } + else if (pos.bottom + node.offsetHeight <= vspace) + { top = pos.bottom } + if (left + node.offsetWidth > hspace) + { left = hspace - node.offsetWidth } } - - try { var rng = range(start.node, start.offset, end.offset, end.node); } - catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible - if (rng) { - if (!gecko && this.cm.state.focused) { - sel.collapse(start.node, start.offset); - if (!rng.collapsed) sel.addRange(rng); - } else { - sel.removeAllRanges(); - sel.addRange(rng); - } - if (old && sel.anchorNode == null) sel.addRange(old); - else if (gecko) this.startGracePeriod(); + node.style.top = top + "px" + node.style.left = node.style.right = "" + if (horiz == "right") { + left = display.sizer.clientWidth - node.offsetWidth + node.style.right = "0px" + } else { + if (horiz == "left") { left = 0 } + else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2 } + node.style.left = left + "px" } - this.rememberSelection(); + if (scroll) + { scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight) } }, - startGracePeriod: function() { - var input = this; - clearTimeout(this.gracePeriod); - this.gracePeriod = setTimeout(function() { - input.gracePeriod = false; - if (input.selectionChanged()) - input.cm.operation(function() { input.cm.curOp.selectionChanged = true; }); - }, 20); - }, + triggerOnKeyDown: methodOp(onKeyDown), + triggerOnKeyPress: methodOp(onKeyPress), + triggerOnKeyUp: onKeyUp, - showMultipleSelections: function(info) { - removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); - removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection); + execCommand: function(cmd) { + if (commands.hasOwnProperty(cmd)) + { return commands[cmd].call(null, this) } }, - rememberSelection: function() { - var sel = window.getSelection(); - this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset; - this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset; - }, + triggerElectric: methodOp(function(text) { triggerElectric(this, text) }), - selectionInEditor: function() { - var sel = window.getSelection(); - if (!sel.rangeCount) return false; - var node = sel.getRangeAt(0).commonAncestorContainer; - return contains(this.div, node); - }, + findPosH: function(from, amount, unit, visually) { + var this$1 = this; - focus: function() { - if (this.cm.options.readOnly != "nocursor") this.div.focus(); + var dir = 1 + if (amount < 0) { dir = -1; amount = -amount } + var cur = clipPos(this.doc, from) + for (var i = 0; i < amount; ++i) { + cur = findPosH(this$1.doc, cur, dir, unit, visually) + if (cur.hitSide) { break } + } + return cur }, - blur: function() { this.div.blur(); }, - getField: function() { return this.div; }, - - supportsTouch: function() { return true; }, - receivedFocus: function() { - var input = this; - if (this.selectionInEditor()) - this.pollSelection(); - else - runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; }); + moveH: methodOp(function(dir, unit) { + var this$1 = this; - function poll() { - if (input.cm.state.focused) { - input.pollSelection(); - input.polling.set(input.cm.options.pollInterval, poll); - } - } - this.polling.set(this.cm.options.pollInterval, poll); - }, + this.extendSelectionsBy(function (range) { + if (this$1.display.shift || this$1.doc.extend || range.empty()) + { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) } + else + { return dir < 0 ? range.from() : range.to() } + }, sel_move) + }), - selectionChanged: function() { - var sel = window.getSelection(); - return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || - sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset; - }, + deleteH: methodOp(function(dir, unit) { + var sel = this.doc.sel, doc = this.doc + if (sel.somethingSelected()) + { doc.replaceSelection("", null, "+delete") } + else + { deleteNearSelection(this, function (range) { + var other = findPosH(doc, range.head, dir, unit, false) + return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other} + }) } + }), - pollSelection: function() { - if (!this.composing && !this.gracePeriod && this.selectionChanged()) { - var sel = window.getSelection(), cm = this.cm; - this.rememberSelection(); - var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); - var head = domToPos(cm, sel.focusNode, sel.focusOffset); - if (anchor && head) runInOp(cm, function() { - setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll); - if (anchor.bad || head.bad) cm.curOp.selectionChanged = true; - }); - } + findPosV: function(from, amount, unit, goalColumn) { + var this$1 = this; + + var dir = 1, x = goalColumn + if (amount < 0) { dir = -1; amount = -amount } + var cur = clipPos(this.doc, from) + for (var i = 0; i < amount; ++i) { + var coords = cursorCoords(this$1, cur, "div") + if (x == null) { x = coords.left } + else { coords.left = x } + cur = findPosV(this$1, coords, dir, unit) + if (cur.hitSide) { break } + } + return cur }, - pollContent: function() { - var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary(); - var from = sel.from(), to = sel.to(); - if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false; - - var fromIndex; - if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { - var fromLine = lineNo(display.view[0].line); - var fromNode = display.view[0].node; - } else { - var fromLine = lineNo(display.view[fromIndex].line); - var fromNode = display.view[fromIndex - 1].node.nextSibling; - } - var toIndex = findViewIndex(cm, to.line); - if (toIndex == display.view.length - 1) { - var toLine = display.viewTo - 1; - var toNode = display.lineDiv.lastChild; - } else { - var toLine = lineNo(display.view[toIndex + 1].line) - 1; - var toNode = display.view[toIndex + 1].node.previousSibling; - } + moveV: methodOp(function(dir, unit) { + var this$1 = this; - var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)); - var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)); - while (newText.length > 1 && oldText.length > 1) { - if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; } - else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; } - else break; - } + var doc = this.doc, goals = [] + var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected() + doc.extendSelectionsBy(function (range) { + if (collapse) + { return dir < 0 ? range.from() : range.to() } + var headPos = cursorCoords(this$1, range.head, "div") + if (range.goalColumn != null) { headPos.left = range.goalColumn } + goals.push(headPos.left) + var pos = findPosV(this$1, headPos, dir, unit) + if (unit == "page" && range == doc.sel.primary()) + { addToScrollPos(this$1, null, charCoords(this$1, pos, "div").top - headPos.top) } + return pos + }, sel_move) + if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++) + { doc.sel.ranges[i].goalColumn = goals[i] } } + }), - var cutFront = 0, cutEnd = 0; - var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length); - while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) - ++cutFront; - var newBot = lst(newText), oldBot = lst(oldText); - var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), - oldBot.length - (oldText.length == 1 ? cutFront : 0)); - while (cutEnd < maxCutEnd && - newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) - ++cutEnd; - - newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd); - newText[0] = newText[0].slice(cutFront); - - var chFrom = Pos(fromLine, cutFront); - var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0); - if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { - replaceRange(cm.doc, newText, chFrom, chTo, "+input"); - return true; + // Find the word at the given position (as returned by coordsChar). + findWordAt: function(pos) { + var doc = this.doc, line = getLine(doc, pos.line).text + var start = pos.ch, end = pos.ch + if (line) { + var helper = this.getHelper(pos, "wordChars") + if ((pos.xRel < 0 || end == line.length) && start) { --start; } else { ++end } + var startChar = line.charAt(start) + var 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)); } + while (start > 0 && check(line.charAt(start - 1))) { --start } + while (end < line.length && check(line.charAt(end))) { ++end } } + return new Range(Pos(pos.line, start), Pos(pos.line, end)) }, - ensurePolled: function() { - this.forceCompositionEnd(); - }, - reset: function() { - this.forceCompositionEnd(); - }, - forceCompositionEnd: function() { - if (!this.composing || this.composing.handled) return; - this.applyComposition(this.composing); - this.composing.handled = true; - this.div.blur(); - this.div.focus(); - }, - applyComposition: function(composing) { - if (this.cm.isReadOnly()) - operation(this.cm, regChange)(this.cm) - else if (composing.data && composing.data != composing.startData) - operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel); - }, - - setUneditable: function(node) { - node.contentEditable = "false" - }, + toggleOverwrite: function(value) { + if (value != null && value == this.state.overwrite) { return } + if (this.state.overwrite = !this.state.overwrite) + { addClass(this.display.cursorDiv, "CodeMirror-overwrite") } + else + { rmClass(this.display.cursorDiv, "CodeMirror-overwrite") } - onKeyPress: function(e) { - e.preventDefault(); - if (!this.cm.isReadOnly()) - operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); + signal(this, "overwriteToggle", this, this.state.overwrite) }, + hasFocus: function() { return this.display.input.getField() == activeElt() }, + isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) }, - readOnlyChanged: function(val) { - this.div.contentEditable = String(val != "nocursor") + scrollTo: methodOp(function(x, y) { + if (x != null || y != null) { resolveScrollToPos(this) } + if (x != null) { this.curOp.scrollLeft = x } + if (y != null) { this.curOp.scrollTop = 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)} }, - onContextMenu: nothing, - resetPosition: nothing, - - needsContentAttribute: true - }, ContentEditableInput.prototype); - - function posToDOM(cm, pos) { - var view = findViewForLine(cm, pos.line); - if (!view || view.hidden) return null; - var line = getLine(cm.doc, pos.line); - var info = mapFromLineView(view, line, pos.line); - - var order = getOrder(line), side = "left"; - if (order) { - var partPos = getBidiPartAt(order, pos.ch); - side = partPos % 2 ? "right" : "left"; - } - var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); - result.offset = result.collapse == "right" ? result.end : result.start; - return result; - } - - function badPos(pos, bad) { if (bad) pos.bad = true; return pos; } - - function domToPos(cm, node, offset) { - var lineNode; - if (node == cm.display.lineDiv) { - lineNode = cm.display.lineDiv.childNodes[offset]; - if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true); - 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 locateNodeInLineView(lineView, node, offset); - } - } - - function locateNodeInLineView(lineView, node, offset) { - var wrapper = lineView.text.firstChild, bad = false; - if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true); - if (node == wrapper) { - bad = true; - node = wrapper.childNodes[offset]; - offset = 0; - if (!node) { - var line = lineView.rest ? lst(lineView.rest) : lineView.line; - return badPos(Pos(lineNo(line), line.text.length), bad); + scrollIntoView: methodOp(function(range, margin) { + if (range == null) { + range = {from: this.doc.sel.primary().head, to: null} + if (margin == null) { margin = this.options.cursorScrollMargin } + } else if (typeof range == "number") { + range = {from: Pos(range, 0), to: null} + } else if (range.from == null) { + range = {from: range, to: null} } - } + if (!range.to) { range.to = range.from } + range.margin = margin || 0 - var textNode = node.nodeType == 3 ? node : null, topNode = node; - if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { - textNode = node.firstChild; - if (offset) offset = textNode.nodeValue.length; - } - while (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++) { - var map = i < 0 ? measure.map : maps[i]; - for (var j = 0; j < map.length; j += 3) { - var curNode = map[j + 2]; - if (curNode == textNode || curNode == topNode) { - var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]); - var ch = map[j] + offset; - if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)]; - return Pos(line, ch); - } - } + if (range.from.line != null) { + resolveScrollToPos(this) + this.curOp.scrollToPos = range + } else { + var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left), + Math.min(range.from.top, range.to.top) - range.margin, + Math.max(range.from.right, range.to.right), + Math.max(range.from.bottom, range.to.bottom) + range.margin) + this.scrollTo(sPos.scrollLeft, sPos.scrollTop) } - } - var found = find(textNode, topNode, offset); - if (found) return badPos(found, bad); + }), - // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems - for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { - found = find(after, after.firstChild, 0); - if (found) - return badPos(Pos(found.line, found.ch - dist), bad); - else - dist += after.textContent.length; - } - for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) { - found = find(before, before.firstChild, -1); - if (found) - return badPos(Pos(found.line, found.ch + dist), bad); - else - dist += before.textContent.length; - } - } + setSize: methodOp(function(width, height) { + var this$1 = this; + + var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; } + if (width != null) { this.display.wrapper.style.width = interpret(width) } + if (height != null) { this.display.wrapper.style.height = interpret(height) } + if (this.options.lineWrapping) { clearLineMeasurementCache(this) } + var lineNo = 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 = true + signal(this, "refresh", this) + }), - function domTextBetween(cm, from, to, fromLine, toLine) { - var text = "", closing = false, lineSep = cm.doc.lineSeparator(); - function recognizeMarker(id) { return function(marker) { return marker.id == id; }; } - function walk(node) { - if (node.nodeType == 1) { - var cmText = node.getAttribute("cm-text"); - if (cmText != null) { - if (cmText == "") cmText = node.textContent.replace(/\u200b/g, ""); - text += cmText; - return; - } - var markerID = node.getAttribute("cm-marker"), range; - if (markerID) { - var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)); - if (found.length && (range = found[0].find())) - text += getBetween(cm.doc, range.from, range.to).join(lineSep); - return; - } - if (node.getAttribute("contenteditable") == "false") return; - for (var i = 0; i < node.childNodes.length; i++) - walk(node.childNodes[i]); - if (/^(pre|div|p)$/i.test(node.nodeName)) - closing = true; - } else if (node.nodeType == 3) { - var val = node.nodeValue; - if (!val) return; - if (closing) { - text += lineSep; - closing = false; - } - text += val; - } - } - for (;;) { - walk(from); - if (from == to) break; - from = from.nextSibling; - } - return text; - } + operation: function(f){return runInOp(this, f)}, - CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput}; + refresh: methodOp(function() { + var oldHeight = this.display.cachedTextHeight + regChange(this) + this.curOp.forceUpdate = true + clearCaches(this) + this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop) + updateGutterSpace(this) + if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5) + { estimateLineHeights(this) } + signal(this, "refresh", this) + }), - // SELECTION / CURSOR + swapDoc: methodOp(function(doc) { + var old = this.doc + old.cm = null + attachDoc(this, doc) + clearCaches(this) + this.display.input.reset() + this.scrollTo(doc.scrollLeft, doc.scrollTop) + this.curOp.forceScroll = true + signalLater(this, "swapDoc", this, old) + return old + }), - // Selection objects are immutable. A new one is created every time - // the selection changes. A selection is one or more non-overlapping - // (and non-touching) ranges, sorted, and an integer that indicates - // which one is the primary selection (the one that's scrolled into - // view, that getCursor returns, etc). - function Selection(ranges, primIndex) { - this.ranges = ranges; - this.primIndex = primIndex; + 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) - Selection.prototype = { - primary: function() { return this.ranges[this.primIndex]; }, - equals: function(other) { - if (other == this) return true; - if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false; - for (var i = 0; i < this.ranges.length; i++) { - var here = this.ranges[i], there = other.ranges[i]; - if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false; - } - return true; - }, - 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); - }, - somethingSelected: function() { - for (var i = 0; i < this.ranges.length; i++) - if (!this.ranges[i].empty()) return true; - return false; - }, - contains: function(pos, end) { - if (!end) end = pos; - for (var i = 0; i < this.ranges.length; i++) { - var range = this.ranges[i]; - if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) - return i; - } - return -1; - } - }; - - function Range(anchor, head) { - this.anchor = anchor; this.head = head; + CodeMirror.registerHelper = function(type, name, value) { + if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []} } + helpers[type][name] = value } - - Range.prototype = { - from: function() { return minPos(this.anchor, this.head); }, - to: function() { return maxPos(this.anchor, this.head); }, - empty: function() { - return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch; - } - }; - - // Take an unsorted, potentially overlapping set of ranges, and - // build a selection out of it. 'Consumes' ranges array (modifying - // it). - function normalizeSelection(ranges, primIndex) { - var prim = ranges[primIndex]; - ranges.sort(function(a, b) { return cmp(a.from(), b.from()); }); - primIndex = indexOf(ranges, prim); - for (var i = 1; i < ranges.length; i++) { - var cur = ranges[i], prev = ranges[i - 1]; - if (cmp(prev.to(), cur.from()) >= 0) { - var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()); - var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; - if (i <= primIndex) --primIndex; - ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)); + CodeMirror.registerGlobalHelper = function(type, name, predicate, value) { + CodeMirror.registerHelper(type, name, value) + helpers[type]._global.push({pred: predicate, val: value}) + } +} + +// Used for horizontal relative motion. Dir is -1 or 1 (left or +// right), unit can be "char", "column" (like char, but doesn't +// cross line boundaries), "word" (across next word), or "group" (to +// the start of next group of word or non-word-non-whitespace +// chars). The visually param controls whether, in right-to-left +// text, direction 1 means to move towards the next index in the +// string, or towards the character to the right of the current +// position. The resulting position will have a hitSide=true +// property if it reached the end of the document. +function findPosH(doc, pos, dir, unit, visually) { + var line = pos.line, ch = pos.ch, origDir = dir + var lineObj = getLine(doc, line) + function findNextLine() { + var l = line + dir + if (l < doc.first || l >= doc.first + doc.size) { return false } + line = l + return lineObj = getLine(doc, l) + } + function moveOnce(boundToLine) { + var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true) + if (next == null) { + if (!boundToLine && findNextLine()) { + if (visually) { ch = (dir < 0 ? lineRight : lineLeft)(lineObj) } + else { ch = dir < 0 ? lineObj.text.length : 0 } + } else { return false } + } else { ch = next } + return true + } + + if (unit == "char") { + moveOnce() + } else if (unit == "column") { + moveOnce(true) + } else if (unit == "word" || unit == "group") { + var sawType = null, group = unit == "group" + var helper = doc.cm && doc.cm.getHelper(pos, "wordChars") + for (var first = true;; first = false) { + if (dir < 0 && !moveOnce(!first)) { break } + var cur = lineObj.text.charAt(ch) || "\n" + var type = isWordChar(cur, helper) ? "w" + : group && cur == "\n" ? "n" + : !group || /\s/.test(cur) ? null + : "p" + if (group && !first && !type) { type = "s" } + if (sawType && sawType != type) { + if (dir < 0) {dir = 1; moveOnce()} + break + } + + if (type) { sawType = type } + if (dir > 0 && !moveOnce(!first)) { break } + } + } + var result = skipAtomic(doc, Pos(line, ch), pos, origDir, true) + if (!cmp(pos, result)) { result.hitSide = true } + return result +} + +// For relative vertical movement. Dir may be -1 or 1. Unit can be +// "page" or "line". The resulting position will have a hitSide=true +// property if it reached the end of the document. +function findPosV(cm, pos, dir, unit) { + var doc = cm.doc, x = pos.left, y + if (unit == "page") { + var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight) + var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3) + y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount + + } else if (unit == "line") { + y = dir > 0 ? pos.bottom + 3 : pos.top - 3 + } + var target + for (;;) { + target = coordsChar(cm, x, y) + if (!target.outside) { break } + if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break } + y += dir * 5 + } + return target +} + +// CONTENTEDITABLE INPUT STYLE + +function ContentEditableInput(cm) { + this.cm = cm + this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null + this.polling = new Delayed() + this.gracePeriod = false +} + +ContentEditableInput.prototype = copyObj({ + init: function(display) { + var input = this, cm = input.cm + var div = input.div = display.lineDiv + disableBrowserMagic(div, cm.options.spellcheck) + + on(div, "paste", function (e) { + if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } + // IE doesn't fire input events, so we schedule a read for the pasted content in this way + if (ie_version <= 11) { setTimeout(operation(cm, function () { + if (!input.pollContent()) { regChange(cm) } + }), 20) } + }) + + on(div, "compositionstart", function (e) { + var data = e.data + input.composing = {sel: cm.doc.sel, data: data, startData: data} + if (!data) { return } + var prim = cm.doc.sel.primary() + var line = cm.getLine(prim.head.line) + var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length)) + if (found > -1 && found <= prim.head.ch) + { input.composing.sel = simpleSelection(Pos(prim.head.line, found), + Pos(prim.head.line, found + data.length)) } + }) + on(div, "compositionupdate", function (e) { return input.composing.data = e.data; }) + on(div, "compositionend", function (e) { + var ours = input.composing + if (!ours) { return } + if (e.data != ours.startData && !/\u200b/.test(e.data)) + { ours.data = e.data } + // Need a small delay to prevent other code (input event, + // selection polling) from doing damage when fired right after + // compositionend. + setTimeout(function () { + if (!ours.handled) + { input.applyComposition(ours) } + if (input.composing == ours) + { input.composing = null } + }, 50) + }) + + on(div, "touchstart", function () { return input.forceCompositionEnd(); }) + + on(div, "input", function () { + if (input.composing) { return } + if (cm.isReadOnly() || !input.pollContent()) + { runInOp(input.cm, function () { return regChange(cm); }) } + }) + + function onCopyCut(e) { + if (signalDOMEvent(cm, e)) { return } + if (cm.somethingSelected()) { + setLastCopied({lineWise: false, text: cm.getSelections()}) + if (e.type == "cut") { cm.replaceSelection("", null, "cut") } + } else if (!cm.options.lineWiseCopyCut) { + return + } else { + var ranges = copyableRanges(cm) + setLastCopied({lineWise: true, text: ranges.text}) + if (e.type == "cut") { + cm.operation(function () { + cm.setSelections(ranges.ranges, 0, sel_dontScroll) + cm.replaceSelection("", null, "cut") + }) + } } - } - return new Selection(ranges, primIndex); - } - - function simpleSelection(anchor, head) { - return new Selection([new Range(anchor, head || anchor)], 0); - } - - // Most of the external API clips given positions to make sure they - // actually exist within the document. - function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));} - function clipPos(doc, pos) { - if (pos.line < doc.first) return Pos(doc.first, 0); - var last = doc.first + doc.size - 1; - if (pos.line > last) return Pos(last, getLine(doc, last).text.length); - return clipToLen(pos, getLine(doc, pos.line).text.length); - } - function clipToLen(pos, linelen) { - var ch = pos.ch; - if (ch == null || ch > linelen) return Pos(pos.line, linelen); - else if (ch < 0) return Pos(pos.line, 0); - else return pos; - } - function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;} - function clipPosArray(doc, array) { - for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]); - return out; - } - - // SELECTION UPDATES - - // The 'scroll' parameter given to many of these indicated whether - // the new cursor position should be scrolled into view after - // modifying the selection. - - // If shift is held or the extend flag is set, extends a range to - // include a given position (and optionally a second position). - // Otherwise, simply returns the range between the given positions. - // Used for cursor motion and such. - function extendRange(doc, range, head, other) { - if (doc.cm && doc.cm.display.shift || doc.extend) { - var anchor = range.anchor; - if (other) { - var posBefore = cmp(head, anchor) < 0; - if (posBefore != (cmp(other, anchor) < 0)) { - anchor = head; - head = other; - } else if (posBefore != (cmp(head, other) < 0)) { - head = other; + if (e.clipboardData) { + e.clipboardData.clearData() + var content = lastCopied.text.join("\n") + // iOS exposes the clipboard API, but seems to discard content inserted into it + e.clipboardData.setData("Text", content) + if (e.clipboardData.getData("Text") == content) { + e.preventDefault() + return } } - return new Range(anchor, head); + // Old-fashioned briefly-focus-a-textarea hack + var kludge = hiddenTextarea(), te = kludge.firstChild + cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild) + te.value = lastCopied.text.join("\n") + var hadFocus = document.activeElement + selectInput(te) + setTimeout(function () { + cm.display.lineSpace.removeChild(kludge) + hadFocus.focus() + if (hadFocus == div) { input.showPrimarySelection() } + }, 50) + } + on(div, "copy", onCopyCut) + on(div, "cut", onCopyCut) + }, + + prepareSelection: function() { + var result = prepareSelection(this.cm, false) + result.focus = this.cm.state.focused + return result + }, + + showSelection: function(info, takeFocus) { + if (!info || !this.cm.display.view.length) { return } + if (info.focus || takeFocus) { this.showPrimarySelection() } + this.showMultipleSelections(info) + }, + + showPrimarySelection: function() { + var sel = window.getSelection(), prim = this.cm.doc.sel.primary() + var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset) + var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset) + if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && + cmp(minPos(curAnchor, curFocus), prim.from()) == 0 && + cmp(maxPos(curAnchor, curFocus), prim.to()) == 0) + { return } + + var start = posToDOM(this.cm, prim.from()) + var end = posToDOM(this.cm, prim.to()) + if (!start && !end) { return } + + var view = this.cm.display.view + var old = sel.rangeCount && sel.getRangeAt(0) + if (!start) { + start = {node: view[0].measure.map[2], offset: 0} + } else if (!end) { // FIXME dangerously hacky + var measure = view[view.length - 1].measure + var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map + end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]} + } + + var rng + try { rng = range(start.node, start.offset, end.offset, end.node) } + catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible + if (rng) { + if (!gecko && this.cm.state.focused) { + sel.collapse(start.node, start.offset) + if (!rng.collapsed) { + sel.removeAllRanges() + sel.addRange(rng) + } + } else { + sel.removeAllRanges() + sel.addRange(rng) + } + if (old && sel.anchorNode == null) { sel.addRange(old) } + else if (gecko) { this.startGracePeriod() } + } + this.rememberSelection() + }, + + startGracePeriod: function() { + var this$1 = this; + + clearTimeout(this.gracePeriod) + this.gracePeriod = setTimeout(function () { + this$1.gracePeriod = false + if (this$1.selectionChanged()) + { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }) } + }, 20) + }, + + showMultipleSelections: function(info) { + removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors) + removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection) + }, + + rememberSelection: function() { + var sel = window.getSelection() + this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset + this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset + }, + + selectionInEditor: function() { + var sel = window.getSelection() + if (!sel.rangeCount) { return false } + var node = sel.getRangeAt(0).commonAncestorContainer + return contains(this.div, node) + }, + + focus: function() { + if (this.cm.options.readOnly != "nocursor") { this.div.focus() } + }, + blur: function() { this.div.blur() }, + getField: function() { return this.div }, + + supportsTouch: function() { return true }, + + receivedFocus: function() { + var input = this + if (this.selectionInEditor()) + { this.pollSelection() } + else + { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }) } + + function poll() { + if (input.cm.state.focused) { + input.pollSelection() + input.polling.set(input.cm.options.pollInterval, poll) + } + } + this.polling.set(this.cm.options.pollInterval, poll) + }, + + selectionChanged: function() { + var sel = window.getSelection() + return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || + sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset + }, + + pollSelection: function() { + if (!this.composing && !this.gracePeriod && this.selectionChanged()) { + var sel = window.getSelection(), cm = this.cm + this.rememberSelection() + var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset) + var head = domToPos(cm, sel.focusNode, sel.focusOffset) + if (anchor && head) { runInOp(cm, function () { + setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll) + if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true } + }) } + } + }, + + pollContent: function() { + var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary() + var from = sel.from(), to = sel.to() + if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false } + + var fromIndex, fromLine, fromNode + if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { + fromLine = lineNo(display.view[0].line) + fromNode = display.view[0].node } else { - return new Range(other || head, head); - } - } - - // Extend the primary selection range, discard the rest. - function extendSelection(doc, head, other, options) { - setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options); - } - - // Extend all selections (pos is an array of selections with length - // equal the number of selections) - function extendSelections(doc, heads, options) { - for (var out = [], i = 0; i < doc.sel.ranges.length; i++) - out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null); - var newSel = normalizeSelection(out, doc.sel.primIndex); - setSelection(doc, newSel, options); - } - - // Updates a single range in the selection. - function replaceOneSelection(doc, i, range, options) { - var ranges = doc.sel.ranges.slice(0); - ranges[i] = range; - setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options); - } - - // Reset the selection to a single range. - function setSimpleSelection(doc, anchor, head, options) { - setSelection(doc, simpleSelection(anchor, head), options); - } - - // Give beforeSelectionChange handlers a change to influence a - // selection update. - function filterSelectionChange(doc, sel, options) { - var obj = { - 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, obj); - if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj); - if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1); - else return sel; - } - - function setSelectionReplaceHistory(doc, sel, options) { - var done = doc.history.done, last = lst(done); - if (last && last.ranges) { - done[done.length - 1] = sel; - setSelectionNoUndo(doc, sel, options); + fromLine = lineNo(display.view[fromIndex].line) + fromNode = display.view[fromIndex - 1].node.nextSibling + } + var toIndex = findViewIndex(cm, to.line) + var toLine, toNode + if (toIndex == display.view.length - 1) { + toLine = display.viewTo - 1 + toNode = display.lineDiv.lastChild } else { - setSelection(doc, sel, options); - } - } - - // Set a new selection. - 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) { - if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) - sel = filterSelectionChange(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, true)); - - if (!(options && options.scroll === false) && doc.cm) - ensureCursorVisible(doc.cm); - } - - function setSelectionInner(doc, sel) { - if (sel.equals(doc.sel)) return; - - doc.sel = sel; - - if (doc.cm) { - doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true; - signalCursorActivity(doc.cm); - } - signalLater(doc, "cursorActivity", doc); - } - - // Verify that the selection does not partially select any atomic - // marked ranges. - function reCheckSelection(doc) { - setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll); - } - - // Return a selection that does not partially select any atomic - // ranges. - function skipAtomicInSelection(doc, sel, bias, mayClear) { - var out; - for (var i = 0; i < sel.ranges.length; i++) { - var range = sel.ranges[i]; - var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i]; - var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear); - var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear); - if (out || newAnchor != range.anchor || newHead != range.head) { - if (!out) out = sel.ranges.slice(0, i); - out[i] = new Range(newAnchor, newHead); - } - } - return out ? normalizeSelection(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; - if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) && - (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) { - if (mayClear) { - signal(m, "beforeCursorEnter"); - if (m.explicitlyCleared) { - if (!line.markedSpans) break; - else {--i; continue;} - } - } - if (!m.atomic) continue; - - if (oldPos) { - var near = m.find(dir < 0 ? 1 : -1), diff; - if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft) - near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); - if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) - return skipAtomicInner(doc, near, pos, dir, mayClear); + toLine = lineNo(display.view[toIndex + 1].line) - 1 + toNode = display.view[toIndex + 1].node.previousSibling + } + + var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)) + var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)) + while (newText.length > 1 && oldText.length > 1) { + if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine-- } + else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++ } + else { break } + } + + var cutFront = 0, cutEnd = 0 + var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length) + while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) + { ++cutFront } + var newBot = lst(newText), oldBot = lst(oldText) + var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), + oldBot.length - (oldText.length == 1 ? cutFront : 0)) + while (cutEnd < maxCutEnd && + newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) + { ++cutEnd } + + newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd) + newText[0] = newText[0].slice(cutFront) + + var chFrom = Pos(fromLine, cutFront) + var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0) + if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { + replaceRange(cm.doc, newText, chFrom, chTo, "+input") + return true + } + }, + + ensurePolled: function() { + this.forceCompositionEnd() + }, + reset: function() { + this.forceCompositionEnd() + }, + forceCompositionEnd: function() { + if (!this.composing || this.composing.handled) { return } + this.applyComposition(this.composing) + this.composing.handled = true + this.div.blur() + this.div.focus() + }, + applyComposition: function(composing) { + if (this.cm.isReadOnly()) + { operation(this.cm, regChange)(this.cm) } + else if (composing.data && composing.data != composing.startData) + { operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel) } + }, + + setUneditable: function(node) { + node.contentEditable = "false" + }, + + onKeyPress: function(e) { + e.preventDefault() + if (!this.cm.isReadOnly()) + { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0) } + }, + + readOnlyChanged: function(val) { + this.div.contentEditable = String(val != "nocursor") + }, + + onContextMenu: nothing, + resetPosition: nothing, + + needsContentAttribute: true + }, ContentEditableInput.prototype) + +function posToDOM(cm, pos) { + var view = findViewForLine(cm, pos.line) + if (!view || view.hidden) { return null } + var line = getLine(cm.doc, pos.line) + var info = mapFromLineView(view, line, pos.line) + + var order = getOrder(line), side = "left" + if (order) { + var partPos = getBidiPartAt(order, pos.ch) + side = partPos % 2 ? "right" : "left" + } + var result = nodeAndOffsetInLineMap(info.map, pos.ch, side) + result.offset = result.collapse == "right" ? result.end : result.start + return result +} + +function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos } + +function domTextBetween(cm, from, to, fromLine, toLine) { + var text = "", closing = false, lineSep = cm.doc.lineSeparator() + function recognizeMarker(id) { return function (marker) { return marker.id == id; } } + function walk(node) { + if (node.nodeType == 1) { + var cmText = node.getAttribute("cm-text") + if (cmText != null) { + if (cmText == "") { cmText = node.textContent.replace(/\u200b/g, "") } + text += cmText + return + } + var markerID = node.getAttribute("cm-marker"), range + if (markerID) { + var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)) + if (found.length && (range = found[0].find())) + { text += getBetween(cm.doc, range.from, range.to).join(lineSep) } + return + } + if (node.getAttribute("contenteditable") == "false") { return } + for (var i = 0; i < node.childNodes.length; i++) + { walk(node.childNodes[i]) } + if (/^(pre|div|p)$/i.test(node.nodeName)) + { closing = true } + } else if (node.nodeType == 3) { + var val = node.nodeValue + if (!val) { return } + if (closing) { + text += lineSep + closing = false + } + text += val + } + } + for (;;) { + walk(from) + if (from == to) { break } + from = from.nextSibling + } + return text +} + +function domToPos(cm, node, offset) { + var lineNode + if (node == cm.display.lineDiv) { + lineNode = cm.display.lineDiv.childNodes[offset] + if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) } + 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 locateNodeInLineView(lineView, node, offset) } + } +} + +function locateNodeInLineView(lineView, node, offset) { + var wrapper = lineView.text.firstChild, bad = false + if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) } + if (node == wrapper) { + bad = true + node = wrapper.childNodes[offset] + offset = 0 + if (!node) { + var line = lineView.rest ? lst(lineView.rest) : lineView.line + return badPos(Pos(lineNo(line), line.text.length), bad) + } + } + + var textNode = node.nodeType == 3 ? node : null, topNode = node + if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { + textNode = node.firstChild + if (offset) { offset = textNode.nodeValue.length } + } + while (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++) { + var map = i < 0 ? measure.map : maps[i] + for (var j = 0; j < map.length; j += 3) { + var curNode = map[j + 2] + if (curNode == textNode || curNode == topNode) { + var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]) + var ch = map[j] + offset + if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)] } + return Pos(line, ch) } - - var far = m.find(dir < 0 ? -1 : 1); - if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight) - far = movePos(doc, far, dir, far.line == pos.line ? line : null); - return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null; } } - return pos; - } - - // Ensure a given position is not inside an atomic range. - function skipAtomic(doc, pos, oldPos, bias, mayClear) { - var dir = bias || 1; - var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) || - (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) || - skipAtomicInner(doc, pos, oldPos, -dir, mayClear) || - (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true)); - if (!found) { - doc.cantEdit = true; - return Pos(doc.first, 0); - } - return found; - } - - function movePos(doc, pos, dir, line) { - if (dir < 0 && pos.ch == 0) { - if (pos.line > doc.first) return clipPos(doc, Pos(pos.line - 1)); - else return null; - } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) { - if (pos.line < doc.first + doc.size - 1) return Pos(pos.line + 1, 0); - else return null; - } else { - return new Pos(pos.line, pos.ch + dir); - } - } - - // SELECTION DRAWING - - function updateSelection(cm) { - cm.display.input.showSelection(cm.display.input.prepareSelection()); - } - - function prepareSelection(cm, primary) { - var doc = cm.doc, result = {}; - var curFragment = result.cursors = document.createDocumentFragment(); - var selFragment = result.selection = document.createDocumentFragment(); - - for (var i = 0; i < doc.sel.ranges.length; i++) { - if (primary === false && i == doc.sel.primIndex) continue; - var range = doc.sel.ranges[i]; - if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) continue; - var collapsed = range.empty(); - if (collapsed || cm.options.showCursorWhenSelecting) - drawSelectionCursor(cm, range.head, curFragment); - if (!collapsed) - drawSelectionRange(cm, range, selFragment); - } - return result; } + var found = find(textNode, topNode, offset) + if (found) { return badPos(found, bad) } - // Draws a cursor for the given range - function drawSelectionCursor(cm, head, output) { - var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine); - - var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")); - cursor.style.left = pos.left + "px"; - cursor.style.top = pos.top + "px"; - cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; - - if (pos.other) { - // Secondary cursor, shown when on a 'jump' in bi-directional text - var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")); - otherCursor.style.display = ""; - otherCursor.style.left = pos.other.left + "px"; - otherCursor.style.top = pos.other.top + "px"; - otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; - } + // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems + for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { + found = find(after, after.firstChild, 0) + if (found) + { return badPos(Pos(found.line, found.ch - dist), bad) } + else + { dist += after.textContent.length } } - - // Draws the given range as a highlighted selection - function drawSelectionRange(cm, range, output) { - var display = cm.display, doc = cm.doc; - var fragment = document.createDocumentFragment(); - var padding = paddingH(cm.display), leftSide = padding.left; - var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right; - - function add(left, top, width, bottom) { - if (top < 0) top = 0; - top = Math.round(top); - bottom = Math.round(bottom); - fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + - "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) + - "px; height: " + (bottom - top) + "px")); - } - - function drawForLine(line, fromArg, toArg) { - var lineObj = getLine(doc, line); - var lineLen = lineObj.text.length; - var start, end; - function coords(ch, bias) { - return charCoords(cm, Pos(line, ch), "div", lineObj, bias); - } - - iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) { - var leftPos = coords(from, "left"), rightPos, left, right; - if (from == to) { - rightPos = leftPos; - left = right = leftPos.left; - } else { - rightPos = coords(to - 1, "right"); - if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; } - left = leftPos.left; - right = rightPos.right; - } - if (fromArg == null && from == 0) left = leftSide; - if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part - add(left, leftPos.top, null, leftPos.bottom); - left = leftSide; - if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top); + for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) { + found = find(before, before.firstChild, -1) + if (found) + { return badPos(Pos(found.line, found.ch + dist$1), bad) } + else + { dist$1 += before.textContent.length } + } +} + +// TEXTAREA INPUT STYLE + +function TextareaInput(cm) { + this.cm = cm + // See input.poll and input.reset + this.prevInput = "" + + // Flag that indicates whether we expect input to appear real soon + // now (after some event like 'keypress' or 'input') and are + // polling intensively. + this.pollingFast = false + // Self-resetting timeout for the poller + this.polling = new Delayed() + // Tracks when input.reset has punted to just putting a short + // string into the textarea instead of the full selection. + this.inaccurateSelection = false + // Used to work around IE issue with selection being forgotten when focus moves away from textarea + this.hasSelection = false + this.composing = null +} + +TextareaInput.prototype = copyObj({ + init: function(display) { + var this$1 = this; + + var input = this, cm = this.cm + + // Wraps and hides input textarea + var div = this.wrapper = hiddenTextarea() + // The semihidden textarea that is focused when the editor is + // focused, and receives input. + var te = this.textarea = div.firstChild + display.wrapper.insertBefore(div, display.wrapper.firstChild) + + // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore) + if (ios) { te.style.width = "0px" } + + on(te, "input", function () { + if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null } + input.poll() + }) + + on(te, "paste", function (e) { + if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } + + cm.state.pasteIncoming = true + input.fastPoll() + }) + + function prepareCopyCut(e) { + if (signalDOMEvent(cm, e)) { return } + if (cm.somethingSelected()) { + setLastCopied({lineWise: false, text: cm.getSelections()}) + if (input.inaccurateSelection) { + input.prevInput = "" + input.inaccurateSelection = false + te.value = lastCopied.text.join("\n") + selectInput(te) } - if (toArg == null && to == lineLen) right = rightSide; - if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left) - start = leftPos; - if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right) - end = rightPos; - if (left < leftSide + 1) left = leftSide; - add(left, rightPos.top, right - left, rightPos.bottom); - }); - return {start: start, end: end}; - } - - var sFrom = range.from(), sTo = range.to(); - if (sFrom.line == sTo.line) { - drawForLine(sFrom.line, sFrom.ch, sTo.ch); - } else { - var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line); - var singleVLine = visualLine(fromLine) == visualLine(toLine); - var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; - var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; - if (singleVLine) { - if (leftEnd.top < rightStart.top - 2) { - add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); - add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); + } else if (!cm.options.lineWiseCopyCut) { + return + } else { + var ranges = copyableRanges(cm) + setLastCopied({lineWise: true, text: ranges.text}) + if (e.type == "cut") { + cm.setSelections(ranges.ranges, null, sel_dontScroll) } else { - add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); + input.prevInput = "" + te.value = ranges.text.join("\n") + selectInput(te) } } - if (leftEnd.bottom < rightStart.top) - add(leftSide, leftEnd.bottom, null, rightStart.top); - } - - output.appendChild(fragment); - } - - // Cursor-blinking - function restartBlink(cm) { - if (!cm.state.focused) return; - var display = cm.display; - clearInterval(display.blinker); - var on = true; - display.cursorDiv.style.visibility = ""; - if (cm.options.cursorBlinkRate > 0) - display.blinker = setInterval(function() { - display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; - }, cm.options.cursorBlinkRate); - else if (cm.options.cursorBlinkRate < 0) - display.cursorDiv.style.visibility = "hidden"; - } - - // HIGHLIGHT WORKER - - function startWorker(cm, time) { - if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo) - cm.state.highlight.set(time, bind(highlightWorker, cm)); - } - - function highlightWorker(cm) { - var doc = cm.doc; - if (doc.frontier < doc.first) doc.frontier = doc.first; - if (doc.frontier >= cm.display.viewTo) return; - var end = +new Date + cm.options.workTime; - var state = copyState(doc.mode, getStateBefore(cm, doc.frontier)); - var changedLines = []; - - doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) { - if (doc.frontier >= cm.display.viewFrom) { // Visible - var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength; - var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true); - line.styles = highlighted.styles; - var oldCls = line.styleClasses, newCls = highlighted.classes; - if (newCls) line.styleClasses = newCls; - else if (oldCls) line.styleClasses = null; - var ischange = !oldStyles || oldStyles.length != line.styles.length || - oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass); - for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i]; - if (ischange) changedLines.push(doc.frontier); - line.stateAfter = tooLong ? state : copyState(doc.mode, state); - } else { - if (line.text.length <= cm.options.maxHighlightLength) - processLine(cm, line.text, state); - line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null; - } - ++doc.frontier; - if (+new Date > end) { - startWorker(cm, cm.options.workDelay); - return true; - } - }); - if (changedLines.length) runInOp(cm, function() { - for (var i = 0; i < changedLines.length; i++) - regLineChange(cm, changedLines[i], "text"); - }); - } - - // Finds the line to start with when starting a parse. Tries to - // find a line with a stateAfter, so that it can start with a - // valid state. If that fails, it returns the line with the - // smallest indentation, which tends to need the least context to - // parse correctly. - function findStartLine(cm, n, precise) { - var minindent, minline, doc = cm.doc; - var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100); - for (var search = n; search > lim; --search) { - if (search <= doc.first) return doc.first; - var line = getLine(doc, search - 1); - if (line.stateAfter && (!precise || search <= doc.frontier)) return search; - var indented = countColumn(line.text, null, cm.options.tabSize); - if (minline == null || minindent > indented) { - minline = search - 1; - minindent = indented; - } + if (e.type == "cut") { cm.state.cutIncoming = true } + } + on(te, "cut", prepareCopyCut) + on(te, "copy", prepareCopyCut) + + on(display.scroller, "paste", function (e) { + if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return } + cm.state.pasteIncoming = true + input.focus() + }) + + // Prevent normal selection in the editor (we handle our own) + on(display.lineSpace, "selectstart", function (e) { + if (!eventInWidget(display, e)) { e_preventDefault(e) } + }) + + on(te, "compositionstart", function () { + var start = cm.getCursor("from") + if (input.composing) { input.composing.range.clear() } + input.composing = { + start: start, + range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"}) + } + }) + on(te, "compositionend", function () { + if (input.composing) { + input.poll() + input.composing.range.clear() + input.composing = null + } + }) + }, + + prepareSelection: function() { + // Redraw the selection and/or cursor + var cm = this.cm, display = cm.display, doc = cm.doc + var result = prepareSelection(cm) + + // Move the hidden textarea near the cursor to prevent scrolling artifacts + if (cm.options.moveInputWithCursor) { + var headPos = cursorCoords(cm, doc.sel.primary().head, "div") + var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect() + result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, + headPos.top + lineOff.top - wrapOff.top)) + result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, + headPos.left + lineOff.left - wrapOff.left)) } - return minline; - } - - function getStateBefore(cm, n, precise) { - var doc = cm.doc, display = cm.display; - if (!doc.mode.startState) return true; - var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter; - if (!state) state = startState(doc.mode); - else state = copyState(doc.mode, state); - doc.iter(pos, n, function(line) { - processLine(cm, line.text, state); - var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo; - line.stateAfter = save ? copyState(doc.mode, state) : null; - ++pos; - }); - if (precise) doc.frontier = pos; - return state; - } - - // POSITION MEASUREMENT - - function paddingTop(display) {return display.lineSpace.offsetTop;} - function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;} - function paddingH(display) { - if (display.cachedPaddingH) return display.cachedPaddingH; - var e = removeChildrenAndAdd(display.measure, elt("pre", "x")); - var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; - var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}; - if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data; - return data; - } - - 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; - } - - // Ensure the lineView.wrapping.heights array is populated. This is - // an array of bottom offsets for the lines that make up a drawn - // line. When lineWrapping is on, there might be more than one - // height. - function ensureLineHeights(cm, lineView, rect) { - var wrapping = cm.options.lineWrapping; - var curWidth = wrapping && displayWidth(cm); - if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { - var heights = lineView.measure.heights = []; - if (wrapping) { - lineView.measure.width = curWidth; - var rects = lineView.text.firstChild.getClientRects(); - for (var i = 0; i < rects.length - 1; i++) { - var cur = rects[i], next = rects[i + 1]; - if (Math.abs(cur.bottom - next.bottom) > 2) - heights.push((cur.bottom + next.top) / 2 - rect.top); + + return result + }, + + showSelection: function(drawn) { + var cm = this.cm, display = cm.display + removeChildrenAndAdd(display.cursorDiv, drawn.cursors) + removeChildrenAndAdd(display.selectionDiv, drawn.selection) + if (drawn.teTop != null) { + this.wrapper.style.top = drawn.teTop + "px" + this.wrapper.style.left = drawn.teLeft + "px" + } + }, + + // Reset the input to correspond to the selection (or to be empty, + // when not typing and nothing is selected) + reset: function(typing) { + if (this.contextMenuPending) { return } + var minimal, selected, cm = this.cm, doc = cm.doc + if (cm.somethingSelected()) { + this.prevInput = "" + var range = doc.sel.primary() + minimal = hasCopyEvent && + (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000) + var content = minimal ? "-" : selected || cm.getSelection() + this.textarea.value = content + if (cm.state.focused) { selectInput(this.textarea) } + if (ie && ie_version >= 9) { this.hasSelection = content } + } else if (!typing) { + this.prevInput = this.textarea.value = "" + if (ie && ie_version >= 9) { this.hasSelection = null } + } + this.inaccurateSelection = minimal + }, + + getField: function() { return this.textarea }, + + supportsTouch: function() { return false }, + + focus: function() { + if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { + try { this.textarea.focus() } + catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM + } + }, + + blur: function() { this.textarea.blur() }, + + resetPosition: function() { + this.wrapper.style.top = this.wrapper.style.left = 0 + }, + + receivedFocus: function() { this.slowPoll() }, + + // Poll for input changes, using the normal rate of polling. This + // runs as long as the editor is focused. + slowPoll: function() { + var this$1 = this; + + if (this.pollingFast) { return } + this.polling.set(this.cm.options.pollInterval, function () { + this$1.poll() + if (this$1.cm.state.focused) { this$1.slowPoll() } + }) + }, + + // When an event has just come in that is likely to add or change + // something in the input textarea, we poll faster, to ensure that + // the change appears on the screen quickly. + fastPoll: function() { + var missed = false, input = this + input.pollingFast = true + function p() { + var changed = input.poll() + if (!changed && !missed) {missed = true; input.polling.set(60, p)} + else {input.pollingFast = false; input.slowPoll()} + } + input.polling.set(20, p) + }, + + // Read input from the textarea, and update the document to match. + // When something is selected, it is present in the textarea, and + // selected (unless it is huge, in which case a placeholder is + // used). When nothing is selected, the cursor sits after previously + // seen text (can be empty), which is stored in prevInput (we must + // not reset the textarea when typing, because that breaks IME). + poll: function() { + var this$1 = this; + + var cm = this.cm, input = this.textarea, prevInput = this.prevInput + // Since this is called a *lot*, try to bail out as cheaply as + // possible when it is clear that nothing happened. hasSelection + // will be the case when there is a lot of text in the textarea, + // in which case reading its value would be expensive. + if (this.contextMenuPending || !cm.state.focused || + (hasSelection(input) && !prevInput && !this.composing) || + cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) + { return false } + + var text = input.value + // If nothing changed, bail. + if (text == prevInput && !cm.somethingSelected()) { return false } + // Work around nonsensical selection resetting in IE9/10, and + // inexplicable appearance of private area unicode characters on + // some key combos in Mac (#2689). + if (ie && ie_version >= 9 && this.hasSelection === text || + mac && /[\uf700-\uf7ff]/.test(text)) { + cm.display.input.reset() + return false + } + + if (cm.doc.sel == cm.display.selForContextMenu) { + var first = text.charCodeAt(0) + if (first == 0x200b && !prevInput) { prevInput = "\u200b" } + if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") } + } + // Find the part of the input that is actually new + var same = 0, l = Math.min(prevInput.length, text.length) + while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same } + + runInOp(cm, function () { + applyTextInput(cm, text.slice(same), prevInput.length - same, + null, this$1.composing ? "*compose" : null) + + // Don't leave long text in the textarea, since it makes further polling slow + if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = "" } + else { this$1.prevInput = text } + + if (this$1.composing) { + this$1.composing.range.clear() + this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"), + {className: "CodeMirror-composing"}) + } + }) + return true + }, + + ensurePolled: function() { + if (this.pollingFast && this.poll()) { this.pollingFast = false } + }, + + onKeyPress: function() { + if (ie && ie_version >= 9) { this.hasSelection = null } + this.fastPoll() + }, + + onContextMenu: function(e) { + var input = this, cm = input.cm, display = cm.display, te = input.textarea + var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop + if (!pos || presto) { return } // Opera is difficult. + + // Reset the current text selection only if the click is done outside of the selection + // and 'resetSelectionOnContextMenu' option is true. + var reset = cm.options.resetSelectionOnContextMenu + if (reset && cm.doc.sel.contains(pos) == -1) + { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll) } + + var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText + input.wrapper.style.cssText = "position: absolute" + var wrapperBox = input.wrapper.getBoundingClientRect() + te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.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);" + var oldScrollY + if (webkit) { oldScrollY = window.scrollY } // Work around Chrome issue (#2712) + display.input.focus() + if (webkit) { window.scrollTo(null, oldScrollY) } + display.input.reset() + // Adds "Select all" to context menu in FF + if (!cm.somethingSelected()) { te.value = input.prevInput = " " } + input.contextMenuPending = true + display.selForContextMenu = cm.doc.sel + clearTimeout(display.detectingSelectAll) + + // Select-all will be greyed out if there's nothing to select, so + // this adds a zero-width space so that we can later check whether + // it got selected. + function prepareSelectAllHack() { + if (te.selectionStart != null) { + var selected = cm.somethingSelected() + var extval = "\u200b" + (selected ? te.value : "") + te.value = "\u21da" // Used to catch context-menu undo + te.value = extval + input.prevInput = selected ? "" : "\u200b" + te.selectionStart = 1; te.selectionEnd = extval.length + // Re-set this, in case some other handler touched the + // selection in the meantime. + display.selForContextMenu = cm.doc.sel + } + } + function rehide() { + input.contextMenuPending = false + input.wrapper.style.cssText = oldWrapperCSS + te.style.cssText = oldCSS + if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos) } + + // Try to detect the user choosing select-all + if (te.selectionStart != null) { + if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack() } + var i = 0, poll = function () { + if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && + te.selectionEnd > 0 && input.prevInput == "\u200b") + { operation(cm, selectAll)(cm) } + else if (i++ < 10) { display.detectingSelectAll = setTimeout(poll, 500) } + else { display.input.reset() } } + display.detectingSelectAll = setTimeout(poll, 200) } - heights.push(rect.bottom - rect.top); - } - } - - // Find a line map (mapping character offsets to text nodes) and a - // measurement cache for the given line number. (A line view might - // contain multiple lines when collapsed ranges are present.) - 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 = 0; i < lineView.rest.length; i++) - if (lineNo(lineView.rest[i]) > lineN) - return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true}; - } - - // Render a line into the hidden node display.externalMeasured. Used - // when measurement is needed for a line that's not in the viewport. - function updateExternalMeasurement(cm, line) { - line = visualLine(line); - var lineN = lineNo(line); - var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); - view.lineN = lineN; - var built = view.built = buildLineContent(cm, view); - view.text = built.pre; - removeChildrenAndAdd(cm.display.lineMeasure, built.pre); - return view; - } - - // Get a {top, bottom, left, right} box (in line-local coordinates) - // for a given character. - function measureChar(cm, line, ch, bias) { - return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias); - } - - // Find a line view that corresponds to the given line number. - function findViewForLine(cm, lineN) { - if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) - return cm.display.view[findViewIndex(cm, lineN)]; - var ext = cm.display.externalMeasured; - if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) - return ext; - } - - // Measurement can be split in two steps, the set-up work that - // applies to the whole line, and the measurement of the actual - // character. Functions like coordsChar, that need to do a lot of - // measurements in a row, can thus ensure that the set-up work is - // only done once. - function prepareMeasureForLine(cm, line) { - var lineN = lineNo(line); - var view = findViewForLine(cm, lineN); - if (view && !view.text) { - view = null; - } else if (view && view.changes) { - updateLineForChanges(cm, view, lineN, getDimensions(cm)); - cm.curOp.forceUpdate = true; - } - if (!view) - view = updateExternalMeasurement(cm, line); - - var info = mapFromLineView(view, line, lineN); - return { - line: line, view: view, rect: null, - map: info.map, cache: info.cache, before: info.before, - hasHeights: false - }; - } - - // Given a prepared measurement object, measures the position of an - // actual character (or fetches it from the cache). - function measureCharPrepared(cm, prepared, ch, bias, varHeight) { - if (prepared.before) ch = -1; - var key = ch + (bias || ""), found; - if (prepared.cache.hasOwnProperty(key)) { - found = prepared.cache[key]; - } else { - if (!prepared.rect) - prepared.rect = prepared.view.text.getBoundingClientRect(); - if (!prepared.hasHeights) { - ensureLineHeights(cm, prepared.view, prepared.rect); - prepared.hasHeights = true; - } - found = measureCharInner(cm, prepared, ch, bias); - if (!found.bogus) prepared.cache[key] = found; - } - return {left: found.left, right: found.right, - top: varHeight ? found.rtop : found.top, - bottom: varHeight ? found.rbottom : found.bottom}; - } - - var nullRect = {left: 0, right: 0, top: 0, bottom: 0}; - - function nodeAndOffsetInLineMap(map, ch, bias) { - var node, start, end, collapse; - // First, search the line map for the text node corresponding to, - // or closest to, the target character. - for (var i = 0; i < map.length; i += 3) { - var mStart = map[i], mEnd = map[i + 1]; - if (ch < mStart) { - start = 0; end = 1; - collapse = "left"; - } else if (ch < mEnd) { - start = ch - mStart; - end = start + 1; - } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) { - end = mEnd - mStart; - start = end - 1; - if (ch >= mEnd) collapse = "right"; - } - if (start != null) { - node = map[i + 2]; - if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) - collapse = bias; - if (bias == "left" && start == 0) - while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) { - node = map[(i -= 3) + 2]; - collapse = "left"; - } - if (bias == "right" && start == mEnd - mStart) - while (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 getUsefulRect(rects, bias) { - var rect = nullRect - if (bias == "left") for (var i = 0; i < rects.length; i++) { - if ((rect = rects[i]).left != rect.right) break - } else for (var i = rects.length - 1; i >= 0; i--) { - if ((rect = rects[i]).left != rect.right) break } - return rect - } - - function measureCharInner(cm, prepared, ch, bias) { - var place = nodeAndOffsetInLineMap(prepared.map, ch, bias); - var node = place.node, start = place.start, end = place.end, collapse = place.collapse; - var rect; - if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates. - for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned - while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start; - while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end; - if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) - rect = node.parentNode.getBoundingClientRect(); - else - rect = getUsefulRect(range(node, start, end).getClientRects(), bias) - if (rect.left || rect.right || start == 0) break; - end = start; - start = start - 1; - collapse = "right"; - } - if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect); - } else { // If it is a widget, simply get the box for the whole widget. - if (start > 0) collapse = bias = "right"; - var rects; - if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) - rect = rects[bias == "right" ? rects.length - 1 : 0]; - else - rect = node.getBoundingClientRect(); - } - if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { - var rSpan = node.parentNode.getClientRects()[0]; - if (rSpan) - rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; - else - rect = nullRect; - } - - var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top; - var mid = (rtop + rbot) / 2; - var heights = prepared.view.measure.heights; - for (var i = 0; i < heights.length - 1; i++) - if (mid < heights[i]) break; - var top = i ? heights[i - 1] : 0, bot = heights[i]; - var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, - right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, - top: top, bottom: bot}; - if (!rect.left && !rect.right) result.bogus = true; - if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; } - - return result; - } - - // Work around problem with bounding client rects on ranges being - // returned incorrectly when zoomed on IE10 and below. - function maybeUpdateRectForZooming(measure, rect) { - if (!window.screen || screen.logicalXDPI == null || - screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) - return rect; - var scaleX = screen.logicalXDPI / screen.deviceXDPI; - var scaleY = screen.logicalYDPI / screen.deviceYDPI; - return {left: rect.left * scaleX, right: rect.right * scaleX, - top: rect.top * scaleY, bottom: rect.bottom * scaleY}; - } - - function clearLineMeasurementCacheFor(lineView) { - if (lineView.measure) { - lineView.measure.cache = {}; - lineView.measure.heights = null; - if (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; - if (!cm.options.lineWrapping) cm.display.maxLineChanged = true; - cm.display.lineNumChars = null; - } - - function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; } - function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; } - - // Converts a {top, bottom, left, right} box from line-local - // coordinates into another coordinate system. Context may be one of - // "line", "div" (display.lineDiv), "local"/null (editor), "window", - // or "page". - function intoCoordSystem(cm, lineObj, rect, context) { - if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) { - var size = widgetHeight(lineObj.widgets[i]); - rect.top += size; rect.bottom += size; - } - if (context == "line") return rect; - if (!context) context = "local"; - var yOff = heightAtLine(lineObj); - if (context == "local") yOff += paddingTop(cm.display); - else yOff -= cm.display.viewOffset; - if (context == "page" || context == "window") { - var lOff = cm.display.lineSpace.getBoundingClientRect(); - yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); - var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); - rect.left += xOff; rect.right += xOff; - } - rect.top += yOff; rect.bottom += yOff; - return rect; - } - - // Coverts a box from "div" coords to another coordinate system. - // Context may be "window", "page", "div", or "local"/null. - function fromCoordSystem(cm, coords, context) { - if (context == "div") return coords; - var left = coords.left, top = coords.top; - // First move into "page" coordinate system - if (context == "page") { - left -= pageScrollX(); - top -= pageScrollY(); - } else if (context == "local" || !context) { - var localBox = cm.display.sizer.getBoundingClientRect(); - left += localBox.left; - top += localBox.top; - } - - var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); - return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}; - } - - function charCoords(cm, pos, context, lineObj, bias) { - if (!lineObj) lineObj = getLine(cm.doc, pos.line); - return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context); - } - - // Returns a box for a given cursor position, which may have an - // 'other' property containing the position of the secondary cursor - // on a bidi boundary. - function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { - lineObj = lineObj || getLine(cm.doc, pos.line); - if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj); - function get(ch, right) { - var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight); - if (right) m.left = m.right; else m.right = m.left; - return intoCoordSystem(cm, lineObj, m, context); - } - function getBidi(ch, partPos) { - var part = order[partPos], right = part.level % 2; - if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) { - part = order[--partPos]; - ch = bidiRight(part) - (part.level % 2 ? 0 : 1); - right = true; - } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) { - part = order[++partPos]; - ch = bidiLeft(part) - part.level % 2; - right = false; + if (ie && ie_version >= 9) { prepareSelectAllHack() } + if (captureRightClick) { + e_stop(e) + var mouseup = function () { + off(window, "mouseup", mouseup) + setTimeout(rehide, 20) } - if (right && ch == part.to && ch > part.from) return get(ch - 1); - return get(ch, right); - } - var order = getOrder(lineObj), ch = pos.ch; - if (!order) return get(ch); - var partPos = getBidiPartAt(order, ch); - var val = getBidi(ch, partPos); - if (bidiOther != null) val.other = getBidi(ch, bidiOther); - return val; - } - - // Used to cheaply estimate the coordinates for a position. Used for - // intermediate scroll updates. - function estimateCoords(cm, pos) { - var left = 0, pos = clipPos(cm.doc, pos); - if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch; - var lineObj = getLine(cm.doc, pos.line); - var top = heightAtLine(lineObj) + paddingTop(cm.display); - return {left: left, right: left, top: top, bottom: top + lineObj.height}; - } - - // Positions returned by coordsChar contain some extra information. - // xRel is the relative x position of the input coordinates compared - // to the found position (so xRel > 0 means the coordinates are to - // the right of the character position, for example). When outside - // is true, that means the coordinates lie outside the line's - // vertical range. - function PosWithInfo(line, ch, outside, xRel) { - var pos = Pos(line, ch); - pos.xRel = xRel; - if (outside) pos.outside = true; - return pos; - } - - // Compute the character position closest to the given coordinates. - // Input must be lineSpace-local ("div" coordinate system). - function coordsChar(cm, x, y) { - var doc = cm.doc; - y += cm.display.viewOffset; - if (y < 0) return PosWithInfo(doc.first, 0, true, -1); - var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1; - if (lineN > last) - return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1); - if (x < 0) x = 0; - - var lineObj = getLine(doc, lineN); - for (;;) { - var found = coordsCharInner(cm, lineObj, lineN, x, y); - var merged = collapsedSpanAtEnd(lineObj); - var mergedPos = merged && merged.find(0, true); - if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0)) - lineN = lineNo(lineObj = mergedPos.to.line); - else - return found; - } - } - - function coordsCharInner(cm, lineObj, lineNo, x, y) { - var innerOff = y - heightAtLine(lineObj); - var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth; - var preparedMeasure = prepareMeasureForLine(cm, lineObj); - - function getX(ch) { - var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure); - wrongLine = true; - if (innerOff > sp.bottom) return sp.left - adjust; - else if (innerOff < sp.top) return sp.left + adjust; - else wrongLine = false; - return sp.left; - } - - var bidi = getOrder(lineObj), dist = lineObj.text.length; - var from = lineLeft(lineObj), to = lineRight(lineObj); - var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine; - - if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1); - // Do a binary search between these bounds. - for (;;) { - if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) { - var ch = x < fromX || x - fromX <= toX - x ? from : to; - var outside = ch == from ? fromOutside : toOutside - var xDiff = x - (ch == from ? fromX : toX); - // This is a kludge to handle the case where the coordinates - // are after a line-wrapped line. We should replace it with a - // more general handling of cursor positions around line - // breaks. (Issue #4078) - if (toOutside && !bidi && !/\s/.test(lineObj.text.charAt(ch)) && xDiff > 0 && - ch < lineObj.text.length && preparedMeasure.view.measure.heights.length > 1) { - var charSize = measureCharPrepared(cm, preparedMeasure, ch, "right"); - if (innerOff <= charSize.bottom && innerOff >= charSize.top && Math.abs(x - charSize.right) < xDiff) { - outside = false - ch++ - xDiff = x - charSize.right - } - } - while (isExtendingChar(lineObj.text.charAt(ch))) ++ch; - var pos = PosWithInfo(lineNo, ch, outside, xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0); - return pos; - } - var step = Math.ceil(dist / 2), middle = from + step; - if (bidi) { - middle = from; - for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1); - } - var middleX = getX(middle); - if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;} - else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;} - } - } - - var measureText; - // Compute the default text height. - function textHeight(display) { - if (display.cachedTextHeight != null) return display.cachedTextHeight; - if (measureText == null) { - measureText = elt("pre"); - // Measure a bunch of lines, for browsers that compute - // fractional heights. - 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; - if (height > 3) display.cachedTextHeight = height; - removeChildren(display.measure); - return height || 1; - } - - // Compute the default character width. - function charWidth(display) { - if (display.cachedCharWidth != null) return display.cachedCharWidth; - var anchor = elt("span", "xxxxxxxxxx"); - var pre = elt("pre", [anchor]); - removeChildrenAndAdd(display.measure, pre); - var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10; - if (width > 2) display.cachedCharWidth = width; - return width || 10; - } - - // OPERATIONS - - // Operations are used to wrap a series of changes to the editor - // state in such a way that each change won't have to update the - // cursor and display (which would be awkward, slow, and - // error-prone). Instead, display updates are batched and then all - // combined and executed at once. - - var operationGroup = null; - - var nextOpId = 0; - // Start a new operation. - function startOperation(cm) { - cm.curOp = { - cm: cm, - viewChanged: false, // Flag that indicates that lines might need to be redrawn - startHeight: cm.doc.height, // Used to detect need to update scrollbar - forceUpdate: false, // Used to force a redraw - updateInput: null, // Whether to reset the input textarea - typing: false, // Whether this reset should be careful to leave existing text (for compositing) - changeObjs: null, // Accumulated changes, for firing change events - cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on - cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already - selectionChanged: false, // Whether the selection needs to be redrawn - updateMaxLine: false, // Set when the widest line needs to be determined anew - scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet - scrollToPos: null, // Used to scroll to a specific position - focus: false, - id: ++nextOpId // Unique ID - }; - if (operationGroup) { - operationGroup.ops.push(cm.curOp); - } else { - cm.curOp.ownsGroup = operationGroup = { - ops: [cm.curOp], - delayedCallbacks: [] - }; - } - } - - function fireCallbacksForOps(group) { - // Calls delayed callbacks and cursorActivity handlers until no - // new ones appear - 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) - while (op.cursorActivityCalled < op.cursorActivityHandlers.length) - op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); - } - } while (i < callbacks.length); - } - - // Finish an operation, updating the display and signalling delayed events - function endOperation(cm) { - var op = cm.curOp, group = op.ownsGroup; - if (!group) return; - - try { fireCallbacksForOps(group); } - finally { - operationGroup = null; - for (var i = 0; i < group.ops.length; i++) - group.ops[i].cm.curOp = null; - endOperations(group); - } - } - - // The DOM updates done when an operation finishes are batched so - // that the minimum number of relayouts are required. - function endOperations(group) { - var ops = group.ops; - for (var i = 0; i < ops.length; i++) // Read DOM - endOperation_R1(ops[i]); - for (var i = 0; i < ops.length; i++) // Write DOM (maybe) - endOperation_W1(ops[i]); - for (var i = 0; i < ops.length; i++) // Read DOM - endOperation_R2(ops[i]); - for (var i = 0; i < ops.length; i++) // Write DOM (maybe) - endOperation_W2(ops[i]); - for (var i = 0; i < ops.length; i++) // Read DOM - endOperation_finish(ops[i]); - } - - function endOperation_R1(op) { - var cm = op.cm, display = cm.display; - maybeClipScrollbars(cm); - if (op.updateMaxLine) findMaxLine(cm); - - op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || - 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); - } - - function endOperation_W1(op) { - op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); - } - - function endOperation_R2(op) { - var cm = op.cm, display = cm.display; - if (op.updatedDisplay) updateHeightsInViewport(cm); - - op.barMeasure = measureForScrollbars(cm); - - // If the max line changed since it was last measured, measure it, - // and ensure the document's width matches it. - // updateDisplay_W2 will use these properties to do the actual resizing - if (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)); - } - - if (op.updatedDisplay || op.selectionChanged) - op.preparedSelection = display.input.prepareSelection(op.focus); - } - - function endOperation_W2(op) { - var cm = op.cm; - - if (op.adjustWidthTo != null) { - cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; - if (op.maxScrollLeft < cm.doc.scrollLeft) - setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); - cm.display.maxLineChanged = false; - } - - var takeFocus = op.focus && op.focus == activeElt() && (!document.hasFocus || document.hasFocus()) - if (op.preparedSelection) - cm.display.input.showSelection(op.preparedSelection, takeFocus); - if (op.updatedDisplay || op.startHeight != cm.doc.height) - updateScrollbars(cm, op.barMeasure); - if (op.updatedDisplay) - setDocumentHeight(cm, op.barMeasure); - - if (op.selectionChanged) restartBlink(cm); - - if (cm.state.focused && op.updateInput) - cm.display.input.reset(op.typing); - if (takeFocus) ensureFocus(op.cm); - } - - function endOperation_finish(op) { - var cm = op.cm, display = cm.display, doc = cm.doc; - - if (op.updatedDisplay) postUpdateDisplay(cm, op.update); - - // Abort mouse wheel delta measurement, when scrolling explicitly - if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) - display.wheelStartX = display.wheelStartY = null; - - // Propagate the scroll position to the actual DOM scroller - if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) { - doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop)); - display.scrollbars.setScrollTop(doc.scrollTop); - display.scroller.scrollTop = doc.scrollTop; - } - if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) { - doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft)); - display.scrollbars.setScrollLeft(doc.scrollLeft); - display.scroller.scrollLeft = doc.scrollLeft; - alignHorizontally(cm); - } - // If we need to scroll a specific position into view, do so. - if (op.scrollToPos) { - var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), - clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin); - if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords); - } - - // Fire events for markers that are hidden/unidden by editing or - // undoing - var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; - if (hidden) for (var i = 0; i < hidden.length; ++i) - if (!hidden[i].lines.length) signal(hidden[i], "hide"); - if (unhidden) for (var i = 0; i < unhidden.length; ++i) - if (unhidden[i].lines.length) signal(unhidden[i], "unhide"); - - if (display.wrapper.offsetHeight) - doc.scrollTop = cm.display.scroller.scrollTop; - - // Fire change events, and delayed event handlers - if (op.changeObjs) - signal(cm, "changes", cm, op.changeObjs); - if (op.update) - op.update.finish(); - } - - // Run the given function in an operation - function runInOp(cm, f) { - if (cm.curOp) return f(); - startOperation(cm); - try { return f(); } - finally { endOperation(cm); } - } - // Wraps a function in an operation. Returns the wrapped function. - 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); } - }; - } - // Used to add methods to editor and doc instances, wrapping them in - // operations. - 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); } - }; - } - - // VIEW TRACKING - - // These objects are used to represent the visible (currently drawn) - // part of the document. A LineView may correspond to multiple - // logical lines, if those are connected by collapsed ranges. - function LineView(doc, line, lineN) { - // The starting line - this.line = line; - // Continuing lines, if any - this.rest = visualLineContinued(line); - // Number of logical lines in this visual line - this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; - this.node = this.text = null; - this.hidden = lineIsHidden(doc, line); - } - - // Create a range of LineView objects for the given lines. - function buildViewArray(cm, from, to) { - var array = [], nextPos; - for (var 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; - } - - // Updates the display.view data structure for a given change to the - // document. From and to are in pre-change coordinates. Lendiff is - // the amount of lines added or subtracted by the change. This is - // used for changes that span multiple lines, or change the way - // lines are divided into visual lines. regLineChange (below) - // registers single-line changes. - function regChange(cm, from, to, lendiff) { - if (from == null) from = cm.doc.first; - if (to == null) to = cm.doc.first + cm.doc.size; - if (!lendiff) lendiff = 0; - - var display = cm.display; - if (lendiff && to < display.viewTo && - (display.updateLineNumbers == null || display.updateLineNumbers > from)) - display.updateLineNumbers = from; - - cm.curOp.viewChanged = true; - - if (from >= display.viewTo) { // Change after - if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) - resetView(cm); - } else if (to <= display.viewFrom) { // Change before - if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { - resetView(cm); - } else { - display.viewFrom += lendiff; - display.viewTo += lendiff; - } - } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap - resetView(cm); - } else if (from <= display.viewFrom) { // Top overlap - var cut = viewCuttingPoint(cm, to, to + lendiff, 1); - if (cut) { - display.view = display.view.slice(cut.index); - display.viewFrom = cut.lineN; - display.viewTo += lendiff; - } else { - resetView(cm); - } - } else if (to >= display.viewTo) { // Bottom overlap - var cut = viewCuttingPoint(cm, from, from, -1); - if (cut) { - display.view = display.view.slice(0, cut.index); - display.viewTo = cut.lineN; - } else { - resetView(cm); - } - } else { // Gap in the middle - var cutTop = viewCuttingPoint(cm, from, from, -1); - var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); - if (cutTop && cutBot) { - display.view = display.view.slice(0, cutTop.index) - .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) - .concat(display.view.slice(cutBot.index)); - display.viewTo += lendiff; - } else { - resetView(cm); - } - } - - var ext = display.externalMeasured; - if (ext) { - if (to < ext.lineN) - ext.lineN += lendiff; - else if (from < ext.lineN + ext.size) - display.externalMeasured = null; - } - } - - // Register a change to a single line. Type must be one of "text", - // "gutter", "class", "widget" - function regLineChange(cm, line, type) { - cm.curOp.viewChanged = true; - var display = cm.display, ext = cm.display.externalMeasured; - if (ext && line >= ext.lineN && line < ext.lineN + ext.size) - display.externalMeasured = null; - - if (line < display.viewFrom || line >= display.viewTo) return; - var lineView = display.view[findViewIndex(cm, line)]; - if (lineView.node == null) return; - var arr = lineView.changes || (lineView.changes = []); - if (indexOf(arr, type) == -1) arr.push(type); - } - - // Clear the view. - function resetView(cm) { - cm.display.viewFrom = cm.display.viewTo = cm.doc.first; - cm.display.view = []; - cm.display.viewOffset = 0; - } - - // Find the view element corresponding to a given line. Return null - // when the line isn't visible. - function findViewIndex(cm, n) { - if (n >= cm.display.viewTo) return null; - n -= cm.display.viewFrom; - if (n < 0) return null; - var view = cm.display.view; - for (var i = 0; i < view.length; i++) { - n -= view[i].size; - if (n < 0) return i; - } - } - - function viewCuttingPoint(cm, oldN, newN, dir) { - var index = findViewIndex(cm, oldN), diff, view = cm.display.view; - if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) - return {index: index, lineN: newN}; - for (var i = 0, n = cm.display.viewFrom; i < index; i++) - n += view[i].size; - if (n != oldN) { - if (dir > 0) { - if (index == view.length - 1) return null; - diff = (n + view[index].size) - oldN; - index++; - } else { - diff = n - oldN; - } - oldN += diff; newN += diff; - } - while (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}; - } - - // Force the view to cover a given range, adding empty view element - // or clipping off existing ones as needed. - function adjustView(cm, from, to) { - var display = cm.display, view = display.view; - if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { - display.view = buildViewArray(cm, from, to); - display.viewFrom = from; - } else { - if (display.viewFrom > from) - display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); - else if (display.viewFrom < from) - display.view = display.view.slice(findViewIndex(cm, from)); - display.viewFrom = from; - if (display.viewTo < to) - display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); - else if (display.viewTo > to) - display.view = display.view.slice(0, findViewIndex(cm, to)); - } - display.viewTo = to; - } - - // Count the number of lines in the view whose DOM representation is - // out of date (or nonexistent). - function countDirtyView(cm) { - var view = cm.display.view, dirty = 0; - for (var i = 0; i < view.length; i++) { - var lineView = view[i]; - if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty; - } - return dirty; - } - - // EVENT HANDLERS - - // Attach the necessary event handlers when initializing the editor - function registerEventHandlers(cm) { - var d = cm.display; - on(d.scroller, "mousedown", operation(cm, onMouseDown)); - // Older IE's will not fire a second mousedown for a double click - if (ie && ie_version < 11) - on(d.scroller, "dblclick", operation(cm, function(e) { - if (signalDOMEvent(cm, e)) return; - var pos = posFromMouse(cm, e); - if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return; - e_preventDefault(e); - var word = cm.findWordAt(pos); - extendSelection(cm.doc, word.anchor, word.head); - })); - else - on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); }); - // Some browsers fire contextmenu *after* opening the menu, at - // which point we can't mess with it anymore. Context menu is - // handled in onMouseDown for these browsers. - if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);}); - - // Used to suppress mouse event handling when a touch happens - var touchFinished, prevTouch = {end: 0}; - function finishTouch() { - if (d.activeTouch) { - touchFinished = setTimeout(function() {d.activeTouch = null;}, 1000); - prevTouch = d.activeTouch; - prevTouch.end = +new Date; - } - }; - function isMouseLikeTouchEvent(e) { - if (e.touches.length != 1) return false; - var touch = e.touches[0]; - return touch.radiusX <= 1 && touch.radiusY <= 1; - } - function farAway(touch, other) { - if (other.left == null) return true; - var dx = other.left - touch.left, dy = other.top - touch.top; - return dx * dx + dy * dy > 20 * 20; - } - on(d.scroller, "touchstart", function(e) { - if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e)) { - clearTimeout(touchFinished); - var now = +new Date; - d.activeTouch = {start: now, moved: false, - prev: now - prevTouch.end <= 300 ? prevTouch : null}; - if (e.touches.length == 1) { - d.activeTouch.left = e.touches[0].pageX; - d.activeTouch.top = e.touches[0].pageY; - } - } - }); - on(d.scroller, "touchmove", function() { - if (d.activeTouch) d.activeTouch.moved = true; - }); - on(d.scroller, "touchend", function(e) { - var touch = d.activeTouch; - if (touch && !eventInWidget(d, e) && touch.left != null && - !touch.moved && new Date - touch.start < 300) { - var pos = cm.coordsChar(d.activeTouch, "page"), range; - if (!touch.prev || farAway(touch, touch.prev)) // Single tap - range = new Range(pos, pos); - else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap - range = cm.findWordAt(pos); - else // Triple tap - range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); - cm.setSelection(range.anchor, range.head); - cm.focus(); - e_preventDefault(e); - } - finishTouch(); - }); - on(d.scroller, "touchcancel", finishTouch); - - // Sync scrolling between fake scrollbars and real scrollable - // area, ensure viewport is updated when scrolling. - on(d.scroller, "scroll", function() { - if (d.scroller.clientHeight) { - setScrollTop(cm, d.scroller.scrollTop); - setScrollLeft(cm, d.scroller.scrollLeft, true); - signal(cm, "scroll", cm); - } - }); - - // Listen to wheel events in order to try and update the viewport on time. - on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);}); - on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);}); - - // Prevent wrapper from ever scrolling - on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); - - d.dragFunctions = { - enter: function(e) {if (!signalDOMEvent(cm, e)) e_stop(e);}, - over: function(e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }}, - start: function(e){onDragStart(cm, e);}, - drop: operation(cm, onDrop), - leave: function(e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }} - }; - - var inp = d.input.getField(); - on(inp, "keyup", function(e) { onKeyUp.call(cm, e); }); - on(inp, "keydown", operation(cm, onKeyDown)); - on(inp, "keypress", operation(cm, onKeyPress)); - on(inp, "focus", function (e) { onFocus(cm, e); }); - on(inp, "blur", function (e) { onBlur(cm, e); }); - } - - function dragDropChanged(cm, value, old) { - var wasOn = old && old != CodeMirror.Init; - if (!value != !wasOn) { - var funcs = cm.display.dragFunctions; - var toggle = value ? on : off; - toggle(cm.display.scroller, "dragstart", funcs.start); - toggle(cm.display.scroller, "dragenter", funcs.enter); - toggle(cm.display.scroller, "dragover", funcs.over); - toggle(cm.display.scroller, "dragleave", funcs.leave); - toggle(cm.display.scroller, "drop", funcs.drop); - } - } - - // Called when the window resizes - function onResize(cm) { - var d = cm.display; - if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth) - return; - // Might be a text scaling operation, clear size caches. - d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; - d.scrollbarsClipped = false; - cm.setSize(); - } - - // MOUSE EVENTS - - // Return true when the given mouse event happened in a widget - function eventInWidget(display, e) { - for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { - if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") || - (n.parentNode == display.sizer && n != display.mover)) - return true; - } - } - - // Given a mouse event, find the corresponding position. If liberal - // is false, it checks whether a gutter or scrollbar was clicked, - // and returns null if it was. forRect is used by rectangular - // selections, and tries to estimate a character position even for - // coordinates beyond the right of the text. - function posFromMouse(cm, e, liberal, forRect) { - var display = cm.display; - if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null; - - var x, y, space = display.lineSpace.getBoundingClientRect(); - // Fails unpredictably on IE[67] when mouse is dragged around quickly. - try { x = e.clientX - space.left; y = e.clientY - space.top; } - catch (e) { return null; } - var coords = coordsChar(cm, x, y), line; - if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { - var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; - coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)); - } - return coords; - } - - // A mouse down can be a single click, double click, triple click, - // start of selection drag, start of text drag, new cursor - // (ctrl-click), rectangle drag (alt-drag), or xwin - // middle-click-paste. Or it might be a click on something we should - // not interfere with, such as a scrollbar or widget. - function onMouseDown(e) { - var cm = this, display = cm.display; - if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) return; - display.shift = e.shiftKey; - - if (eventInWidget(display, e)) { - if (!webkit) { - // Briefly turn off draggability, to allow widgets to do - // normal dragging things. - display.scroller.draggable = false; - setTimeout(function(){display.scroller.draggable = true;}, 100); - } - return; - } - if (clickInGutter(cm, e)) return; - var start = posFromMouse(cm, e); - window.focus(); - - switch (e_button(e)) { - case 1: - // #3261: make sure, that we're not starting a second selection - if (cm.state.selectingText) - cm.state.selectingText(e); - else if (start) - leftButtonDown(cm, e, start); - else if (e_target(e) == display.scroller) - e_preventDefault(e); - break; - case 2: - if (webkit) cm.state.lastMiddleDown = +new Date; - if (start) extendSelection(cm.doc, start); - setTimeout(function() {display.input.focus();}, 20); - e_preventDefault(e); - break; - case 3: - if (captureRightClick) onContextMenu(cm, e); - else delayBlurEvent(cm); - break; - } - } - - var lastClick, lastDoubleClick; - function leftButtonDown(cm, e, start) { - if (ie) setTimeout(bind(ensureFocus, cm), 0); - else cm.curOp.focus = activeElt(); - - var now = +new Date, type; - if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) { - type = "triple"; - } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) { - type = "double"; - lastDoubleClick = {time: now, pos: start}; - } else { - type = "single"; - lastClick = {time: now, pos: start}; - } - - var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained; - if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() && - type == "single" && (contained = sel.contains(start)) > -1 && - (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) && - (cmp(contained.to(), start) > 0 || start.xRel < 0)) - leftButtonStartDrag(cm, e, start, modifier); - else - leftButtonSelect(cm, e, start, type, modifier); - } - - // Start a text drag. When it ends, see if any dragging actually - // happen, and treat as a click if it didn't. - function leftButtonStartDrag(cm, e, start, modifier) { - var display = cm.display, startTime = +new Date; - var dragEnd = operation(cm, function(e2) { - if (webkit) display.scroller.draggable = false; - cm.state.draggingText = false; - off(document, "mouseup", dragEnd); - off(display.scroller, "drop", dragEnd); - if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) { - e_preventDefault(e2); - if (!modifier && +new Date - 200 < startTime) - extendSelection(cm.doc, start); - // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081) - if (webkit || ie && ie_version == 9) - setTimeout(function() {document.body.focus(); display.input.focus();}, 20); - else - display.input.focus(); - } - }); - // Let the drag handler handle this. - if (webkit) display.scroller.draggable = true; - cm.state.draggingText = dragEnd; - dragEnd.copy = mac ? e.altKey : e.ctrlKey - // IE's approach to draggable - if (display.scroller.dragDrop) display.scroller.dragDrop(); - on(document, "mouseup", dragEnd); - on(display.scroller, "drop", dragEnd); - } - - // Normal selection, as opposed to text dragging. - function leftButtonSelect(cm, e, start, type, addNew) { - var display = cm.display, doc = cm.doc; - e_preventDefault(e); - - var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges; - if (addNew && !e.shiftKey) { - ourIndex = doc.sel.contains(start); - if (ourIndex > -1) - ourRange = ranges[ourIndex]; - else - ourRange = new Range(start, start); - } else { - ourRange = doc.sel.primary(); - ourIndex = doc.sel.primIndex; - } - - if (chromeOS ? e.shiftKey && e.metaKey : e.altKey) { - type = "rect"; - if (!addNew) ourRange = new Range(start, start); - start = posFromMouse(cm, e, true, true); - ourIndex = -1; - } else if (type == "double") { - var word = cm.findWordAt(start); - if (cm.display.shift || doc.extend) - ourRange = extendRange(doc, ourRange, word.anchor, word.head); - else - ourRange = word; - } else if (type == "triple") { - var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0))); - if (cm.display.shift || doc.extend) - ourRange = extendRange(doc, ourRange, line.anchor, line.head); - else - ourRange = line; + on(window, "mouseup", mouseup) } else { - ourRange = extendRange(doc, ourRange, start); - } - - if (!addNew) { - ourIndex = 0; - setSelection(doc, new Selection([ourRange], 0), sel_mouse); - startSel = doc.sel; - } else if (ourIndex == -1) { - ourIndex = ranges.length; - setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex), - {scroll: false, origin: "*mouse"}); - } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) { - setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), - {scroll: false, origin: "*mouse"}); - startSel = doc.sel; - } else { - replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); - } - - var lastPos = start; - function extendTo(pos) { - if (cmp(lastPos, pos) == 0) return; - lastPos = pos; - - if (type == "rect") { - var ranges = [], tabSize = cm.options.tabSize; - var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize); - var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize); - var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol); - for (var 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); - if (left == right) - ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); - else if (text.length > leftPos) - ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); - } - if (!ranges.length) ranges.push(new Range(start, start)); - setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), - {origin: "*mouse", scroll: false}); - cm.scrollIntoView(pos); - } else { - var oldRange = ourRange; - var anchor = oldRange.anchor, head = pos; - if (type != "single") { - if (type == "double") - var range = cm.findWordAt(pos); - else - var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0))); - if (cmp(range.anchor, anchor) > 0) { - head = range.head; - anchor = minPos(oldRange.from(), range.anchor); - } else { - head = range.anchor; - anchor = maxPos(oldRange.to(), range.head); - } - } - var ranges = startSel.ranges.slice(0); - ranges[ourIndex] = new Range(clipPos(doc, anchor), head); - setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse); - } - } - - var editorSize = display.wrapper.getBoundingClientRect(); - // Used to ensure timeout re-tries don't fire when another extend - // happened in the meantime (clearTimeout isn't reliable -- at - // least on Chrome, the timeouts still happen even when cleared, - // if the clear happens after their scheduled firing time). - var counter = 0; - - function extend(e) { - var curCount = ++counter; - var cur = posFromMouse(cm, e, true, type == "rect"); - if (!cur) return; - if (cmp(cur, lastPos) != 0) { - cm.curOp.focus = activeElt(); - extendTo(cur); - var visible = visibleLines(display, doc); - if (cur.line >= visible.to || cur.line < visible.from) - setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150); - } else { - var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; - if (outside) setTimeout(operation(cm, function() { - if (counter != curCount) return; - display.scroller.scrollTop += outside; - extend(e); - }), 50); - } - } - - function done(e) { - cm.state.selectingText = false; - counter = Infinity; - e_preventDefault(e); - display.input.focus(); - off(document, "mousemove", move); - off(document, "mouseup", up); - doc.history.lastSelOrigin = null; - } - - var move = operation(cm, function(e) { - if (!e_button(e)) done(e); - else extend(e); - }); - var up = operation(cm, done); - cm.state.selectingText = up; - on(document, "mousemove", move); - on(document, "mouseup", up); - } - - // Determines whether an event happened in the gutter, and fires the - // handlers for the corresponding event. - function gutterEvent(cm, e, type, prevent) { - try { var mX = e.clientX, mY = e.clientY; } - catch(e) { return false; } - if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false; - if (prevent) e_preventDefault(e); - - var display = cm.display; - var lineBox = display.lineDiv.getBoundingClientRect(); - - if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e); - mY -= lineBox.top - display.viewOffset; - - for (var i = 0; i < cm.options.gutters.length; ++i) { - var g = display.gutters.childNodes[i]; - if (g && g.getBoundingClientRect().right >= mX) { - var line = lineAtHeight(cm.doc, mY); - var gutter = cm.options.gutters[i]; - signal(cm, type, cm, line, gutter, e); - return e_defaultPrevented(e); - } - } - } - - function clickInGutter(cm, e) { - return gutterEvent(cm, e, "gutterClick", true); - } - - // Kludge to work around strange IE behavior where it'll sometimes - // re-fire a series of drag-related events right after the drop (#1551) - var lastDrop = 0; - - function onDrop(e) { - var cm = this; - clearDragCursor(cm); - if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) - return; - e_preventDefault(e); - if (ie) lastDrop = +new Date; - var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; - if (!pos || cm.isReadOnly()) return; - // Might be a file drop, in which case we simply extract the text - // and insert it. - if (files && files.length && window.FileReader && window.File) { - var n = files.length, text = Array(n), read = 0; - var loadFile = function(file, i) { - if (cm.options.allowDropFileTypes && - indexOf(cm.options.allowDropFileTypes, file.type) == -1) - return; - - var reader = new FileReader; - reader.onload = operation(cm, function() { - var content = reader.result; - if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) content = ""; - text[i] = content; - if (++read == n) { - pos = clipPos(cm.doc, pos); - var change = {from: pos, to: pos, - text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())), - origin: "paste"}; - makeChange(cm.doc, change); - setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change))); - } - }); - reader.readAsText(file); - }; - for (var i = 0; i < n; ++i) loadFile(files[i], i); - } else { // Normal drop - // Don't do a replace if the drop happened inside of the selected text. - if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { - cm.state.draggingText(e); - // Ensure the editor is re-focused - setTimeout(function() {cm.display.input.focus();}, 20); - return; - } + setTimeout(rehide, 50) + } + }, + + readOnlyChanged: function(val) { + if (!val) { this.reset() } + }, + + setUneditable: nothing, + + needsContentAttribute: false +}, TextareaInput.prototype) + +function fromTextArea(textarea, options) { + options = options ? copyObj(options) : {} + options.value = textarea.value + if (!options.tabindex && textarea.tabIndex) + { options.tabindex = textarea.tabIndex } + if (!options.placeholder && textarea.placeholder) + { options.placeholder = textarea.placeholder } + // Set autofocus to true if this textarea is focused, or if it has + // autofocus and no other element is focused. + if (options.autofocus == null) { + var hasFocus = activeElt() + options.autofocus = hasFocus == textarea || + textarea.getAttribute("autofocus") != null && hasFocus == document.body + } + + function save() {textarea.value = cm.getValue()} + + var realSubmit + if (textarea.form) { + on(textarea.form, "submit", save) + // Deplorable hack to make the submit method do the right thing. + if (!options.leaveSubmitMethodAlone) { + var form = textarea.form + realSubmit = form.submit try { - var text = e.dataTransfer.getData("Text"); - if (text) { - if (cm.state.draggingText && !cm.state.draggingText.copy) - var selected = cm.listSelections(); - setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); - if (selected) for (var i = 0; i < selected.length; ++i) - replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag"); - cm.replaceSelection(text, "around", "paste"); - cm.display.input.focus(); - } - } - catch(e){} - } - } - - function onDragStart(cm, e) { - if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; } - if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return; - - e.dataTransfer.setData("Text", cm.getSelection()); - e.dataTransfer.effectAllowed = "copyMove" - - // Use dummy image instead of default browsers image. - // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. - if (e.dataTransfer.setDragImage && !safari) { - var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); - img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; - if (presto) { - img.width = img.height = 1; - cm.display.wrapper.appendChild(img); - // Force a relayout, or Opera won't use our image for some obscure reason - img._top = img.offsetTop; - } - e.dataTransfer.setDragImage(img, 0, 0); - if (presto) img.parentNode.removeChild(img); - } - } - - function onDragOver(cm, e) { - var pos = posFromMouse(cm, e); - if (!pos) return; - var frag = document.createDocumentFragment(); - drawSelectionCursor(cm, pos, frag); - if (!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, frag); - } - - function clearDragCursor(cm) { - if (cm.display.dragCursor) { - cm.display.lineSpace.removeChild(cm.display.dragCursor); - cm.display.dragCursor = null; - } - } - - // SCROLL EVENTS - - // Sync the scrollable area and scrollbars, ensure the viewport - // covers the visible area. - function setScrollTop(cm, val) { - if (Math.abs(cm.doc.scrollTop - val) < 2) return; - cm.doc.scrollTop = val; - if (!gecko) updateDisplaySimple(cm, {top: val}); - if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val; - cm.display.scrollbars.setScrollTop(val); - if (gecko) updateDisplaySimple(cm); - startWorker(cm, 100); - } - // Sync scroller and scrollbar, ensure the gutter elements are - // aligned. - function setScrollLeft(cm, val, isScroller) { - if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return; - val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth); - cm.doc.scrollLeft = val; - alignHorizontally(cm); - if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val; - cm.display.scrollbars.setScrollLeft(val); - } - - // Since the delta values reported on mouse wheel events are - // unstandardized between browsers and even browser versions, and - // generally horribly unpredictable, this code starts by measuring - // the scroll effect that the first few mouse wheel events have, - // and, from that, detects the way it can convert deltas to pixel - // offsets afterwards. - // - // The reason we want to know the amount a wheel event will scroll - // is that it gives us a chance to update the display before the - // actual scrolling happens, reducing flickering. - - var wheelSamples = 0, wheelPixelsPerUnit = null; - // Fill in a browser-detected starting value on browsers where we - // know one. These don't have to be accurate -- the result of them - // being wrong would just be a slight flicker on the first wheel - // scroll (if it is large enough). - if (ie) wheelPixelsPerUnit = -.53; - else if (gecko) wheelPixelsPerUnit = 15; - else if (chrome) wheelPixelsPerUnit = -.7; - else if (safari) wheelPixelsPerUnit = -1/3; - - var wheelEventDelta = function(e) { - var dx = e.wheelDeltaX, dy = e.wheelDeltaY; - if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail; - if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail; - else if (dy == null) dy = e.wheelDelta; - return {x: dx, y: dy}; - }; - CodeMirror.wheelEventPixels = function(e) { - var delta = wheelEventDelta(e); - delta.x *= wheelPixelsPerUnit; - delta.y *= wheelPixelsPerUnit; - return delta; - }; - - function onScrollWheel(cm, e) { - var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y; - - var display = cm.display, scroll = display.scroller; - // Quit if there's nothing to scroll here - var canScrollX = scroll.scrollWidth > scroll.clientWidth; - var canScrollY = scroll.scrollHeight > scroll.clientHeight; - if (!(dx && canScrollX || dy && canScrollY)) return; - - // Webkit browsers on OS X abort momentum scrolls when the target - // of the scroll event is removed from the scrollable element. - // This hack (see related code in patchDisplay) makes sure the - // element is kept around. - if (dy && 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; - } - } - } - } - - // On some browsers, horizontal scrolling will cause redraws to - // happen before the gutter has been realigned, causing it to - // wriggle around in a most unseemly way. When we have an - // estimated pixels/delta value, we just handle horizontal - // scrolling entirely here. It'll be slightly off from native, but - // better than glitching out. - if (dx && !gecko && !presto && wheelPixelsPerUnit != null) { - if (dy && canScrollY) - setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight))); - setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth))); - // Only prevent default scrolling if vertical scrolling is - // actually possible. Otherwise, it causes vertical scroll - // jitter on OSX trackpads when deltaX is small and deltaY - // is large (issue #3579) - if (!dy || (dy && canScrollY)) - e_preventDefault(e); - display.wheelStartX = null; // Abort measurement, if in progress - return; - } - - // 'Project' the visible viewport to cover the area that is being - // scrolled into view (if we know enough to estimate it). - if (dy && wheelPixelsPerUnit != null) { - var pixels = dy * wheelPixelsPerUnit; - var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; - if (pixels < 0) top = Math.max(0, top + pixels - 50); - else bot = Math.min(cm.doc.height, bot + pixels + 50); - updateDisplaySimple(cm, {top: top, bottom: bot}); - } - - if (wheelSamples < 20) { - if (display.wheelStartX == null) { - display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop; - display.wheelDX = dx; display.wheelDY = dy; - setTimeout(function() { - if (display.wheelStartX == null) return; - var movedX = scroll.scrollLeft - display.wheelStartX; - var movedY = scroll.scrollTop - display.wheelStartY; - var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || - (movedX && display.wheelDX && movedX / display.wheelDX); - display.wheelStartX = display.wheelStartY = null; - if (!sample) return; - wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); - ++wheelSamples; - }, 200); - } else { - display.wheelDX += dx; display.wheelDY += dy; - } - } - } - - // KEY EVENTS - - // Run a handler that was bound to a key. - function doHandleBinding(cm, bound, dropShift) { - if (typeof bound == "string") { - bound = commands[bound]; - if (!bound) return false; - } - // Ensure previous input has been read, so that the handler sees a - // consistent view of the document - cm.display.input.ensurePolled(); - var prevShift = cm.display.shift, done = false; - try { - if (cm.isReadOnly()) cm.state.suppressEdits = true; - if (dropShift) cm.display.shift = false; - done = bound(cm) != Pass; - } finally { - cm.display.shift = prevShift; - cm.state.suppressEdits = false; - } - return done; - } - - function lookupKeyForEditor(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); - } - - var stopSeq = new Delayed; - function dispatchKey(cm, name, e, handle) { - var seq = cm.state.keySeq; - if (seq) { - if (isModifierKey(name)) return "handled"; - stopSeq.set(50, function() { - if (cm.state.keySeq == seq) { - cm.state.keySeq = null; - cm.display.input.reset(); - } - }); - name = seq + " " + name; - } - var result = lookupKeyForEditor(cm, name, handle); - - if (result == "multi") - cm.state.keySeq = name; - if (result == "handled") - signalLater(cm, "keyHandled", cm, name, e); - - if (result == "handled" || result == "multi") { - e_preventDefault(e); - restartBlink(cm); - } - - if (seq && !result && /\'$/.test(name)) { - e_preventDefault(e); - return true; - } - return !!result; - } - - // Handle a key from the keydown event. - function handleKeyBinding(cm, e) { - var name = keyName(e, true); - if (!name) return false; - - if (e.shiftKey && !cm.state.keySeq) { - // First try to resolve full name (including 'Shift-'). Failing - // that, see if there is a cursor-motion command (starting with - // 'go') bound to the keyname without 'Shift-'. - return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);}) - || dispatchKey(cm, name, e, function(b) { - if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) - return doHandleBinding(cm, b); - }); - } else { - return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); }); - } - } - - // Handle a key from the keypress event - function handleCharBinding(cm, e, ch) { - return dispatchKey(cm, "'" + ch + "'", e, - function(b) { return doHandleBinding(cm, b, true); }); - } - - var lastStoppedKey = null; - function onKeyDown(e) { - var cm = this; - cm.curOp.focus = activeElt(); - if (signalDOMEvent(cm, e)) return; - // IE does strange things with escape. - if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false; - var code = e.keyCode; - cm.display.shift = code == 16 || e.shiftKey; - var handled = handleKeyBinding(cm, e); - if (presto) { - lastStoppedKey = handled ? code : null; - // Opera has no cut event... we try to at least catch the key combo - if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) - cm.replaceSelection("", null, "cut"); - } - - // Turn mouse into crosshair when Alt is held on Mac. - if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) - showCrossHair(cm); - } - - function showCrossHair(cm) { - var lineDiv = cm.display.lineDiv; - addClass(lineDiv, "CodeMirror-crosshair"); - - function up(e) { - if (e.keyCode == 18 || !e.altKey) { - rmClass(lineDiv, "CodeMirror-crosshair"); - off(document, "keyup", up); - off(document, "mouseover", up); - } - } - on(document, "keyup", up); - on(document, "mouseover", up); - } - - function onKeyUp(e) { - if (e.keyCode == 16) this.doc.sel.shift = false; - signalDOMEvent(this, e); - } - - function onKeyPress(e) { - var cm = this; - if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return; - var keyCode = e.keyCode, charCode = e.charCode; - if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;} - if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return; - var ch = String.fromCharCode(charCode == null ? keyCode : charCode); - if (handleCharBinding(cm, e, ch)) return; - cm.display.input.onKeyPress(e); - } - - // FOCUS/BLUR EVENTS - - function delayBlurEvent(cm) { - cm.state.delayingBlurEvent = true; - setTimeout(function() { - if (cm.state.delayingBlurEvent) { - cm.state.delayingBlurEvent = false; - onBlur(cm); - } - }, 100); - } - - function onFocus(cm, e) { - if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false; - - if (cm.options.readOnly == "nocursor") return; - if (!cm.state.focused) { - signal(cm, "focus", cm, e); - cm.state.focused = true; - addClass(cm.display.wrapper, "CodeMirror-focused"); - // This test prevents this from firing when a context - // menu is closed (since the input reset would kill the - // select-all detection hack) - if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { - cm.display.input.reset(); - if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730 - } - cm.display.input.receivedFocus(); - } - restartBlink(cm); - } - function onBlur(cm, e) { - if (cm.state.delayingBlurEvent) return; - - if (cm.state.focused) { - signal(cm, "blur", cm, e); - cm.state.focused = false; - rmClass(cm.display.wrapper, "CodeMirror-focused"); - } - clearInterval(cm.display.blinker); - setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150); - } - - // CONTEXT MENU HANDLING - - // To make the context menu work, we need to briefly unhide the - // textarea (making it as unobtrusive as possible) to let the - // right-click take effect on it. - function onContextMenu(cm, e) { - if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return; - if (signalDOMEvent(cm, e, "contextmenu")) return; - cm.display.input.onContextMenu(e); - } - - function contextMenuInGutter(cm, e) { - if (!hasHandler(cm, "gutterContextMenu")) return false; - return gutterEvent(cm, e, "gutterContextMenu", false); - } - - // UPDATING - - // Compute the position of the end of a change (its 'to' property - // refers to the pre-change end). - var changeEnd = CodeMirror.changeEnd = function(change) { - if (!change.text) return change.to; - return Pos(change.from.line + change.text.length - 1, - lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)); - }; - - // Adjust a position to refer to the post-change position of the - // same text, or the end of the change if the change covers it. - function adjustForChange(pos, change) { - if (cmp(pos, change.from) < 0) return pos; - if (cmp(pos, change.to) <= 0) return changeEnd(change); - - var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; - if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch; - return Pos(line, ch); - } - - function computeSelAfterChange(doc, change) { - var out = []; - for (var 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(out, doc.sel.primIndex); - } - - function offsetPos(pos, old, nw) { - if (pos.line == old.line) - return Pos(nw.line, pos.ch - old.ch + nw.ch); - else - return Pos(nw.line + (pos.line - old.line), pos.ch); - } - - // Used by replaceSelections to allow moving the selection to the - // start or around the replaced test. Hint may be "start" or "around". - function computeReplacedSel(doc, changes, hint) { - var out = []; - var oldPrev = Pos(doc.first, 0), newPrev = oldPrev; - for (var i = 0; i < changes.length; i++) { - var change = changes[i]; - var from = offsetPos(change.from, oldPrev, newPrev); - var to = offsetPos(changeEnd(change), oldPrev, newPrev); - oldPrev = change.to; - newPrev = to; - if (hint == "around") { - var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0; - out[i] = new Range(inv ? to : from, inv ? from : to); - } else { - out[i] = new Range(from, from); - } - } - return new Selection(out, doc.sel.primIndex); - } - - // Allow "beforeChange" event handlers to influence a change - function filterChange(doc, change, update) { - var obj = { - canceled: false, - from: change.from, - to: change.to, - text: change.text, - origin: change.origin, - cancel: function() { this.canceled = true; } - }; - if (update) obj.update = function(from, to, text, origin) { - if (from) this.from = clipPos(doc, from); - if (to) this.to = clipPos(doc, to); - if (text) this.text = text; - if (origin !== undefined) this.origin = origin; - }; - signal(doc, "beforeChange", doc, obj); - if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj); - - if (obj.canceled) return null; - return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}; - } - - // Apply a change to a document, and add it to the document's - // history, and propagating it to all linked documents. - 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, true); - if (!change) return; - } - - // Possibly split or suppress the update based on the presence - // of read-only spans in its range. - var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); - if (split) { - for (var i = split.length - 1; i >= 0; --i) - makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text}); - } else { - makeChangeInner(doc, change); - } - } - - function makeChangeInner(doc, change) { - if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return; - var selAfter = computeSelAfterChange(doc, change); - addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); - - makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); - var rebased = []; - - linkedDocs(doc, function(doc, sharedHist) { - if (!sharedHist && indexOf(rebased, doc.history) == -1) { - rebaseHist(doc.history, change); - rebased.push(doc.history); - } - makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)); - }); - } - - // Revert a change stored in a document's history. - function makeChangeFromHistory(doc, type, allowSelectionOnly) { - if (doc.cm && doc.cm.state.suppressEdits && !allowSelectionOnly) return; - - var hist = doc.history, event, selAfter = doc.sel; - var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done; - - // Verify that there is a useable event (so that ctrl-z won't - // needlessly clear selection events) - for (var i = 0; i < source.length; i++) { - event = source[i]; - if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) - break; - } - if (i == source.length) return; - hist.lastOrigin = hist.lastSelOrigin = null; - - for (;;) { - event = source.pop(); - if (event.ranges) { - pushSelectionToHistory(event, dest); - if (allowSelectionOnly && !event.equals(doc.sel)) { - setSelection(doc, event, {clearRedo: false}); - return; - } - selAfter = event; - } - else break; - } - - // Build up a reverse change object to add to the opposite history - // stack (redo when undoing, and vice versa). - var antiChanges = []; - pushSelectionToHistory(selAfter, dest); - dest.push({changes: antiChanges, generation: hist.generation}); - hist.generation = event.generation || ++hist.maxGeneration; - - var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); - - for (var i = event.changes.length - 1; i >= 0; --i) { - var change = event.changes[i]; - change.origin = type; - if (filter && !filterChange(doc, change, false)) { - source.length = 0; - return; - } - - antiChanges.push(historyChangeFromChange(doc, change)); - - var after = i ? computeSelAfterChange(doc, change) : lst(source); - makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); - if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); - var rebased = []; - - // Propagate to the linked documents - linkedDocs(doc, function(doc, sharedHist) { - if (!sharedHist && indexOf(rebased, doc.history) == -1) { - rebaseHist(doc.history, change); - rebased.push(doc.history); - } - makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); - }); - } - } - - // Sub-views need their line numbers shifted when text is added - // above or below them in the parent document. - function shiftDoc(doc, distance) { - if (distance == 0) return; - 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); - if (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"); - } - } - - // More lower-level change function, handling only a single document - // (not linked ones). - function makeChangeSingleDoc(doc, change, selAfter, spans) { - if (doc.cm && !doc.cm.curOp) - return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans); - - if (change.to.line < doc.first) { - shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); - return; - } - if (change.from.line > doc.lastLine()) return; - - // Clip the change to the size of this doc - if (change.from.line < doc.first) { - var shift = change.text.length - 1 - (doc.first - change.from.line); - shiftDoc(doc, shift); - change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), - text: [lst(change.text)], origin: change.origin}; - } - var last = doc.lastLine(); - if (change.to.line > last) { - change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), - text: [change.text[0]], origin: change.origin}; - } - - change.removed = getBetween(doc, change.from, change.to); - - if (!selAfter) selAfter = computeSelAfterChange(doc, change); - if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans); - else updateDoc(doc, change, spans); - setSelectionNoUndo(doc, selAfter, sel_dontScroll); - } - - // Handle the interaction of a change to a document with the editor - // that this document is part of. - function makeChangeSingleDocInEditor(cm, change, spans) { - var doc = cm.doc, display = cm.display, from = change.from, to = change.to; - - var recomputeMaxLength = false, checkWidthStart = from.line; - if (!cm.options.lineWrapping) { - checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); - doc.iter(checkWidthStart, to.line + 1, function(line) { - if (line == display.maxLine) { - recomputeMaxLength = true; - return true; - } - }); - } - - if (doc.sel.contains(change.from, change.to) > -1) - signalCursorActivity(cm); - - updateDoc(doc, change, spans, estimateHeight(cm)); - - if (!cm.options.lineWrapping) { - doc.iter(checkWidthStart, from.line + change.text.length, function(line) { - var len = lineLength(line); - if (len > display.maxLineLength) { - display.maxLine = line; - display.maxLineLength = len; - display.maxLineChanged = true; - recomputeMaxLength = false; - } - }); - if (recomputeMaxLength) cm.curOp.updateMaxLine = true; - } - - // Adjust frontier, schedule worker - doc.frontier = Math.min(doc.frontier, from.line); - startWorker(cm, 400); - - var lendiff = change.text.length - (to.line - from.line) - 1; - // Remember that these lines changed, for updating the display - if (change.full) - regChange(cm); - else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) - regLineChange(cm, from.line, "text"); - else - regChange(cm, from.line, to.line + 1, lendiff); - - var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change"); - if (changeHandler || changesHandler) { - var obj = { - from: from, to: to, - text: change.text, - removed: change.removed, - origin: change.origin - }; - if (changeHandler) signalLater(cm, "change", cm, obj); - if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); - } - cm.display.selForContextMenu = null; - } - - function replaceRange(doc, code, from, to, origin) { - if (!to) to = from; - if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; } - if (typeof code == "string") code = doc.splitLines(code); - makeChange(doc, {from: from, to: to, text: code, origin: origin}); - } - - // SCROLLING THINGS INTO VIEW - - // If an editor sits on the top or bottom of the window, partially - // scrolled out of view, this ensures that the cursor is visible. - function maybeScrollWindow(cm, coords) { - if (signalDOMEvent(cm, "scrollCursorIntoView")) return; - - var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null; - if (coords.top + box.top < 0) doScroll = true; - else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false; - if (doScroll != null && !phantom) { - var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " + - (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " + - (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " + - coords.left + "px; width: 2px;"); - cm.display.lineSpace.appendChild(scrollNode); - scrollNode.scrollIntoView(doScroll); - cm.display.lineSpace.removeChild(scrollNode); - } - } - - // Scroll a given position into view (immediately), verifying that - // it actually became visible (as line heights are accurately - // measured, the position of something may 'drift' during drawing). - function scrollPosIntoView(cm, pos, end, margin) { - if (margin == null) margin = 0; - for (var limit = 0; limit < 5; limit++) { - var changed = false, coords = cursorCoords(cm, pos); - var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); - var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left), - Math.min(coords.top, endCoords.top) - margin, - Math.max(coords.left, endCoords.left), - Math.max(coords.bottom, endCoords.bottom) + margin); - var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; - if (scrollPos.scrollTop != null) { - setScrollTop(cm, scrollPos.scrollTop); - if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true; - } - if (scrollPos.scrollLeft != null) { - setScrollLeft(cm, scrollPos.scrollLeft); - if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true; - } - if (!changed) break; - } - return coords; - } - - // Scroll a given set of coordinates into view (immediately). - function scrollIntoView(cm, x1, y1, x2, y2) { - var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2); - if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop); - if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft); - } - - // Calculate a new scroll position needed to scroll the given - // rectangle into view. Returns an object with scrollTop and - // scrollLeft properties. When these are undefined, the - // vertical/horizontal position does not need to be adjusted. - function calculateScrollPos(cm, x1, y1, x2, y2) { - var display = cm.display, snapMargin = textHeight(cm.display); - if (y1 < 0) y1 = 0; - var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; - var screen = displayHeight(cm), result = {}; - if (y2 - y1 > screen) y2 = y1 + screen; - var docBottom = cm.doc.height + paddingVert(display); - var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin; - if (y1 < screentop) { - result.scrollTop = atTop ? 0 : y1; - } else if (y2 > screentop + screen) { - var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen); - if (newTop != screentop) result.scrollTop = newTop; - } - - var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft; - var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0); - var tooWide = x2 - x1 > screenw; - if (tooWide) x2 = x1 + screenw; - if (x1 < 10) - result.scrollLeft = 0; - else if (x1 < screenleft) - result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10)); - else if (x2 > screenw + screenleft - 3) - result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw; - return result; - } - - // Store a relative adjustment to the scroll position in the current - // operation (to be applied when the operation finishes). - function addToScrollPos(cm, left, top) { - if (left != null || top != null) resolveScrollToPos(cm); - if (left != null) - cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left; - if (top != null) - cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top; - } - - // Make sure that at the end of the operation the current cursor is - // shown. - function ensureCursorVisible(cm) { - resolveScrollToPos(cm); - var cur = cm.getCursor(), from = cur, to = cur; - if (!cm.options.lineWrapping) { - from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur; - to = Pos(cur.line, cur.ch + 1); - } - cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true}; - } - - // When an operation has its scrollToPos property set, and another - // scroll action is applied before the end of the operation, this - // 'simulates' scrolling that position into view in a cheap way, so - // that the effect of intermediate scroll commands is not ignored. - function resolveScrollToPos(cm) { - var range = cm.curOp.scrollToPos; - if (range) { - cm.curOp.scrollToPos = null; - var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to); - var sPos = calculateScrollPos(cm, Math.min(from.left, to.left), - Math.min(from.top, to.top) - range.margin, - Math.max(from.right, to.right), - Math.max(from.bottom, to.bottom) + range.margin); - cm.scrollTo(sPos.scrollLeft, sPos.scrollTop); - } - } - - // API UTILITIES - - // Indent the given line. The how parameter can be "smart", - // "add"/null, "subtract", or "prev". When aggressive is false - // (typically set to true for forced single-line indents), empty - // lines are not indented, and places where the mode returns Pass - // are left alone. - function indentLine(cm, n, how, aggressive) { - var doc = cm.doc, state; - if (how == null) how = "add"; - if (how == "smart") { - // Fall back to "prev" when the mode doesn't have an indentation - // method. - if (!doc.mode.indent) how = "prev"; - else state = getStateBefore(cm, n); - } - - var tabSize = cm.options.tabSize; - var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); - if (line.stateAfter) line.stateAfter = null; - var curSpaceString = line.text.match(/^\s*/)[0], indentation; - if (!aggressive && !/\S/.test(line.text)) { - indentation = 0; - how = "not"; - } else if (how == "smart") { - indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); - if (indentation == Pass || indentation > 150) { - if (!aggressive) return; - how = "prev"; - } - } - if (how == "prev") { - if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize); - else indentation = 0; - } else if (how == "add") { - indentation = curSpace + cm.options.indentUnit; - } else if (how == "subtract") { - indentation = curSpace - cm.options.indentUnit; - } else if (typeof how == "number") { - indentation = curSpace + how; - } - indentation = Math.max(0, indentation); - - var 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); - - if (indentString != curSpaceString) { - replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); - line.stateAfter = null; - return true; - } else { - // Ensure that, if the cursor was in the whitespace at the start - // of the line, it is moved to the end of that space. - for (var i = 0; i < doc.sel.ranges.length; i++) { - var range = doc.sel.ranges[i]; - if (range.head.line == n && range.head.ch < curSpaceString.length) { - var pos = Pos(n, curSpaceString.length); - replaceOneSelection(doc, i, new Range(pos, pos)); - break; - } - } - } - } - - // Utility for applying a change to a line by handle or number, - // returning the number and optionally registering the line as - // changed. - function changeLine(doc, handle, changeType, op) { - var no = handle, line = handle; - if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle)); - else no = lineNo(handle); - if (no == null) return null; - if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType); - return line; - } - - // Helper for deleting text near the selection(s), used to implement - // backspace, delete, and similar functionality. - function deleteNearSelection(cm, compute) { - var ranges = cm.doc.sel.ranges, kill = []; - // Build up a set of ranges to kill first, merging overlapping - // ranges. - for (var i = 0; i < ranges.length; i++) { - var toKill = compute(ranges[i]); - while (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); - } - // Next, remove those actual ranges. - runInOp(cm, function() { - for (var i = kill.length - 1; i >= 0; i--) - replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); - ensureCursorVisible(cm); - }); - } - - // Used for horizontal relative motion. Dir is -1 or 1 (left or - // right), unit can be "char", "column" (like char, but doesn't - // cross line boundaries), "word" (across next word), or "group" (to - // the start of next group of word or non-word-non-whitespace - // chars). The visually param controls whether, in right-to-left - // text, direction 1 means to move towards the next index in the - // string, or towards the character to the right of the current - // position. The resulting position will have a hitSide=true - // property if it reached the end of the document. - function findPosH(doc, pos, dir, unit, visually) { - var line = pos.line, ch = pos.ch, origDir = dir; - var lineObj = getLine(doc, line); - function findNextLine() { - var l = line + dir; - if (l < doc.first || l >= doc.first + doc.size) return false - line = l; - return lineObj = getLine(doc, l); - } - function moveOnce(boundToLine) { - var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true); - if (next == null) { - if (!boundToLine && findNextLine()) { - if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj); - else ch = dir < 0 ? lineObj.text.length : 0; - } else return false - } else ch = next; - return true; - } - - if (unit == "char") { - moveOnce() - } else if (unit == "column") { - moveOnce(true) - } else if (unit == "word" || unit == "group") { - var sawType = null, group = unit == "group"; - var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); - for (var first = true;; first = false) { - if (dir < 0 && !moveOnce(!first)) break; - var cur = lineObj.text.charAt(ch) || "\n"; - var type = isWordChar(cur, helper) ? "w" - : group && cur == "\n" ? "n" - : !group || /\s/.test(cur) ? null - : "p"; - if (group && !first && !type) type = "s"; - if (sawType && sawType != type) { - if (dir < 0) {dir = 1; moveOnce();} - break; + var wrappedSubmit = form.submit = function () { + save() + form.submit = realSubmit + form.submit() + form.submit = wrappedSubmit } - - if (type) sawType = type; - if (dir > 0 && !moveOnce(!first)) break; - } - } - var result = skipAtomic(doc, Pos(line, ch), pos, origDir, true); - if (!cmp(pos, result)) result.hitSide = true; - return result; - } - - // For relative vertical movement. Dir may be -1 or 1. Unit can be - // "page" or "line". The resulting position will have a hitSide=true - // property if it reached the end of the document. - function findPosV(cm, pos, dir, unit) { - var doc = cm.doc, x = pos.left, y; - if (unit == "page") { - var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); - var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3); - y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount; - } else if (unit == "line") { - y = dir > 0 ? pos.bottom + 3 : pos.top - 3; - } - for (;;) { - var target = coordsChar(cm, x, y); - if (!target.outside) break; - if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; } - y += dir * 5; - } - return target; - } - - // EDITOR METHODS - - // The publicly visible API. Note that methodOp(f) means - // 'wrap f in an operation, performed on its `this` parameter'. - - // This is not the complete set of editor methods. Most of the - // methods defined on the Doc type are also injected into - // CodeMirror.prototype, for backwards compatibility and - // convenience. - - CodeMirror.prototype = { - constructor: CodeMirror, - focus: function(){window.focus(); this.display.input.focus();}, - - setOption: function(option, value) { - var options = this.options, old = options[option]; - if (options[option] == value && option != "mode") return; - options[option] = value; - if (optionHandlers.hasOwnProperty(option)) - operation(this, optionHandlers[option])(this, value, old); - }, - - 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) { - var maps = this.state.keyMaps; - for (var i = 0; i < maps.length; ++i) - if (maps[i] == map || maps[i].name == map) { - maps.splice(i, 1); - return true; - } - }, - - 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."); - insertSorted(this.state.overlays, - {mode: mode, modeSpec: spec, opaque: options && options.opaque, - priority: (options && options.priority) || 0}, - function(overlay) { return overlay.priority }) - this.state.modeGen++; - regChange(this); - }), - removeOverlay: methodOp(function(spec) { - var overlays = this.state.overlays; - for (var i = 0; i < overlays.length; ++i) { - var cur = overlays[i].modeSpec; - if (cur == spec || typeof spec == "string" && cur.name == spec) { - overlays.splice(i, 1); - this.state.modeGen++; - regChange(this); - return; - } - } - }), - - indentLine: methodOp(function(n, dir, aggressive) { - if (typeof dir != "string" && typeof dir != "number") { - if (dir == null) dir = this.options.smartIndent ? "smart" : "prev"; - else dir = dir ? "add" : "subtract"; - } - if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive); - }), - indentSelection: methodOp(function(how) { - var ranges = this.doc.sel.ranges, end = -1; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - if (!range.empty()) { - var from = range.from(), to = range.to(); - var start = Math.max(end, from.line); - end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; - for (var j = start; j < end; ++j) - indentLine(this, j, how); - var newRanges = this.doc.sel.ranges; - if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) - replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); - } else if (range.head.line > end) { - indentLine(this, range.head.line, how, true); - end = range.head.line; - if (i == this.doc.sel.primIndex) ensureCursorVisible(this); - } - } - }), - - // Fetch the parser token for a given character. Useful for hacks - // that want to inspect the mode state (say, for completion). - getTokenAt: function(pos, precise) { - return takeToken(this, pos, precise); - }, - - getLineTokens: function(line, precise) { - return takeToken(this, Pos(line), precise, true); - }, - - getTokenTypeAt: function(pos) { - pos = clipPos(this.doc, pos); - var styles = getLineStyles(this, getLine(this.doc, pos.line)); - var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; - var type; - if (ch == 0) type = styles[2]; - else for (;;) { - var mid = (before + after) >> 1; - if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid; - else if (styles[mid * 2 + 1] < ch) before = mid + 1; - else { type = styles[mid * 2 + 2]; break; } - } - var cut = type ? type.indexOf("cm-overlay ") : -1; - return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1); - }, - - getModeAt: function(pos) { - var mode = this.doc.mode; - if (!mode.innerMode) return mode; - return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode; - }, - - getHelper: function(pos, type) { - return this.getHelpers(pos, type)[0]; - }, - - getHelpers: function(pos, type) { - var found = []; - if (!helpers.hasOwnProperty(type)) return found; - var help = helpers[type], mode = this.getModeAt(pos); - if (typeof mode[type] == "string") { - if (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]]; - if (val) found.push(val); - } - } else if (mode.helperType && help[mode.helperType]) { - found.push(help[mode.helperType]); - } else if (help[mode.name]) { - found.push(help[mode.name]); - } - for (var i = 0; i < help._global.length; i++) { - var cur = help._global[i]; - if (cur.pred(mode, this) && indexOf(found, cur.val) == -1) - found.push(cur.val); - } - return found; - }, - - getStateAfter: function(line, precise) { - var doc = this.doc; - line = clipLine(doc, line == null ? doc.first + doc.size - 1: line); - return getStateBefore(this, line + 1, precise); - }, - - cursorCoords: function(start, mode) { - var pos, range = this.doc.sel.primary(); - if (start == null) pos = range.head; - else if (typeof start == "object") pos = clipPos(this.doc, start); - else pos = start ? range.from() : range.to(); - return cursorCoords(this, pos, mode || "page"); - }, - - charCoords: function(pos, mode) { - return charCoords(this, clipPos(this.doc, pos), mode || "page"); - }, - - coordsChar: function(coords, mode) { - coords = fromCoordSystem(this, coords, mode || "page"); - return coordsChar(this, coords.left, coords.top); - }, - - lineAtHeight: function(height, mode) { - height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top; - return lineAtHeight(this.doc, height + this.display.viewOffset); - }, - heightAtLine: function(line, mode) { - var end = false, lineObj; - if (typeof line == "number") { - var last = this.doc.first + this.doc.size - 1; - if (line < this.doc.first) line = this.doc.first; - else if (line > last) { line = last; end = true; } - lineObj = getLine(this.doc, line); - } else { - lineObj = line; - } - return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top + - (end ? this.doc.height - heightAtLine(lineObj) : 0); - }, - - defaultTextHeight: function() { return textHeight(this.display); }, - defaultCharWidth: function() { return charWidth(this.display); }, - - setGutterMarker: methodOp(function(line, gutterID, value) { - return changeLine(this.doc, line, "gutter", function(line) { - var markers = line.gutterMarkers || (line.gutterMarkers = {}); - markers[gutterID] = value; - if (!value && isEmpty(markers)) line.gutterMarkers = null; - return true; - }); - }), - - clearGutter: methodOp(function(gutterID) { - var cm = this, doc = cm.doc, i = doc.first; - doc.iter(function(line) { - if (line.gutterMarkers && line.gutterMarkers[gutterID]) { - line.gutterMarkers[gutterID] = null; - regLineChange(cm, i, "gutter"); - if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null; - } - ++i; - }); - }), - - lineInfo: function(line) { - if (typeof line == "number") { - if (!isLine(this.doc, line)) return null; - var n = line; - line = getLine(this.doc, line); - if (!line) return null; - } else { - var n = lineNo(line); - if (n == null) 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}; - }, - - getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};}, - - addWidget: function(pos, node, scroll, vert, horiz) { - var display = this.display; - pos = cursorCoords(this, clipPos(this.doc, pos)); - var top = pos.bottom, left = pos.left; - node.style.position = "absolute"; - node.setAttribute("cm-ignore-events", "true"); - this.display.input.setUneditable(node); - display.sizer.appendChild(node); - if (vert == "over") { - top = pos.top; - } else if (vert == "above" || vert == "near") { - var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), - hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); - // Default to positioning above (if specified and possible); otherwise default to positioning below - if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) - top = pos.top - node.offsetHeight; - else if (pos.bottom + node.offsetHeight <= vspace) - top = pos.bottom; - if (left + node.offsetWidth > hspace) - left = hspace - node.offsetWidth; - } - node.style.top = top + "px"; - node.style.left = node.style.right = ""; - if (horiz == "right") { - left = display.sizer.clientWidth - node.offsetWidth; - node.style.right = "0px"; - } else { - if (horiz == "left") left = 0; - else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2; - node.style.left = left + "px"; - } - if (scroll) - scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight); - }, - - triggerOnKeyDown: methodOp(onKeyDown), - triggerOnKeyPress: methodOp(onKeyPress), - triggerOnKeyUp: onKeyUp, - - 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) { - var dir = 1; - if (amount < 0) { dir = -1; amount = -amount; } - for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { - cur = findPosH(this.doc, cur, dir, unit, visually); - if (cur.hitSide) break; - } - return cur; - }, - - moveH: methodOp(function(dir, unit) { - var cm = this; - cm.extendSelectionsBy(function(range) { - if (cm.display.shift || cm.doc.extend || range.empty()) - return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually); - else - return dir < 0 ? range.from() : range.to(); - }, sel_move); - }), - - deleteH: methodOp(function(dir, unit) { - var sel = this.doc.sel, doc = this.doc; - if (sel.somethingSelected()) - doc.replaceSelection("", null, "+delete"); - else - deleteNearSelection(this, function(range) { - var other = findPosH(doc, range.head, dir, unit, false); - return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}; - }); - }), - - findPosV: function(from, amount, unit, goalColumn) { - var dir = 1, x = goalColumn; - if (amount < 0) { dir = -1; amount = -amount; } - for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { - var coords = cursorCoords(this, cur, "div"); - if (x == null) x = coords.left; - else coords.left = x; - cur = findPosV(this, coords, dir, unit); - if (cur.hitSide) break; - } - return cur; - }, - - moveV: methodOp(function(dir, unit) { - var cm = this, doc = this.doc, goals = []; - var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected(); - doc.extendSelectionsBy(function(range) { - if (collapse) - return dir < 0 ? range.from() : range.to(); - var headPos = cursorCoords(cm, range.head, "div"); - if (range.goalColumn != null) headPos.left = range.goalColumn; - goals.push(headPos.left); - var pos = findPosV(cm, headPos, dir, unit); - if (unit == "page" && range == doc.sel.primary()) - addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top); - return pos; - }, sel_move); - if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++) - doc.sel.ranges[i].goalColumn = goals[i]; - }), - - // Find the word at the given position (as returned by coordsChar). - findWordAt: function(pos) { - var doc = this.doc, line = getLine(doc, pos.line).text; - var start = pos.ch, end = pos.ch; - if (line) { - var helper = this.getHelper(pos, "wordChars"); - if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end; - var startChar = line.charAt(start); - var 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);}; - while (start > 0 && check(line.charAt(start - 1))) --start; - while (end < line.length && check(line.charAt(end))) ++end; - } - return new Range(Pos(pos.line, start), Pos(pos.line, end)); - }, - - toggleOverwrite: function(value) { - if (value != null && value == this.state.overwrite) return; - if (this.state.overwrite = !this.state.overwrite) - addClass(this.display.cursorDiv, "CodeMirror-overwrite"); - else - 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) { - if (x != null || y != null) resolveScrollToPos(this); - if (x != null) this.curOp.scrollLeft = x; - if (y != null) this.curOp.scrollTop = 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) { - if (range == null) { - range = {from: this.doc.sel.primary().head, to: null}; - if (margin == null) margin = this.options.cursorScrollMargin; - } else if (typeof range == "number") { - range = {from: Pos(range, 0), to: null}; - } else if (range.from == null) { - range = {from: range, to: null}; - } - if (!range.to) range.to = range.from; - range.margin = margin || 0; - - if (range.from.line != null) { - resolveScrollToPos(this); - this.curOp.scrollToPos = range; - } else { - var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left), - Math.min(range.from.top, range.to.top) - range.margin, - Math.max(range.from.right, range.to.right), - Math.max(range.from.bottom, range.to.bottom) + range.margin); - this.scrollTo(sPos.scrollLeft, sPos.scrollTop); - } - }), - - setSize: methodOp(function(width, height) { - var cm = this; - function interpret(val) { - return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; - } - if (width != null) cm.display.wrapper.style.width = interpret(width); - if (height != null) cm.display.wrapper.style.height = interpret(height); - if (cm.options.lineWrapping) clearLineMeasurementCache(this); - var lineNo = cm.display.viewFrom; - cm.doc.iter(lineNo, cm.display.viewTo, function(line) { - if (line.widgets) for (var i = 0; i < line.widgets.length; i++) - if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; } - ++lineNo; - }); - cm.curOp.forceUpdate = true; - signal(cm, "refresh", this); - }), - - operation: function(f){return runInOp(this, f);}, - - refresh: methodOp(function() { - var oldHeight = this.display.cachedTextHeight; - regChange(this); - this.curOp.forceUpdate = true; - clearCaches(this); - this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop); - updateGutterSpace(this); - if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5) - estimateLineHeights(this); - signal(this, "refresh", this); - }), - - swapDoc: methodOp(function(doc) { - var old = this.doc; - old.cm = null; - attachDoc(this, doc); - clearCaches(this); - this.display.input.reset(); - this.scrollTo(doc.scrollLeft, doc.scrollTop); - this.curOp.forceScroll = true; - signalLater(this, "swapDoc", this, old); - return old; - }), - - 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); - - // OPTION DEFAULTS - - // The default configuration options. - var defaults = CodeMirror.defaults = {}; - // Functions to run when options are changed. - var optionHandlers = CodeMirror.optionHandlers = {}; - - function option(name, deflt, handle, notOnInit) { - CodeMirror.defaults[name] = deflt; - if (handle) optionHandlers[name] = - notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle; - } - - // Passed to option handlers when there is no old value. - var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}}; - - // These two are, on init, called from the constructor because they - // have to be initialized before the editor can start at all. - option("value", "", function(cm, val) { - cm.setValue(val); - }, true); - option("mode", null, function(cm, val) { - cm.doc.modeOption = val; - loadMode(cm); - }, true); - - option("indentUnit", 2, loadMode, true); - option("indentWithTabs", false); - option("smartIndent", true); - option("tabSize", 4, function(cm) { - resetModeState(cm); - clearCaches(cm); - regChange(cm); - }, true); - option("lineSeparator", null, function(cm, val) { - cm.doc.lineSep = val; - if (!val) return; - var newBreaks = [], lineNo = cm.doc.first; - cm.doc.iter(function(line) { - for (var pos = 0;;) { - var found = line.text.indexOf(val, pos); - if (found == -1) break; - pos = found + val.length; - newBreaks.push(Pos(lineNo, found)); - } - lineNo++; - }); - for (var i = newBreaks.length - 1; i >= 0; i--) - replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)) - }); - option("specialChars", /[\u0000-\u001f\u007f\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) { - cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g"); - if (old != CodeMirror.Init) cm.refresh(); - }); - option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true); - option("electricChars", true); - option("inputStyle", mobile ? "contenteditable" : "textarea", function() { - throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME - }, true); - option("spellcheck", false, function(cm, val) { - cm.getInputField().spellcheck = val - }, true); - option("rtlMoveVisually", !windows); - option("wholeLineUpdateBefore", true); - - option("theme", "default", function(cm) { - themeChanged(cm); - guttersChanged(cm); - }, true); - option("keyMap", "default", function(cm, val, old) { - var next = getKeyMap(val); - var prev = old != CodeMirror.Init && getKeyMap(old); - if (prev && prev.detach) prev.detach(cm, next); - if (next.attach) next.attach(cm, prev || null); - }); - option("extraKeys", null); - - option("lineWrapping", false, wrappingChanged, true); - option("gutters", [], function(cm) { - setGuttersForLineNumbers(cm.options); - guttersChanged(cm); - }, true); - option("fixedGutter", true, function(cm, val) { - cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; - cm.refresh(); - }, true); - option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true); - option("scrollbarStyle", "native", function(cm) { - initScrollbars(cm); - updateScrollbars(cm); - cm.display.scrollbars.setScrollTop(cm.doc.scrollTop); - cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft); - }, true); - option("lineNumbers", false, function(cm) { - setGuttersForLineNumbers(cm.options); - guttersChanged(cm); - }, true); - option("firstLineNumber", 1, guttersChanged, true); - option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true); - option("showCursorWhenSelecting", false, updateSelection, true); - - option("resetSelectionOnContextMenu", true); - option("lineWiseCopyCut", true); - - option("readOnly", false, function(cm, val) { - if (val == "nocursor") { - onBlur(cm); - cm.display.input.blur(); - cm.display.disabled = true; - } else { - cm.display.disabled = false; - } - cm.display.input.readOnlyChanged(val) - }); - option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true); - option("dragDrop", true, dragDropChanged); - option("allowDropFileTypes", null); - - option("cursorBlinkRate", 530); - option("cursorScrollMargin", 0); - option("cursorHeight", 1, updateSelection, true); - option("singleCursorHeightPerLine", true, updateSelection, true); - option("workTime", 100); - option("workDelay", 100); - option("flattenSpans", true, resetModeState, true); - option("addModeClass", false, resetModeState, true); - option("pollInterval", 100); - option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;}); - option("historyEventDelay", 1250); - option("viewportMargin", 10, function(cm){cm.refresh();}, true); - option("maxHighlightLength", 10000, resetModeState, true); - option("moveInputWithCursor", true, function(cm, val) { - if (!val) cm.display.input.resetPosition(); - }); - - option("tabindex", null, function(cm, val) { - cm.display.input.getField().tabIndex = val || ""; - }); - option("autofocus", null); - - // MODE DEFINITION AND QUERYING - - // Known modes, by name and by MIME - var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {}; - - // Extra arguments are stored as the mode's dependencies, which is - // used by (legacy) mechanisms like loadmode.js to automatically - // load a mode. (Preferred mechanism is the require/define calls.) - CodeMirror.defineMode = function(name, mode) { - if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name; - if (arguments.length > 2) - mode.dependencies = Array.prototype.slice.call(arguments, 2); - modes[name] = mode; - }; - - CodeMirror.defineMIME = function(mime, spec) { - mimeModes[mime] = spec; - }; - - // Given a MIME type, a {name, ...options} config object, or a name - // string, return a mode config object. - CodeMirror.resolveMode = function(spec) { - if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { - spec = mimeModes[spec]; - } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { - var found = mimeModes[spec.name]; - if (typeof found == "string") found = {name: found}; - spec = createObj(found, spec); - spec.name = found.name; - } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { - return CodeMirror.resolveMode("application/xml"); - } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) { - return CodeMirror.resolveMode("application/json"); - } - if (typeof spec == "string") return {name: spec}; - else return spec || {name: "null"}; - }; - - // Given a mode spec (anything that resolveMode accepts), find and - // initialize an actual mode object. - CodeMirror.getMode = function(options, spec) { - var spec = CodeMirror.resolveMode(spec); - var mfactory = modes[spec.name]; - if (!mfactory) return CodeMirror.getMode(options, "text/plain"); - var modeObj = mfactory(options, spec); - if (modeExtensions.hasOwnProperty(spec.name)) { - var exts = modeExtensions[spec.name]; - for (var prop in exts) { - if (!exts.hasOwnProperty(prop)) continue; - if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop]; - modeObj[prop] = exts[prop]; - } - } - modeObj.name = spec.name; - if (spec.helperType) modeObj.helperType = spec.helperType; - if (spec.modeProps) for (var prop in spec.modeProps) - modeObj[prop] = spec.modeProps[prop]; - - return modeObj; - }; - - // Minimal default mode. - CodeMirror.defineMode("null", function() { - return {token: function(stream) {stream.skipToEnd();}}; - }); - CodeMirror.defineMIME("text/plain", "null"); - - // This can be used to attach properties to mode objects from - // outside the actual mode definition. - var modeExtensions = CodeMirror.modeExtensions = {}; - CodeMirror.extendMode = function(mode, properties) { - var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); - copyObj(properties, exts); - }; - - // EXTENSIONS - - CodeMirror.defineExtension = function(name, func) { - CodeMirror.prototype[name] = func; - }; - CodeMirror.defineDocExtension = function(name, func) { - Doc.prototype[name] = func; - }; - CodeMirror.defineOption = option; - - var initHooks = []; - CodeMirror.defineInitHook = function(f) {initHooks.push(f);}; - - var helpers = CodeMirror.helpers = {}; - CodeMirror.registerHelper = function(type, name, value) { - if (!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}); - }; - - // MODE STATE HANDLING - - // Utility functions for working with state. Exported because nested - // modes need to do this for their inner modes. - - var copyState = CodeMirror.copyState = function(mode, state) { - if (state === true) return state; - if (mode.copyState) return mode.copyState(state); - var nstate = {}; - for (var n in state) { - var val = state[n]; - if (val instanceof Array) val = val.concat([]); - nstate[n] = val; - } - return nstate; - }; - - var startState = CodeMirror.startState = function(mode, a1, a2) { - return mode.startState ? mode.startState(a1, a2) : true; - }; - - // Given a mode and a state (for that mode), find the inner mode and - // state at the position that the state refers to. - CodeMirror.innerMode = function(mode, state) { - while (mode.innerMode) { - var info = mode.innerMode(state); - if (!info || info.mode == mode) break; - state = info.state; - mode = info.mode; - } - return info || {mode: mode, state: state}; - }; - - // STANDARD COMMANDS - - // Commands are parameter-less actions that can be performed on an - // editor, mostly used for keybindings. - var commands = CodeMirror.commands = { - selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);}, - singleSelection: function(cm) { - cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); - }, - killLine: function(cm) { - deleteNearSelection(cm, function(range) { - if (range.empty()) { - var len = getLine(cm.doc, range.head.line).text.length; - if (range.head.ch == len && range.head.line < cm.lastLine()) - return {from: range.head, to: Pos(range.head.line + 1, 0)}; - else - return {from: range.head, to: Pos(range.head.line, len)}; - } else { - return {from: range.from(), to: range.to()}; - } - }); - }, - deleteLine: function(cm) { - deleteNearSelection(cm, function(range) { - return {from: Pos(range.from().line, 0), - to: clipPos(cm.doc, Pos(range.to().line + 1, 0))}; - }); - }, - delLineLeft: function(cm) { - deleteNearSelection(cm, function(range) { - return {from: Pos(range.from().line, 0), to: range.from()}; - }); - }, - delWrappedLineLeft: function(cm) { - deleteNearSelection(cm, function(range) { - var top = cm.charCoords(range.head, "div").top + 5; - var leftPos = cm.coordsChar({left: 0, top: top}, "div"); - return {from: leftPos, to: range.from()}; - }); - }, - delWrappedLineRight: function(cm) { - deleteNearSelection(cm, function(range) { - var top = cm.charCoords(range.head, "div").top + 5; - var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); - return {from: range.from(), to: rightPos }; - }); - }, - undo: function(cm) {cm.undo();}, - redo: function(cm) {cm.redo();}, - undoSelection: function(cm) {cm.undoSelection();}, - redoSelection: function(cm) {cm.redoSelection();}, - goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));}, - goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));}, - goLineStart: function(cm) { - cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); }, - {origin: "+move", bias: 1}); - }, - goLineStartSmart: function(cm) { - cm.extendSelectionsBy(function(range) { - return lineStartSmart(cm, range.head); - }, {origin: "+move", bias: 1}); - }, - goLineEnd: function(cm) { - cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); }, - {origin: "+move", bias: -1}); - }, - goLineRight: function(cm) { - cm.extendSelectionsBy(function(range) { - var top = cm.charCoords(range.head, "div").top + 5; - return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); - }, sel_move); - }, - goLineLeft: function(cm) { - cm.extendSelectionsBy(function(range) { - var top = cm.charCoords(range.head, "div").top + 5; - return cm.coordsChar({left: 0, top: top}, "div"); - }, sel_move); - }, - goLineLeftSmart: function(cm) { - cm.extendSelectionsBy(function(range) { - var top = cm.charCoords(range.head, "div").top + 5; - var pos = cm.coordsChar({left: 0, top: top}, "div"); - if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head); - return pos; - }, sel_move); - }, - goLineUp: function(cm) {cm.moveV(-1, "line");}, - goLineDown: function(cm) {cm.moveV(1, "line");}, - goPageUp: function(cm) {cm.moveV(-1, "page");}, - goPageDown: function(cm) {cm.moveV(1, "page");}, - goCharLeft: function(cm) {cm.moveH(-1, "char");}, - goCharRight: function(cm) {cm.moveH(1, "char");}, - goColumnLeft: function(cm) {cm.moveH(-1, "column");}, - goColumnRight: function(cm) {cm.moveH(1, "column");}, - goWordLeft: function(cm) {cm.moveH(-1, "word");}, - goGroupRight: function(cm) {cm.moveH(1, "group");}, - goGroupLeft: function(cm) {cm.moveH(-1, "group");}, - goWordRight: function(cm) {cm.moveH(1, "word");}, - delCharBefore: function(cm) {cm.deleteH(-1, "char");}, - delCharAfter: function(cm) {cm.deleteH(1, "char");}, - delWordBefore: function(cm) {cm.deleteH(-1, "word");}, - delWordAfter: function(cm) {cm.deleteH(1, "word");}, - delGroupBefore: function(cm) {cm.deleteH(-1, "group");}, - delGroupAfter: function(cm) {cm.deleteH(1, "group");}, - indentAuto: function(cm) {cm.indentSelection("smart");}, - indentMore: function(cm) {cm.indentSelection("add");}, - indentLess: function(cm) {cm.indentSelection("subtract");}, - insertTab: function(cm) {cm.replaceSelection("\t");}, - insertSoftTab: function(cm) { - var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize; - for (var i = 0; i < ranges.length; i++) { - var pos = ranges[i].from(); - var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize); - spaces.push(spaceStr(tabSize - col % tabSize)); - } - cm.replaceSelections(spaces); - }, - defaultTab: function(cm) { - if (cm.somethingSelected()) cm.indentSelection("add"); - else cm.execCommand("insertTab"); - }, - transposeChars: function(cm) { - runInOp(cm, function() { - var ranges = cm.listSelections(), newSel = []; - for (var i = 0; i < ranges.length; i++) { - var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text; - if (line) { - if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1); - if (cur.ch > 0) { - 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"); - } else if (cur.line > cm.doc.first) { - var prev = getLine(cm.doc, cur.line - 1).text; - if (prev) - cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() + - prev.charAt(prev.length - 1), - Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose"); - } - } - newSel.push(new Range(cur, cur)); - } - cm.setSelections(newSel); - }); - }, - newlineAndIndent: function(cm) { - runInOp(cm, function() { - var len = cm.listSelections().length; - for (var i = 0; i < len; i++) { - var range = cm.listSelections()[i]; - cm.replaceRange(cm.doc.lineSeparator(), range.anchor, range.head, "+input"); - cm.indentLine(range.from().line + 1, null, true); - } - ensureCursorVisible(cm); - }); - }, - openLine: function(cm) {cm.replaceSelection("\n", "start")}, - toggleOverwrite: function(cm) {cm.toggleOverwrite();} - }; - - - // STANDARD KEYMAPS - - var keyMap = CodeMirror.keyMap = {}; - - 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" - }; - // Note that the save and find-related commands aren't defined by - // default. User code or addons can define them. Unknown commands - // are simply ignored. - 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" - }; - // Very basic readline/emacs-style bindings, which are standard on Mac. - 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; - - // KEYMAP DISPATCH - - function normalizeKeyName(name) { - var parts = name.split(/-(?!$)/), name = parts[parts.length - 1]; - var alt, ctrl, shift, cmd; - for (var i = 0; i < parts.length - 1; i++) { - var mod = parts[i]; - if (/^(cmd|meta|m)$/i.test(mod)) cmd = true; - else if (/^a(lt)?$/i.test(mod)) alt = true; - else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true; - else if (/^s(hift)$/i.test(mod)) shift = true; - else throw new Error("Unrecognized modifier name: " + mod); - } - if (alt) name = "Alt-" + name; - if (ctrl) name = "Ctrl-" + name; - if (cmd) name = "Cmd-" + name; - if (shift) name = "Shift-" + name; - return name; - } - - // This is a kludge to keep keymaps mostly working as raw objects - // (backwards compatibility) while at the same time support features - // like normalization and multi-stroke key bindings. It compiles a - // new normalized keymap, and then updates the old object to reflect - // this. - CodeMirror.normalizeKeyMap = function(keymap) { - var copy = {}; - for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) { - var value = keymap[keyname]; - if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue; - if (value == "...") { delete keymap[keyname]; continue; } - - var keys = map(keyname.split(" "), normalizeKeyName); - for (var i = 0; i < keys.length; i++) { - var val, name; - if (i == keys.length - 1) { - name = keys.join(" "); - val = value; - } else { - name = keys.slice(0, i + 1).join(" "); - val = "..."; - } - var prev = copy[name]; - if (!prev) copy[name] = val; - else if (prev != val) throw new Error("Inconsistent bindings for " + name); - } - delete keymap[keyname]; - } - for (var prop in copy) keymap[prop] = copy[prop]; - return keymap; - }; - - var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) { - map = getKeyMap(map); - var found = map.call ? map.call(key, context) : map[key]; - if (found === false) return "nothing"; - if (found === "...") return "multi"; - if (found != null && handle(found)) return "handled"; - - if (map.fallthrough) { - if (Object.prototype.toString.call(map.fallthrough) != "[object Array]") - 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; - } - } - }; - - // Modifier key presses don't count as 'real' key presses for the - // purpose of keymap fallthrough. - var isModifierKey = CodeMirror.isModifierKey = function(value) { - var name = typeof value == "string" ? value : keyNames[value.keyCode]; - return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; - }; - - // Look up the name of a key as indicated by an event object. - var keyName = CodeMirror.keyName = function(event, noShift) { - if (presto && event.keyCode == 34 && event["char"]) return false; - var base = keyNames[event.keyCode], name = base; - if (name == null || event.altGraphKey) return false; - if (event.altKey && base != "Alt") name = "Alt-" + name; - if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name; - if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name; - if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name; - return name; - }; - - function getKeyMap(val) { - return typeof val == "string" ? keyMap[val] : val; - } - - // FROMTEXTAREA - - CodeMirror.fromTextArea = function(textarea, options) { - options = options ? copyObj(options) : {}; - options.value = textarea.value; - if (!options.tabindex && textarea.tabIndex) - options.tabindex = textarea.tabIndex; - if (!options.placeholder && textarea.placeholder) - options.placeholder = textarea.placeholder; - // Set autofocus to true if this textarea is focused, or if it has - // autofocus and no other element is focused. - if (options.autofocus == null) { - var hasFocus = activeElt(); - options.autofocus = hasFocus == textarea || - textarea.getAttribute("autofocus") != null && hasFocus == document.body; - } - - function save() {textarea.value = cm.getValue();} - if (textarea.form) { - on(textarea.form, "submit", save); - // Deplorable hack to make the submit method do the right thing. - if (!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; // Prevent this from being ran twice - save(); - textarea.parentNode.removeChild(cm.getWrapperElement()); - textarea.style.display = ""; - if (textarea.form) { - off(textarea.form, "submit", save); - if (typeof textarea.form.submit == "function") - textarea.form.submit = realSubmit; - } - }; - }; - - textarea.style.display = "none"; - var cm = CodeMirror(function(node) { - textarea.parentNode.insertBefore(node, textarea.nextSibling); - }, options); - return cm; - }; - - // STRING STREAM - - // Fed to the mode parsers, provides helper functions to make - // parsers more succinct. - - var StringStream = CodeMirror.StringStream = function(string, tabSize) { - this.pos = this.start = 0; - this.string = string; - this.tabSize = tabSize || 8; - this.lastColumnPos = this.lastColumnValue = 0; - this.lineStart = 0; - }; - - StringStream.prototype = { - eol: function() {return this.pos >= this.string.length;}, - sol: function() {return this.pos == this.lineStart;}, - peek: function() {return this.string.charAt(this.pos) || undefined;}, - next: function() { - if (this.pos < this.string.length) - return this.string.charAt(this.pos++); - }, - eat: function(match) { - var ch = this.string.charAt(this.pos); - if (typeof match == "string") var ok = ch == match; - else var ok = ch && (match.test ? match.test(ch) : match(ch)); - if (ok) {++this.pos; return ch;} - }, - eatWhile: function(match) { - var start = this.pos; - while (this.eat(match)){} - return this.pos > start; - }, - eatSpace: function() { - var start = this.pos; - while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; - return this.pos > start; - }, - skipToEnd: function() {this.pos = this.string.length;}, - skipTo: function(ch) { - var found = this.string.indexOf(ch, this.pos); - if (found > -1) {this.pos = found; return true;} - }, - backUp: function(n) {this.pos -= n;}, - column: function() { - if (this.lastColumnPos < this.start) { - this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); - this.lastColumnPos = this.start; - } - return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); - }, - indentation: function() { - return countColumn(this.string, null, this.tabSize) - - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); - }, - match: function(pattern, consume, caseInsensitive) { - if (typeof pattern == "string") { - var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;}; - var substr = this.string.substr(this.pos, pattern.length); - if (cased(substr) == cased(pattern)) { - if (consume !== false) this.pos += pattern.length; - return true; - } - } else { - var match = this.string.slice(this.pos).match(pattern); - if (match && match.index > 0) return null; - if (match && consume !== false) this.pos += match[0].length; - return match; - } - }, - current: function(){return this.string.slice(this.start, this.pos);}, - hideFirstChars: function(n, inner) { - this.lineStart += n; - try { return inner(); } - finally { this.lineStart -= n; } - } - }; - - // TEXTMARKERS - - // Created with markText and setBookmark methods. A TextMarker is a - // handle that can be used to clear or find a marked position in the - // document. Line objects hold arrays (markedSpans) containing - // {from, to, marker} object pointing to such marker objects, and - // indicating that such a marker is present on that line. Multiple - // lines may point to the same marker when it spans across lines. - // The spans will have null for their from/to properties when the - // marker continues beyond the start/end of the line. Markers have - // links back to the lines they currently touch. - - var nextMarkerId = 0; - - var TextMarker = CodeMirror.TextMarker = function(doc, type) { - this.lines = []; - this.type = type; - this.doc = doc; - this.id = ++nextMarkerId; - }; - eventMixin(TextMarker); - - // Clear the marker. - TextMarker.prototype.clear = function() { - if (this.explicitlyCleared) return; - var cm = this.doc.cm, withOp = cm && !cm.curOp; - if (withOp) startOperation(cm); - if (hasHandler(this, "clear")) { - var found = this.find(); - if (found) signalLater(this, "clear", found.from, found.to); - } - var min = null, max = null; - for (var i = 0; i < this.lines.length; ++i) { - var line = this.lines[i]; - var span = getMarkedSpanFor(line.markedSpans, this); - if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text"); - else if (cm) { - if (span.to != null) max = lineNo(line); - if (span.from != null) min = lineNo(line); - } - line.markedSpans = removeMarkedSpan(line.markedSpans, span); - if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm) - updateLineHeight(line, textHeight(cm.display)); - } - if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) { - var visual = visualLine(this.lines[i]), len = lineLength(visual); - if (len > cm.display.maxLineLength) { - cm.display.maxLine = visual; - cm.display.maxLineLength = len; - cm.display.maxLineChanged = true; - } - } - - if (min != null && cm && this.collapsed) regChange(cm, min, max + 1); - this.lines.length = 0; - this.explicitlyCleared = true; - if (this.atomic && this.doc.cantEdit) { - this.doc.cantEdit = false; - if (cm) reCheckSelection(cm.doc); - } - if (cm) signalLater(cm, "markerCleared", cm, this); - if (withOp) endOperation(cm); - if (this.parent) this.parent.clear(); - }; - - // Find the position of the marker in the document. Returns a {from, - // to} object by default. Side can be passed to get a specific side - // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the - // Pos objects returned contain a line object, rather than a line - // number (used to prevent looking up the same line twice). - TextMarker.prototype.find = function(side, lineObj) { - if (side == null && this.type == "bookmark") side = 1; - var from, to; - for (var i = 0; i < this.lines.length; ++i) { - var line = this.lines[i]; - var span = getMarkedSpanFor(line.markedSpans, this); - if (span.from != null) { - from = Pos(lineObj ? line : lineNo(line), span.from); - if (side == -1) return from; - } - if (span.to != null) { - to = Pos(lineObj ? line : lineNo(line), span.to); - if (side == 1) return to; - } - } - return from && {from: from, to: to}; - }; - - // Signals that the marker's widget changed, and surrounding layout - // should be recomputed. - TextMarker.prototype.changed = function() { - var pos = this.find(-1, true), widget = this, cm = this.doc.cm; - if (!pos || !cm) return; - runInOp(cm, function() { - var line = pos.line, lineN = lineNo(pos.line); - var view = findViewForLine(cm, lineN); - if (view) { - clearLineMeasurementCacheFor(view); - cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; - } - cm.curOp.updateMaxLine = true; - if (!lineIsHidden(widget.doc, line) && widget.height != null) { - var oldHeight = widget.height; - widget.height = null; - var dHeight = widgetHeight(widget) - oldHeight; - if (dHeight) - updateLineHeight(line, line.height + dHeight); - } - }); - }; - - TextMarker.prototype.attachLine = function(line) { - if (!this.lines.length && this.doc.cm) { - var op = this.doc.cm.curOp; - if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) - (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); - } - this.lines.push(line); - }; - TextMarker.prototype.detachLine = function(line) { - this.lines.splice(indexOf(this.lines, line), 1); - if (!this.lines.length && this.doc.cm) { - var op = this.doc.cm.curOp; - (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); - } - }; - - // Collapsed markers have unique ids, in order to be able to order - // them, which is needed for uniquely determining an outer marker - // when they overlap (they may nest, but not partially overlap). - var nextMarkerId = 0; - - // Create a marker, wire it up to the right lines, and - function markText(doc, from, to, options, type) { - // Shared markers (across linked documents) are handled separately - // (markTextShared will call out to this again, once per - // document). - if (options && options.shared) return markTextShared(doc, from, to, options, type); - // Ensure we are in an operation. - if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type); - - var marker = new TextMarker(doc, type), diff = cmp(from, to); - if (options) copyObj(options, marker, false); - // Don't connect empty markers unless clearWhenEmpty is false - if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) - return marker; - if (marker.replacedWith) { - // Showing up as a widget implies collapsed (widget replaces text) - marker.collapsed = true; - marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget"); - if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true"); - if (options.insertLeft) marker.widgetNode.insertLeft = true; - } - if (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 = true; - } - - if (marker.addToHistory) - addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); - - var curLine = from.line, cm = doc.cm, updateMaxLine; - doc.iter(curLine, to.line + 1, function(line) { - if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) - updateMaxLine = true; - if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0); - addMarkedSpan(line, new MarkedSpan(marker, - curLine == from.line ? from.ch : null, - curLine == to.line ? to.ch : null)); - ++curLine; - }); - // lineIsHidden depends on the presence of the spans, so needs a second pass - if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) { - if (lineIsHidden(doc, line)) updateLineHeight(line, 0); - }); - - if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); }); - - if (marker.readOnly) { - sawReadOnlySpans = true; - if (doc.history.done.length || doc.history.undone.length) - doc.clearHistory(); - } - if (marker.collapsed) { - marker.id = ++nextMarkerId; - marker.atomic = true; - } - if (cm) { - // Sync editor state - if (updateMaxLine) cm.curOp.updateMaxLine = true; - if (marker.collapsed) - regChange(cm, from.line, to.line + 1); - else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css) - for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text"); - if (marker.atomic) reCheckSelection(cm.doc); - signalLater(cm, "markerAdded", cm, marker); - } - return marker; - } - - // SHARED TEXTMARKERS - - // A shared marker spans multiple linked documents. It is - // implemented as a meta-marker-object controlling multiple normal - // markers. - var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) { - this.markers = markers; - this.primary = primary; - for (var i = 0; i < markers.length; ++i) - markers[i].parent = this; - }; - eventMixin(SharedTextMarker); - - SharedTextMarker.prototype.clear = function() { - if (this.explicitlyCleared) return; - this.explicitlyCleared = true; - 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); - }; - - function markTextShared(doc, from, to, options, type) { - options = copyObj(options); - options.shared = false; - var markers = [markText(doc, from, to, options, type)], primary = markers[0]; - var widget = options.widgetNode; - linkedDocs(doc, function(doc) { - if (widget) options.widgetNode = widget.cloneNode(true); - 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); - }); - return new SharedTextMarker(markers, primary); - } - - function findSharedMarkers(doc) { - return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), - function(m) { return m.parent; }); - } - - function copySharedMarkers(doc, markers) { - for (var i = 0; i < markers.length; i++) { - var marker = markers[i], pos = marker.find(); - var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to); - if (cmp(mFrom, mTo)) { - var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type); - marker.markers.push(subMark); - subMark.parent = marker; - } - } - } - - function detachSharedMarkers(markers) { - for (var i = 0; i < markers.length; i++) { - var marker = markers[i], linked = [marker.primary.doc];; - linkedDocs(marker.primary.doc, function(d) { linked.push(d); }); - for (var j = 0; j < marker.markers.length; j++) { - var subMarker = marker.markers[j]; - if (indexOf(linked, subMarker.doc) == -1) { - subMarker.parent = null; - marker.markers.splice(j--, 1); - } - } - } - } - - // TEXTMARKER SPANS - - function MarkedSpan(marker, from, to) { - this.marker = marker; - this.from = from; this.to = to; - } - - // Search an array of spans for a span matching the given marker. - function getMarkedSpanFor(spans, marker) { - if (spans) for (var i = 0; i < spans.length; ++i) { - var span = spans[i]; - if (span.marker == marker) return span; - } - } - // Remove a span from an array, returning undefined if no spans are - // left (we don't store arrays for lines without spans). - function removeMarkedSpan(spans, span) { - for (var r, i = 0; i < spans.length; ++i) - if (spans[i] != span) (r || (r = [])).push(spans[i]); - return r; - } - // Add a span to a line. - function addMarkedSpan(line, span) { - line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; - span.marker.attachLine(line); - } - - // Used for the algorithm that adjusts markers for a change in the - // document. These functions cut an array of spans at a given - // character position, returning an array of remaining chunks (or - // undefined if nothing remains). - function markedSpansBefore(old, startCh, isInsert) { - if (old) for (var i = 0, nw; i < old.length; ++i) { - var span = old[i], marker = span.marker; - var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); - if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { - var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh); - (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)); - } - } - return nw; - } - function markedSpansAfter(old, endCh, isInsert) { - if (old) for (var i = 0, nw; i < old.length; ++i) { - var span = old[i], marker = span.marker; - var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); - if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { - var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh); - (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, - span.to == null ? null : span.to - endCh)); - } - } - return nw; - } - - // Given a change object, compute the new set of marker spans that - // cover the line in which the change took place. Removes spans - // entirely within the change, reconnects spans belonging to the - // same marker that appear on both sides of the change, and cuts off - // spans partially within the change. Returns an array of span - // arrays with one element for each line in (after) the change. - function stretchSpansOverChange(doc, change) { - if (change.full) return null; - var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; - var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; - if (!oldFirst && !oldLast) return null; - - var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0; - // Get the spans that 'stick out' on both sides - var first = markedSpansBefore(oldFirst, startCh, isInsert); - var last = markedSpansAfter(oldLast, endCh, isInsert); - - // Next, merge those two ends - var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0); - if (first) { - // Fix up .to properties of first - for (var i = 0; i < first.length; ++i) { - var span = first[i]; - if (span.to == null) { - var found = getMarkedSpanFor(last, span.marker); - if (!found) span.to = startCh; - else if (sameLine) span.to = found.to == null ? null : found.to + offset; - } - } - } - if (last) { - // Fix up .from in last (or move them into first in case of sameLine) - for (var i = 0; i < last.length; ++i) { - var span = last[i]; - if (span.to != null) span.to += offset; - if (span.from == null) { - var found = getMarkedSpanFor(first, span.marker); - if (!found) { - span.from = offset; - if (sameLine) (first || (first = [])).push(span); - } - } else { - span.from += offset; - if (sameLine) (first || (first = [])).push(span); - } - } - } - // Make sure we didn't create any zero-length spans - if (first) first = clearEmptySpans(first); - if (last && last != first) last = clearEmptySpans(last); - - var newMarkers = [first]; - if (!sameLine) { - // Fill gap with whole-line-spans - var gap = change.text.length - 2, gapMarkers; - if (gap > 0 && first) - for (var i = 0; i < first.length; ++i) - if (first[i].to == null) - (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null)); - for (var i = 0; i < gap; ++i) - newMarkers.push(gapMarkers); - newMarkers.push(last); - } - return newMarkers; - } - - // Remove spans that are empty and don't have a clearWhenEmpty - // option of false. - function clearEmptySpans(spans) { - for (var i = 0; i < spans.length; ++i) { - var span = spans[i]; - if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) - spans.splice(i--, 1); - } - if (!spans.length) return null; - return spans; - } - - // Used for un/re-doing changes from the history. Combines the - // result of computing the existing spans with the set of spans that - // existed in the history (so that deleting around a span and then - // undoing brings back the span). - function mergeOldSpans(doc, change) { - var old = getOldSpans(doc, change); - var stretched = stretchSpansOverChange(doc, change); - if (!old) return stretched; - if (!stretched) return old; - - 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) { - var span = stretchCur[j]; - for (var k = 0; k < oldCur.length; ++k) - if (oldCur[k].marker == span.marker) continue spans; - oldCur.push(span); - } - } else if (stretchCur) { - old[i] = stretchCur; - } - } - return old; - } - - // Used to 'clip' out readOnly ranges when making a change. - function removeReadOnlyRanges(doc, from, to) { - var markers = null; - 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; - if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) - (markers || (markers = [])).push(mark); - } - }); - if (!markers) return null; - var parts = [{from: from, to: to}]; - for (var i = 0; i < markers.length; ++i) { - var mk = markers[i], m = mk.find(0); - for (var j = 0; j < parts.length; ++j) { - var p = parts[j]; - if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue; - var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to); - if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) - newParts.push({from: p.from, to: m.from}); - if (dto > 0 || !mk.inclusiveRight && !dto) - newParts.push({from: m.to, to: p.to}); - parts.splice.apply(parts, newParts); - j += newParts.length - 1; - } - } - return parts; - } - - // Connect or disconnect spans from a line. - function detachMarkedSpans(line) { - var spans = line.markedSpans; - if (!spans) return; - for (var i = 0; i < spans.length; ++i) - spans[i].marker.detachLine(line); - line.markedSpans = null; - } - function attachMarkedSpans(line, spans) { - if (!spans) return; - for (var i = 0; i < spans.length; ++i) - spans[i].marker.attachLine(line); - line.markedSpans = spans; - } - - // Helpers used when computing which overlapping collapsed span - // counts as the larger one. - function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; } - function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; } - - // Returns a number indicating which of two overlapping collapsed - // spans is larger (and thus includes the other). Falls back to - // comparing ids when the spans cover exactly the same range. - function compareCollapsedMarkers(a, b) { - var lenDiff = a.lines.length - b.lines.length; - if (lenDiff != 0) return lenDiff; - var aPos = a.find(), bPos = b.find(); - var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); - if (fromCmp) return -fromCmp; - var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); - if (toCmp) return toCmp; - return b.id - a.id; - } - - // Find out whether a line ends or starts in a collapsed span. If - // so, return the marker for that span. - function collapsedSpanAtSide(line, start) { - var sps = sawCollapsedSpans && line.markedSpans, found; - if (sps) for (var sp, i = 0; i < sps.length; ++i) { - sp = sps[i]; - if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && - (!found || compareCollapsedMarkers(found, sp.marker) < 0)) - found = sp.marker; - } - return found; - } - function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); } - function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); } - - // Test whether there exists a collapsed span that partially - // overlaps (covers the start or end, but not both) of a new span. - // Such overlap is not allowed. - function conflictingCollapsedRange(doc, lineNo, from, to, marker) { - var line = getLine(doc, lineNo); - var sps = sawCollapsedSpans && line.markedSpans; - if (sps) for (var i = 0; i < sps.length; ++i) { - var sp = sps[i]; - if (!sp.marker.collapsed) continue; - var found = sp.marker.find(0); - var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); - var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); - if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue; - if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) || - fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0)) - return true; - } - } - - // A visual line is a line as drawn on the screen. Folding, for - // example, can cause multiple logical lines to appear on the same - // visual line. This finds the start of the visual line that the - // given line is part of (usually that is the line itself). - function visualLine(line) { - var merged; - while (merged = collapsedSpanAtStart(line)) - line = merged.find(-1, true).line; - return line; - } - - // Returns an array of logical lines that continue the visual line - // started by the argument, or undefined if there are no such lines. - function visualLineContinued(line) { - var merged, lines; - while (merged = collapsedSpanAtEnd(line)) { - line = merged.find(1, true).line; - (lines || (lines = [])).push(line); - } - return lines; - } - - // Get the line number of the start of the visual line that the - // given line number is part of. - function visualLineNo(doc, lineN) { - var line = getLine(doc, lineN), vis = visualLine(line); - if (line == vis) return lineN; - return lineNo(vis); - } - // Get the line number of the start of the next visual line after - // the given line. - function visualLineEndNo(doc, lineN) { - if (lineN > doc.lastLine()) return lineN; - var line = getLine(doc, lineN), merged; - if (!lineIsHidden(doc, line)) return lineN; - while (merged = collapsedSpanAtEnd(line)) - line = merged.find(1, true).line; - return lineNo(line) + 1; - } - - // Compute whether a line is hidden. Lines count as hidden when they - // are part of a visual line that starts with another line, or when - // they are entirely covered by collapsed, non-widget span. - function lineIsHidden(doc, line) { - var sps = sawCollapsedSpans && line.markedSpans; - if (sps) for (var sp, i = 0; i < sps.length; ++i) { - sp = sps[i]; - if (!sp.marker.collapsed) continue; - if (sp.from == null) return true; - if (sp.marker.widgetNode) continue; - if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) - return true; - } - } - function lineIsHiddenInner(doc, line, span) { - if (span.to == null) { - var end = span.marker.find(1, true); - return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)); - } - if (span.marker.inclusiveRight && span.to == line.text.length) - return true; - for (var sp, i = 0; i < line.markedSpans.length; ++i) { - sp = line.markedSpans[i]; - if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && - (sp.to == null || sp.to != span.from) && - (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && - lineIsHiddenInner(doc, line, sp)) return true; - } - } - - // LINE WIDGETS - - // Line widgets are block elements displayed above or below a line. - - var LineWidget = CodeMirror.LineWidget = function(doc, node, options) { - if (options) for (var opt in options) if (options.hasOwnProperty(opt)) - this[opt] = options[opt]; - this.doc = doc; - this.node = node; - }; - eventMixin(LineWidget); - - function adjustScrollWhenAboveVisible(cm, line, diff) { - if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) - addToScrollPos(cm, null, diff); - } - - LineWidget.prototype.clear = function() { - var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line); - if (no == null || !ws) return; - for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1); - if (!ws.length) line.widgets = null; - var height = widgetHeight(this); - updateLineHeight(line, Math.max(0, line.height - height)); - if (cm) runInOp(cm, function() { - adjustScrollWhenAboveVisible(cm, line, -height); - regLineChange(cm, no, "widget"); - }); - }; - LineWidget.prototype.changed = function() { - var oldH = this.height, cm = this.doc.cm, line = this.line; - this.height = null; - var diff = widgetHeight(this) - oldH; - if (!diff) return; - updateLineHeight(line, line.height + diff); - if (cm) runInOp(cm, function() { - cm.curOp.forceUpdate = true; - adjustScrollWhenAboveVisible(cm, line, diff); - }); - }; - - function widgetHeight(widget) { - if (widget.height != null) return widget.height; - var cm = widget.doc.cm; - if (!cm) return 0; - if (!contains(document.body, widget.node)) { - var parentStyle = "position: relative;"; - if (widget.coverGutter) - parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; - if (widget.noHScroll) - parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; - removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)); - } - return widget.height = widget.node.parentNode.offsetHeight; - } - - function addLineWidget(doc, handle, node, options) { - var widget = new LineWidget(doc, node, options); - var cm = doc.cm; - if (cm && widget.noHScroll) cm.display.alignWidgets = true; - changeLine(doc, handle, "widget", function(line) { - var widgets = line.widgets || (line.widgets = []); - if (widget.insertAt == null) widgets.push(widget); - else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); - widget.line = line; - if (cm && !lineIsHidden(doc, line)) { - var aboveVisible = heightAtLine(line) < doc.scrollTop; - updateLineHeight(line, line.height + widgetHeight(widget)); - if (aboveVisible) addToScrollPos(cm, null, widget.height); - cm.curOp.forceUpdate = true; - } - return true; - }); - return widget; - } - - // LINE DATA STRUCTURE - - // Line objects. These hold state related to a line, including - // highlighting info (the styles array). - var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) { - this.text = text; - attachMarkedSpans(this, markedSpans); - this.height = estimateHeight ? estimateHeight(this) : 1; - }; - eventMixin(Line); - Line.prototype.lineNo = function() { return lineNo(this); }; - - // Change the content (text, markers) of a line. Automatically - // invalidates cached information and tries to re-estimate the - // line's height. - function updateLine(line, text, markedSpans, estimateHeight) { - line.text = text; - if (line.stateAfter) line.stateAfter = null; - if (line.styles) line.styles = null; - if (line.order != null) line.order = null; - detachMarkedSpans(line); - attachMarkedSpans(line, markedSpans); - var estHeight = estimateHeight ? estimateHeight(line) : 1; - if (estHeight != line.height) updateLineHeight(line, estHeight); - } - - // Detach a line from the document tree and its markers. - function cleanUpLine(line) { - line.parent = null; - detachMarkedSpans(line); - } - - 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"; - if (output[prop] == null) - output[prop] = lineClass[2]; - else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop])) - output[prop] += " " + lineClass[2]; - } - return type; - } - - function callBlankLine(mode, state) { - if (mode.blankLine) return mode.blankLine(state); - if (!mode.innerMode) return; - var inner = CodeMirror.innerMode(mode, state); - if (inner.mode.blankLine) return inner.mode.blankLine(inner.state); - } - - function readToken(mode, stream, state, inner) { - for (var i = 0; i < 10; i++) { - if (inner) inner[0] = CodeMirror.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."); - } - - // Utility for getTokenAt and getLineTokens - function takeToken(cm, pos, precise, asArray) { - function getObj(copy) { - return {start: stream.start, end: stream.pos, - string: stream.current(), - type: style || null, - state: copy ? copyState(doc.mode, state) : state}; - } - - var doc = cm.doc, mode = doc.mode, style; - pos = clipPos(doc, pos); - var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise); - var stream = new StringStream(line.text, cm.options.tabSize), tokens; - if (asArray) tokens = []; - while ((asArray || stream.pos < pos.ch) && !stream.eol()) { - stream.start = stream.pos; - style = readToken(mode, stream, state); - if (asArray) tokens.push(getObj(true)); - } - return asArray ? tokens : getObj(); - } - - // Run the given mode's parser over a line, calling f for each token. - function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) { - var flattenSpans = mode.flattenSpans; - if (flattenSpans == null) flattenSpans = cm.options.flattenSpans; - var curStart = 0, curStyle = null; - var stream = new StringStream(text, cm.options.tabSize), style; - var inner = cm.options.addModeClass && [null]; - if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses); - while (!stream.eol()) { - if (stream.pos > cm.options.maxHighlightLength) { - flattenSpans = false; - if (forceToEnd) processLine(cm, text, state, stream.pos); - stream.pos = text.length; - style = null; - } else { - style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses); - } - if (inner) { - var mName = inner[0].name; - if (mName) style = "m-" + (style ? mName + " " + style : mName); - } - if (!flattenSpans || curStyle != style) { - while (curStart < stream.start) { - curStart = Math.min(stream.start, curStart + 5000); - f(curStart, curStyle); - } - curStyle = style; - } - stream.start = stream.pos; - } - while (curStart < stream.pos) { - // Webkit seems to refuse to render text nodes longer than 57444 - // characters, and returns inaccurate measurements in nodes - // starting around 5000 chars. - var pos = Math.min(stream.pos, curStart + 5000); - f(pos, curStyle); - curStart = pos; - } - } - - // Compute a style array (an array starting with a mode generation - // -- for invalidation -- followed by pairs of end positions and - // style strings), which is used to highlight the tokens on the - // line. - function highlightLine(cm, line, state, forceToEnd) { - // A styles array always starts with a number identifying the - // mode/overlays that it is based on (for easy invalidation). - var st = [cm.state.modeGen], lineClasses = {}; - // Compute the base array of styles - runMode(cm, line.text, cm.doc.mode, state, function(end, style) { - st.push(end, style); - }, lineClasses, forceToEnd); - - // Run overlays, adjust style array. - for (var o = 0; o < cm.state.overlays.length; ++o) { - var overlay = cm.state.overlays[o], i = 1, at = 0; - runMode(cm, line.text, overlay.mode, true, function(end, style) { - var start = i; - // Ensure there's a token end at the current position, and that i points at it - while (at < end) { - var i_end = st[i]; - if (i_end > end) - st.splice(i, 1, end, st[i+1], i_end); - i += 2; - at = Math.min(end, i_end); - } - if (!style) return; - if (overlay.opaque) { - st.splice(start, i - start, end, "cm-overlay " + style); - i = start + 2; - } else { - for (; start < i; start += 2) { - var cur = st[start+1]; - st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style; - } - } - }, lineClasses); - } - - return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}; - } - - function getLineStyles(cm, line, updateFrontier) { - if (!line.styles || line.styles[0] != cm.state.modeGen) { - var state = getStateBefore(cm, lineNo(line)); - var result = highlightLine(cm, line, line.text.length > cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state); - line.stateAfter = state; - line.styles = result.styles; - if (result.classes) line.styleClasses = result.classes; - else if (line.styleClasses) line.styleClasses = null; - if (updateFrontier === cm.doc.frontier) cm.doc.frontier++; - } - return line.styles; - } - - // Lightweight form of highlight -- proceed over this line and - // update state, but don't save a style array. Used for lines that - // aren't currently visible. - function processLine(cm, text, state, startAt) { - var mode = cm.doc.mode; - var stream = new StringStream(text, cm.options.tabSize); - stream.start = stream.pos = startAt || 0; - if (text == "") callBlankLine(mode, state); - while (!stream.eol()) { - readToken(mode, stream, state); - stream.start = stream.pos; - } - } - - // Convert a style as returned by a mode (either null, or a string - // containing one or more styles) to a CSS style. This is cached, - // and also looks for line-wide styles. - var styleToClassCache = {}, styleToClassCacheWithMode = {}; - function interpretTokenStyle(style, options) { - if (!style || /^\s*$/.test(style)) return null; - var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; - return cache[style] || - (cache[style] = style.replace(/\S+/g, "cm-$&")); - } - - // Render the DOM representation of the text of a line. Also builds - // up a 'line map', which points at the DOM nodes that represent - // specific stretches of text, and is used by the measuring code. - // The returned object contains the DOM node, this map, and - // information about line-wide styles that were set by the mode. - function buildLineContent(cm, lineView) { - // The padding-right forces the element to have a 'border', which - // is needed on Webkit to be able to get line-level bounding - // rectangles for it (in measureChar). - var content = elt("span", null, null, webkit ? "padding-right: .1px" : null); - var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content, - col: 0, pos: 0, cm: cm, - trailingSpace: false, - splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")}; - lineView.measure = {}; - - // Iterate over the logical lines that make up this visual line. - for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { - var line = i ? lineView.rest[i - 1] : lineView.line, order; - builder.pos = 0; - builder.addToken = buildToken; - // Optionally wire in some hacks into the token-rendering - // algorithm, to deal with browser quirks. - if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line))) - builder.addToken = buildTokenBadBidi(builder.addToken, order); - builder.map = []; - var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line); - insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)); - if (line.styleClasses) { - if (line.styleClasses.bgClass) - builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); - if (line.styleClasses.textClass) - builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); - } - - // Ensure at least a single node is present, for measuring. - if (builder.map.length == 0) - builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); - - // Store the map and a cache object for the current logical line - if (i == 0) { - lineView.measure.map = builder.map; - lineView.measure.cache = {}; - } else { - (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map); - (lineView.measure.caches || (lineView.measure.caches = [])).push({}); - } - } - - // See issue #2901 - if (webkit) { - var last = builder.content.lastChild - if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab"))) - builder.content.className = "cm-tab-wrap-hack"; - } - - signal(cm, "renderLine", cm, lineView.line, builder.pre); - if (builder.pre.className) - builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); - - return builder; - } - - function defaultSpecialCharPlaceholder(ch) { - var token = elt("span", "\u2022", "cm-invalidchar"); - token.title = "\\u" + ch.charCodeAt(0).toString(16); - token.setAttribute("aria-label", token.title); - return token; - } - - // Build up the DOM representation for a single token, and add it to - // the line map. Takes care to render special characters separately. - function buildToken(builder, text, style, startStyle, endStyle, title, css) { - if (!text) return; - var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text - var special = builder.cm.state.specialChars, mustWrap = false; - if (!special.test(text)) { - builder.col += text.length; - var content = document.createTextNode(displayText); - builder.map.push(builder.pos, builder.pos + text.length, content); - if (ie && ie_version < 9) mustWrap = true; - builder.pos += text.length; - } else { - var content = document.createDocumentFragment(), pos = 0; - while (true) { - special.lastIndex = pos; - var m = special.exec(text); - var skipped = m ? m.index - pos : text.length - pos; - if (skipped) { - var txt = document.createTextNode(displayText.slice(pos, pos + skipped)); - if (ie && ie_version < 9) content.appendChild(elt("span", [txt])); - else content.appendChild(txt); - builder.map.push(builder.pos, builder.pos + skipped, txt); - builder.col += skipped; - builder.pos += skipped; - } - if (!m) break; - pos += skipped + 1; - if (m[0] == "\t") { - var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; - var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); - txt.setAttribute("role", "presentation"); - txt.setAttribute("cm-text", "\t"); - builder.col += tabWidth; - } else if (m[0] == "\r" || m[0] == "\n") { - var txt = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar")); - txt.setAttribute("cm-text", m[0]); - builder.col += 1; - } else { - var txt = builder.cm.options.specialCharPlaceholder(m[0]); - txt.setAttribute("cm-text", m[0]); - if (ie && ie_version < 9) content.appendChild(elt("span", [txt])); - else content.appendChild(txt); - builder.col += 1; - } - builder.map.push(builder.pos, builder.pos + 1, txt); - builder.pos++; - } - } - builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32 - if (style || startStyle || endStyle || mustWrap || css) { - var fullStyle = style || ""; - if (startStyle) fullStyle += startStyle; - if (endStyle) fullStyle += endStyle; - var token = elt("span", [content], fullStyle, css); - if (title) token.title = title; - return builder.content.appendChild(token); - } - builder.content.appendChild(content); - } - - function splitSpaces(text, trailingBefore) { - if (text.length > 1 && !/ /.test(text)) return text - var spaceBefore = trailingBefore, result = "" - for (var i = 0; i < text.length; i++) { - var ch = text.charAt(i) - if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32)) - ch = "\u00a0" - result += ch - spaceBefore = ch == " " - } - return result - } - - // Work around nonsense dimensions being reported for stretches of - // right-to-left text. - function buildTokenBadBidi(inner, order) { - return function(builder, text, style, startStyle, endStyle, title, css) { - style = style ? style + " cm-force-border" : "cm-force-border"; - var start = builder.pos, end = start + text.length; - for (;;) { - // Find the part that overlaps with the start of this text - for (var i = 0; i < order.length; i++) { - var part = order[i]; - if (part.to > start && part.from <= start) break; - } - if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css); - inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css); - startStyle = null; - text = text.slice(part.to - start); - start = part.to; - } - }; - } - - function buildCollapsedSpan(builder, size, marker, ignoreWidget) { - var widget = !ignoreWidget && marker.widgetNode; - if (widget) builder.map.push(builder.pos, builder.pos + size, widget); - if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { - if (!widget) - widget = builder.content.appendChild(document.createElement("span")); - widget.setAttribute("cm-marker", marker.id); - } - if (widget) { - builder.cm.display.input.setUneditable(widget); - builder.content.appendChild(widget); - } - builder.pos += size; - builder.trailingSpace = false - } - - // Outputs a number of spans to make up a line, taking highlighting - // and marked text into account. - function insertLineContent(line, builder, styles) { - var spans = line.markedSpans, allText = line.text, at = 0; - if (!spans) { - for (var i = 1; i < styles.length; i+=2) - builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options)); - return; - } - - var len = allText.length, pos = 0, i = 1, text = "", style, css; - var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed; - for (;;) { - if (nextChange == pos) { // Update current marker set - spanStyle = spanEndStyle = spanStartStyle = title = css = ""; - collapsed = null; nextChange = Infinity; - var foundBookmarks = [], endStyles - for (var j = 0; j < spans.length; ++j) { - var sp = spans[j], m = sp.marker; - if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { - foundBookmarks.push(m); - } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { - if (sp.to != null && sp.to != pos && nextChange > sp.to) { - nextChange = sp.to; - spanEndStyle = ""; - } - if (m.className) spanStyle += " " + m.className; - if (m.css) css = (css ? css + ";" : "") + m.css; - if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle; - if (m.endStyle && sp.to == nextChange) (endStyles || (endStyles = [])).push(m.endStyle, sp.to) - if (m.title && !title) title = m.title; - if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) - collapsed = sp; - } else if (sp.from > pos && nextChange > sp.from) { - nextChange = sp.from; - } - } - if (endStyles) for (var j = 0; j < endStyles.length; j += 2) - if (endStyles[j + 1] == nextChange) spanEndStyle += " " + endStyles[j] - - if (!collapsed || collapsed.from == pos) for (var j = 0; j < foundBookmarks.length; ++j) - buildCollapsedSpan(builder, 0, foundBookmarks[j]); - if (collapsed && (collapsed.from || 0) == pos) { - buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, - collapsed.marker, collapsed.from == null); - if (collapsed.to == null) return; - if (collapsed.to == pos) collapsed = false; - } - } - if (pos >= len) break; - - var upto = Math.min(len, nextChange); - while (true) { - if (text) { - var end = pos + text.length; - if (!collapsed) { - var tokenText = end > upto ? text.slice(0, upto - pos) : text; - builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, - spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css); - } - if (end >= upto) {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); - } - } - } - - // DOCUMENT DATA STRUCTURE - - // By default, updates that start and end at the beginning of a line - // are treated specially, in order to make the association of line - // widgets and marker elements with the text behave more intuitive. - function isWholeLineUpdate(doc, change) { - return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && - (!doc.cm || doc.cm.options.wholeLineUpdateBefore); - } - - // Perform a change on the document data structure. - function updateDoc(doc, change, markedSpans, estimateHeight) { - function spansFor(n) {return markedSpans ? markedSpans[n] : null;} - function update(line, text, spans) { - updateLine(line, text, spans, estimateHeight); - signalLater(line, "change", line, change); - } - function linesFor(start, end) { - for (var i = start, result = []; i < end; ++i) - result.push(new Line(text[i], spansFor(i), estimateHeight)); - return result; - } - - var from = change.from, to = change.to, text = change.text; - var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); - var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; - - // Adjust the line structure - if (change.full) { - doc.insert(0, linesFor(0, text.length)); - doc.remove(text.length, doc.size - text.length); - } else if (isWholeLineUpdate(doc, change)) { - // This is a whole-line replace. Treated specially to make - // sure line objects move the way they are supposed to. - var added = linesFor(0, text.length - 1); - update(lastLine, lastLine.text, lastSpans); - if (nlines) doc.remove(from.line, nlines); - if (added.length) doc.insert(from.line, added); - } else if (firstLine == lastLine) { - if (text.length == 1) { - update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); - } else { - var added = linesFor(1, text.length - 1); - added.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); - } - } else if (text.length == 1) { - update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); - doc.remove(from.line + 1, nlines); - } else { - update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); - update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); - var added = linesFor(1, text.length - 1); - if (nlines > 1) doc.remove(from.line + 1, nlines - 1); - doc.insert(from.line + 1, added); - } - - signalLater(doc, "change", doc, change); - } - - // The document is represented as a BTree consisting of leaves, with - // chunk of lines in them, and branches, with up to ten leaves or - // other branch nodes below them. The top node is always a branch - // node, and is the document object itself (meaning it has - // additional methods and properties). - // - // All nodes have parent links. The tree is used both to go from - // line numbers to line objects, and to go from objects to numbers. - // It also indexes by height, and is used to convert between height - // and line object, and to find the total height of the document. - // - // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html - - function LeafChunk(lines) { - this.lines = lines; - this.parent = null; - for (var i = 0, height = 0; i < lines.length; ++i) { - lines[i].parent = this; - height += lines[i].height; - } - this.height = height; - } - - LeafChunk.prototype = { - chunkSize: function() { return this.lines.length; }, - // Remove the n lines at offset 'at'. - removeInner: function(at, n) { - for (var i = at, e = at + n; i < e; ++i) { - var line = this.lines[i]; - this.height -= line.height; - cleanUpLine(line); - signalLater(line, "delete"); - } - this.lines.splice(at, n); - }, - // Helper used to collapse a small branch into a single leaf. - collapse: function(lines) { - lines.push.apply(lines, this.lines); - }, - // Insert the given array of lines at offset 'at', count them as - // having the given height. - 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; - }, - // Used to iterate over a part of the tree. - iterN: function(at, n, op) { - for (var e = at + n; at < e; ++at) - if (op(this.lines[at])) return true; - } - }; - - function BranchChunk(children) { - this.children = children; - var size = 0, height = 0; - for (var 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; - } - - BranchChunk.prototype = { - chunkSize: function() { return this.size; }, - removeInner: function(at, n) { - this.size -= n; - for (var 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; - child.removeInner(at, rm); - this.height -= oldHeight - child.height; - if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } - if ((n -= rm) == 0) break; - at = 0; - } else at -= sz; - } - // If the result is smaller than 25 lines, ensure that it is a - // single leaf node. - if (this.size - n < 25 && - (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { - var lines = []; - 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) { - child.insertInner(at, lines, height); - if (child.lines && child.lines.length > 50) { - // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced. - // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest. - var remaining = child.lines.length % 25 + 25 - for (var 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; - } - }, - // When a node has grown, check whether it should be split. - maybeSpill: function() { - if (this.children.length <= 10) return; - var me = this; - do { - var spilled = me.children.splice(me.children.length - 5, 5); - var sibling = new BranchChunk(spilled); - if (!me.parent) { // Become the parent node - var copy = new BranchChunk(me.children); - copy.parent = me; - me.children = [copy, sibling]; - me = copy; - } else { - me.size -= sibling.size; - me.height -= sibling.height; - var myIndex = indexOf(me.parent.children, me); - me.parent.children.splice(myIndex + 1, 0, sibling); - } - sibling.parent = me.parent; - } while (me.children.length > 10); - 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 true; - if ((n -= used) == 0) break; - at = 0; - } else at -= sz; - } - } - }; - - var nextDocId = 0; - var Doc = CodeMirror.Doc = function(text, mode, firstLine, lineSep) { - if (!(this instanceof Doc)) return new Doc(text, mode, firstLine, lineSep); - if (firstLine == null) firstLine = 0; - - BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); - this.first = firstLine; - this.scrollTop = this.scrollLeft = 0; - this.cantEdit = false; - this.cleanGeneration = 1; - this.frontier = firstLine; - var start = Pos(firstLine, 0); - this.sel = simpleSelection(start); - this.history = new History(null); - this.id = ++nextDocId; - this.modeOption = mode; - this.lineSep = lineSep; - this.extend = false; - - if (typeof text == "string") text = this.splitLines(text); - updateDoc(this, {from: start, to: start, text: text}); - setSelection(this, simpleSelection(start), sel_dontScroll); - }; - - Doc.prototype = createObj(BranchChunk.prototype, { - constructor: Doc, - // Iterate over the document. Supports two forms -- with only one - // argument, it calls that for each line in the document. With - // three, it iterates over the range given by the first two (with - // the second being non-inclusive). - iter: function(from, to, op) { - if (op) this.iterN(from - this.first, to - from, op); - else this.iterN(this.first, this.first + this.size, from); - }, - - // Non-public interface for adding and removing lines. - insert: function(at, lines) { - var height = 0; - for (var 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); }, - - // From here, the methods are part of the public interface. Most - // are also available from CodeMirror (editor) instances. - - getValue: function(lineSep) { - var lines = getLines(this, this.first, this.first + this.size); - if (lineSep === false) return lines; - return 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: true}, true); - setSelection(this, simpleSelection(top)); - }), - replaceRange: function(code, from, to, origin) { - from = clipPos(this, from); - to = to ? clipPos(this, to) : from; - replaceRange(this, code, from, to, origin); - }, - getRange: function(from, to, lineSep) { - var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); - if (lineSep === false) return lines; - return lines.join(lineSep || this.lineSeparator()); - }, - - getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;}, - - getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);}, - getLineNumber: function(line) {return lineNo(line);}, - - getLineHandleVisualStart: function(line) { - if (typeof line == "number") line = getLine(this, line); - return visualLine(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(), pos; - if (start == null || start == "head") pos = range.head; - else if (start == "anchor") pos = range.anchor; - else if (start == "end" || start == "to" || start === false) pos = range.to(); - else pos = range.from(); - return pos; - }, - listSelections: function() { return this.sel.ranges; }, - somethingSelected: function() {return this.sel.somethingSelected();}, - - setCursor: docMethodOp(function(line, ch, options) { - setSimpleSelection(this, clipPos(this, typeof line == "number" ? 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) { - var heads = map(this.sel.ranges, f); - extendSelections(this, clipPosArray(this, heads), options); - }), - setSelections: docMethodOp(function(ranges, primary, options) { - if (!ranges.length) return; - for (var i = 0, out = []; i < ranges.length; i++) - out[i] = new Range(clipPos(this, ranges[i].anchor), - clipPos(this, ranges[i].head)); - if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex); - setSelection(this, normalizeSelection(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(ranges, ranges.length - 1), options); - }), - - getSelection: function(lineSep) { - var ranges = this.sel.ranges, lines; - for (var i = 0; i < ranges.length; i++) { - var sel = getBetween(this, ranges[i].from(), ranges[i].to()); - lines = lines ? lines.concat(sel) : sel; - } - if (lineSep === false) return lines; - else return lines.join(lineSep || this.lineSeparator()); - }, - getSelections: function(lineSep) { - var parts = [], ranges = this.sel.ranges; - for (var i = 0; i < ranges.length; i++) { - var sel = getBetween(this, ranges[i].from(), ranges[i].to()); - if (lineSep !== false) sel = sel.join(lineSep || this.lineSeparator()); - parts[i] = sel; - } - return parts; - }, - replaceSelection: function(code, collapse, origin) { - var dup = []; - for (var i = 0; i < this.sel.ranges.length; i++) - dup[i] = code; - this.replaceSelections(dup, collapse, origin || "+input"); - }, - replaceSelections: docMethodOp(function(code, collapse, origin) { - var changes = [], sel = this.sel; - for (var 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}; - } - var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); - for (var i = changes.length - 1; i >= 0; i--) - makeChange(this, changes[i]); - if (newSel) setSelectionReplaceHistory(this, newSel); - else if (this.cm) ensureCursorVisible(this.cm); - }), - undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}), - redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}), - undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}), - redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}), - - setExtending: function(val) {this.extend = val;}, - getExtending: function() {return this.extend;}, - - historySize: function() { - var hist = this.history, done = 0, undone = 0; - for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done; - for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone; - return {undo: done, redo: undone}; - }, - clearHistory: function() {this.history = new History(this.history.maxGeneration);}, - - markClean: function() { - this.cleanGeneration = this.changeGeneration(true); - }, - changeGeneration: function(forceSplit) { - if (forceSplit) - this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; - return 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, true); - hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); - }, - - addLineClass: docMethodOp(function(handle, where, cls) { - return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) { - var prop = where == "text" ? "textClass" - : where == "background" ? "bgClass" - : where == "gutter" ? "gutterClass" : "wrapClass"; - if (!line[prop]) line[prop] = cls; - else if (classTest(cls).test(line[prop])) return false; - else line[prop] += " " + cls; - return true; - }); - }), - removeLineClass: docMethodOp(function(handle, where, cls) { - return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) { - var prop = where == "text" ? "textClass" - : where == "background" ? "bgClass" - : where == "gutter" ? "gutterClass" : "wrapClass"; - var cur = line[prop]; - if (!cur) return false; - else if (cls == null) line[prop] = null; - else { - var found = cur.match(classTest(cls)); - if (!found) return false; - var end = found.index + found[0].length; - line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; - } - return true; - }); - }), - - addLineWidget: docMethodOp(function(handle, node, options) { - return addLineWidget(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) { - var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), - insertLeft: options && options.insertLeft, - clearWhenEmpty: false, shared: options && options.shared, - handleMouseEvents: options && options.handleMouseEvents}; - pos = clipPos(this, pos); - return markText(this, pos, pos, realOpts, "bookmark"); - }, - findMarksAt: function(pos) { - pos = clipPos(this, pos); - var markers = [], spans = getLine(this, pos.line).markedSpans; - if (spans) for (var i = 0; i < spans.length; ++i) { - var span = spans[i]; - if ((span.from == null || span.from <= pos.ch) && - (span.to == null || 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; - 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]; - if (!(span.to != null && lineNo == from.line && from.ch >= span.to || - span.from == null && lineNo != from.line || - span.from != null && lineNo == to.line && span.from >= to.ch) && - (!filter || filter(span.marker))) - found.push(span.marker.parent || span.marker); - } - ++lineNo; - }); - return found; - }, - getAllMarks: function() { - var markers = []; - this.iter(function(line) { - var sps = line.markedSpans; - if (sps) for (var i = 0; i < sps.length; ++i) - if (sps[i].from != null) markers.push(sps[i].marker); - }); - return markers; - }, - - posFromIndex: function(off) { - var ch, lineNo = this.first, sepSize = this.lineSeparator().length; - this.iter(function(line) { - var sz = line.text.length + sepSize; - if (sz > off) { ch = off; return true; } - off -= sz; - ++lineNo; - }); - return clipPos(this, Pos(lineNo, ch)); - }, - indexFromPos: function (coords) { - coords = clipPos(this, coords); - var index = coords.ch; - if (coords.line < this.first || coords.ch < 0) return 0; - var sepSize = this.lineSeparator().length; - this.iter(this.first, coords.line, function (line) { - index += line.text.length + sepSize; - }); - return index; - }, - - copy: function(copyHistory) { - var doc = new Doc(getLines(this, this.first, this.first + this.size), - this.modeOption, this.first, this.lineSep); - doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; - doc.sel = this.sel; - doc.extend = false; - if (copyHistory) { - doc.history.undoDepth = this.history.undoDepth; - doc.setHistory(this.getHistory()); - } - return doc; - }, - - linkedDoc: function(options) { - if (!options) options = {}; - var from = this.first, to = this.first + this.size; - if (options.from != null && options.from > from) from = options.from; - if (options.to != null && options.to < to) to = options.to; - var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep); - if (options.sharedHist) copy.history = this.history; - (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}); - copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]; - copySharedMarkers(copy, findSharedMarkers(this)); - return copy; - }, - unlinkDoc: function(other) { - if (other instanceof CodeMirror) other = other.doc; - if (this.linked) for (var i = 0; i < this.linked.length; ++i) { - var link = this.linked[i]; - if (link.doc != other) continue; - this.linked.splice(i, 1); - other.unlinkDoc(this); - detachSharedMarkers(findSharedMarkers(this)); - break; - } - // If the histories were shared, split them again - if (other.history == this.history) { - var splitIds = [other.id]; - linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true); - 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) { - if (this.lineSep) return str.split(this.lineSep); - return splitLinesAuto(str); - }, - lineSeparator: function() { return this.lineSep || "\n"; } - }); - - // Public alias. - Doc.prototype.eachLine = Doc.prototype.iter; - - // Set up methods on CodeMirror's prototype to redirect to the editor's document. - var dontDelegate = "iter insert remove copy getEditor constructor".split(" "); - for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) - CodeMirror.prototype[prop] = (function(method) { - return function() {return method.apply(this.doc, arguments);}; - })(Doc.prototype[prop]); - - eventMixin(Doc); - - // Call f for all linked documents. - function linkedDocs(doc, f, sharedHistOnly) { - function propagate(doc, skip, sharedHist) { - if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) { - var rel = doc.linked[i]; - if (rel.doc == skip) continue; - var shared = sharedHist && rel.sharedHist; - if (sharedHistOnly && !shared) continue; - f(rel.doc, shared); - propagate(rel.doc, doc, shared); - } - } - propagate(doc, null, true); - } - - // Attach a document to an editor. - function attachDoc(cm, doc) { - if (doc.cm) throw new Error("This document is already in use."); - cm.doc = doc; - doc.cm = cm; - estimateLineHeights(cm); - loadMode(cm); - if (!cm.options.lineWrapping) findMaxLine(cm); - cm.options.mode = doc.modeOption; - regChange(cm); - } - - // LINE UTILITIES - - // Find the line object corresponding to the given line number. - function getLine(doc, n) { - n -= doc.first; - if (n < 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]; - } - - // Get the part of a document between two positions, as an array of - // strings. - function getBetween(doc, start, end) { - var out = [], n = start.line; - doc.iter(start.line, end.line + 1, function(line) { - var text = line.text; - if (n == end.line) text = text.slice(0, end.ch); - if (n == start.line) text = text.slice(start.ch); - out.push(text); - ++n; - }); - return out; - } - // Get the lines between from and to, as array of strings. - function getLines(doc, from, to) { - var out = []; - doc.iter(from, to, function(line) { out.push(line.text); }); - return out; - } - - // Update the height of a line, propagating the height change - // upwards to parent nodes. - function updateLineHeight(line, height) { - var diff = height - line.height; - if (diff) for (var n = line; n; n = n.parent) n.height += diff; - } - - // Given a line object, find its line number by walking up through - // its parent links. - function lineNo(line) { - if (line.parent == null) return null; - var cur = line.parent, no = indexOf(cur.lines, line); - for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { - for (var i = 0;; ++i) { - if (chunk.children[i] == cur) break; - no += chunk.children[i].chunkSize(); - } - } - return no + cur.first; - } - - // Find the line at the given vertical position, using the height - // information in the document tree. - function lineAtHeight(chunk, h) { - var n = chunk.first; - outer: do { - for (var i = 0; i < chunk.children.length; ++i) { - var child = chunk.children[i], 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 line = chunk.lines[i], lh = line.height; - if (h < lh) break; - h -= lh; - } - return n + i; - } - - - // Find the height above the given line. - function heightAtLine(lineObj) { - lineObj = visualLine(lineObj); - - var h = 0, chunk = lineObj.parent; - for (var i = 0; i < chunk.lines.length; ++i) { - var line = chunk.lines[i]; - if (line == lineObj) break; - else h += line.height; - } - for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { - for (var i = 0; i < p.children.length; ++i) { - var cur = p.children[i]; - if (cur == chunk) break; - else h += cur.height; - } - } - return h; - } - - // Get the bidi ordering for the given line (and cache it). Returns - // false for lines that are fully left-to-right, and an array of - // BidiSpan objects otherwise. - function getOrder(line) { - var order = line.order; - if (order == null) order = line.order = bidiOrdering(line.text); - return order; - } - - // HISTORY - - function History(startGen) { - // Arrays of change events and selections. Doing something adds an - // event to done and clears undo. Undoing moves events from done - // to undone, redoing moves them in the other direction. - this.done = []; this.undone = []; - this.undoDepth = Infinity; - // Used to track when changes can be merged into a single undo - // event - this.lastModTime = this.lastSelTime = 0; - this.lastOp = this.lastSelOp = null; - this.lastOrigin = this.lastSelOrigin = null; - // Used by the isClean() method - this.generation = this.maxGeneration = startGen || 1; - } - - // Create a history change event from an updateDoc-style change - // object. - function historyChangeFromChange(doc, change) { - var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}; - attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); - linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true); - return histChange; - } - - // Pop all selection events off the end of a history array. Stop at - // a change event. - function clearSelectionEvents(array) { - while (array.length) { - var last = lst(array); - if (last.ranges) array.pop(); - else break; - } - } - - // Find the top change event in the history. Pop off selection - // events that are in the way. - function lastChangeEvent(hist, force) { - if (force) { - clearSelectionEvents(hist.done); - return lst(hist.done); - } else if (hist.done.length && !lst(hist.done).ranges) { - return lst(hist.done); - } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { - hist.done.pop(); - return lst(hist.done); - } - } - - // Register a change in the history. Merges changes that are within - // a single operation, or are close together with an origin that - // allows merging (starting with "+") into a single event. - function addChangeToHistory(doc, change, selAfter, opId) { - var hist = doc.history; - hist.undone.length = 0; - var time = +new Date, cur; - - if ((hist.lastOp == opId || - hist.lastOrigin == change.origin && change.origin && - ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) || - change.origin.charAt(0) == "*")) && - (cur = lastChangeEvent(hist, hist.lastOp == opId))) { - // Merge this change into the last event - var last = lst(cur.changes); - if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { - // Optimized case for simple insertion -- don't want to add - // new changesets for every character typed - last.to = changeEnd(change); - } else { - // Add new sub-event - cur.changes.push(historyChangeFromChange(doc, change)); - } - } else { - // Can not be merged, start a new event. - var before = lst(hist.done); - if (!before || !before.ranges) - pushSelectionToHistory(doc.sel, hist.done); - cur = {changes: [historyChangeFromChange(doc, change)], - generation: hist.generation}; - hist.done.push(cur); - while (hist.done.length > hist.undoDepth) { - hist.done.shift(); - if (!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; - - if (!last) signal(doc, "historyAdded"); - } - - function selectionEventCanBeMerged(doc, origin, prev, sel) { - var ch = origin.charAt(0); - return ch == "*" || - ch == "+" && - prev.ranges.length == sel.ranges.length && - prev.somethingSelected() == sel.somethingSelected() && - new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500); - } - - // Called whenever the selection changes, sets the new selection as - // the pending selection in the history, and pushes the old pending - // selection into the 'done' array when it was significantly - // different (in number of selected ranges, emptiness, or time). - function addSelectionToHistory(doc, sel, opId, options) { - var hist = doc.history, origin = options && options.origin; - - // A new event is started when the previous origin does not match - // the current, or the origins don't allow matching. Origins - // starting with * are always merged, those starting with + are - // merged when similar and close together in time. - if (opId == hist.lastSelOp || - (origin && hist.lastSelOrigin == origin && - (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || - selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) - hist.done[hist.done.length - 1] = sel; - else - pushSelectionToHistory(sel, hist.done); - - hist.lastSelTime = +new Date; - hist.lastSelOrigin = origin; - hist.lastSelOp = opId; - if (options && options.clearRedo !== false) - clearSelectionEvents(hist.undone); - } - - function pushSelectionToHistory(sel, dest) { - var top = lst(dest); - if (!(top && top.ranges && top.equals(sel))) - dest.push(sel); - } - - // Used to store marked span information in the history. - 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) { - if (line.markedSpans) - (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; - ++n; - }); - } - - // When un/re-doing restores text containing marked spans, those - // that have been explicitly cleared should not be restored. - function removeClearedSpans(spans) { - if (!spans) return null; - for (var i = 0, out; i < spans.length; ++i) { - if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); } - else if (out) out.push(spans[i]); - } - return !out ? spans : out.length ? out : null; - } - - // Retrieve and filter the old marked spans stored in a change event. - function getOldSpans(doc, change) { - var found = change["spans_" + doc.id]; - if (!found) return null; - for (var i = 0, nw = []; i < change.text.length; ++i) - nw.push(removeClearedSpans(found[i])); - return nw; - } - - // Used both to provide a JSON-safe object in .getHistory, and, when - // detaching a document, to split the history in two - function copyHistoryArray(events, newGroup, instantiateSel) { - for (var i = 0, copy = []; i < events.length; ++i) { - var event = events[i]; - if (event.ranges) { - copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); - continue; - } - var changes = event.changes, newChanges = []; - copy.push({changes: newChanges}); - for (var j = 0; j < changes.length; ++j) { - var change = changes[j], m; - newChanges.push({from: change.from, to: change.to, text: change.text}); - if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) { - if (indexOf(newGroup, Number(m[1])) > -1) { - lst(newChanges)[prop] = change[prop]; - delete change[prop]; - } - } - } - } - return copy; - } - - // Rebasing/resetting history to deal with externally-sourced changes - - function rebaseHistSelSingle(pos, from, to, diff) { - if (to < pos.line) { - pos.line += diff; - } else if (from < pos.line) { - pos.line = from; - pos.ch = 0; - } - } - - // Tries to rebase an array of history events given a change in the - // document. If the change touches the same lines as the event, the - // event, and everything 'behind' it, is discarded. If the change is - // before the event, the event's positions are updated. Uses a - // copy-on-write scheme for the positions, to avoid having to - // reallocate them all on every rebase, but also avoid problems with - // shared position objects being unsafely updated. - function rebaseHistArray(array, from, to, diff) { - for (var i = 0; i < array.length; ++i) { - var sub = array[i], ok = true; - if (sub.ranges) { - if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; } - 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); - } - continue; - } - for (var j = 0; j < sub.changes.length; ++j) { - var cur = sub.changes[j]; - 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 = false; - break; - } - } - if (!ok) { - array.splice(0, i + 1); - i = 0; - } - } - } - - function rebaseHist(hist, change) { - var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1; - rebaseHistArray(hist.done, from, to, diff); - rebaseHistArray(hist.undone, from, to, diff); - } - - // EVENT UTILITIES - - // Due to the fact that we still support jurassic IE versions, some - // compatibility wrappers are needed. - - var e_preventDefault = CodeMirror.e_preventDefault = function(e) { - if (e.preventDefault) e.preventDefault(); - else e.returnValue = false; - }; - var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) { - if (e.stopPropagation) e.stopPropagation(); - else e.cancelBubble = true; - }; - function e_defaultPrevented(e) { - return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false; - } - var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);}; - - function e_target(e) {return e.target || e.srcElement;} - function e_button(e) { - var b = e.which; - if (b == null) { - if (e.button & 1) b = 1; - else if (e.button & 2) b = 3; - else if (e.button & 4) b = 2; - } - if (mac && e.ctrlKey && b == 1) b = 3; - return b; - } - - // EVENT HANDLING - - // Lightweight event framework. on/off also work on DOM nodes, - // registering native DOM handlers. - - var on = CodeMirror.on = function(emitter, type, f) { - if (emitter.addEventListener) - emitter.addEventListener(type, f, false); - else if (emitter.attachEvent) - emitter.attachEvent("on" + type, f); - else { - var map = emitter._handlers || (emitter._handlers = {}); - var arr = map[type] || (map[type] = []); - arr.push(f); - } - }; - - var noHandlers = [] - function getHandlers(emitter, type, copy) { - var arr = emitter._handlers && emitter._handlers[type] - if (copy) return arr && arr.length > 0 ? arr.slice() : noHandlers - else return arr || noHandlers - } - - var off = CodeMirror.off = function(emitter, type, f) { - if (emitter.removeEventListener) - emitter.removeEventListener(type, f, false); - else if (emitter.detachEvent) - emitter.detachEvent("on" + type, f); - else { - var handlers = getHandlers(emitter, type, false) - for (var i = 0; i < handlers.length; ++i) - if (handlers[i] == f) { handlers.splice(i, 1); break; } - } - }; - - var signal = CodeMirror.signal = function(emitter, type /*, values...*/) { - var handlers = getHandlers(emitter, type, true) - if (!handlers.length) return; - var args = Array.prototype.slice.call(arguments, 2); - for (var i = 0; i < handlers.length; ++i) handlers[i].apply(null, args); - }; - - var orphanDelayedCallbacks = null; - - // Often, we want to signal events at a point where we are in the - // middle of some work, but don't want the handler to start calling - // other methods on the editor, which might be in an inconsistent - // state or simply not expect any other events to happen. - // signalLater looks whether there are any handlers, and schedules - // them to be executed when the last operation ends, or, if no - // operation is active, when a timeout fires. - function signalLater(emitter, type /*, values...*/) { - var arr = getHandlers(emitter, type, false) - if (!arr.length) return; - var args = Array.prototype.slice.call(arguments, 2), list; - if (operationGroup) { - list = operationGroup.delayedCallbacks; - } else if (orphanDelayedCallbacks) { - list = orphanDelayedCallbacks; - } else { - list = orphanDelayedCallbacks = []; - setTimeout(fireOrphanDelayed, 0); - } - function bnd(f) {return function(){f.apply(null, args);};}; - for (var i = 0; i < arr.length; ++i) - list.push(bnd(arr[i])); - } - - function fireOrphanDelayed() { - var delayed = orphanDelayedCallbacks; - orphanDelayedCallbacks = null; - for (var i = 0; i < delayed.length; ++i) delayed[i](); - } - - // The DOM events that CodeMirror handles can be overridden by - // registering a (non-DOM) handler on the editor for the event name, - // and preventDefault-ing the event in that handler. - function signalDOMEvent(cm, e, override) { - if (typeof e == "string") - e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; - signal(cm, override || e.type, cm, e); - return e_defaultPrevented(e) || e.codemirrorIgnore; - } - - function signalCursorActivity(cm) { - var arr = cm._handlers && cm._handlers.cursorActivity; - if (!arr) return; - var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []); - for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1) - set.push(arr[i]); - } - - function hasHandler(emitter, type) { - return getHandlers(emitter, type).length > 0 - } - - // Add on and off methods to a constructor's prototype, to make - // registering events on such objects more convenient. - function eventMixin(ctor) { - ctor.prototype.on = function(type, f) {on(this, type, f);}; - ctor.prototype.off = function(type, f) {off(this, type, f);}; - } - - // MISC UTILITIES - - // Number of pixels added to scroller and sizer to hide scrollbar - var scrollerGap = 30; - - // Returned or thrown by various protocols to signal 'I'm not - // handling this'. - var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}}; - - // Reused option objects for setSelection & friends - var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"}; - - function Delayed() {this.id = null;} - Delayed.prototype.set = function(ms, f) { - clearTimeout(this.id); - this.id = setTimeout(f, ms); - }; - - // Counts the column offset in a string, taking tabs into account. - // Used mostly to find indentation. - var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) { - if (end == null) { - end = string.search(/[^\s\u00a0]/); - if (end == -1) end = string.length; - } - for (var i = startIndex || 0, n = startValue || 0;;) { - var nextTab = string.indexOf("\t", i); - if (nextTab < 0 || nextTab >= end) - return n + (end - i); - n += nextTab - i; - n += tabSize - (n % tabSize); - i = nextTab + 1; - } - }; - - // The inverse of countColumn -- find the offset that corresponds to - // a particular column. - var findColumn = CodeMirror.findColumn = function(string, goal, tabSize) { - for (var pos = 0, col = 0;;) { - var nextTab = string.indexOf("\t", pos); - if (nextTab == -1) nextTab = string.length; - var skipped = nextTab - pos; - if (nextTab == string.length || col + skipped >= goal) - return pos + Math.min(skipped, goal - col); - col += nextTab - pos; - col += tabSize - (col % tabSize); - pos = nextTab + 1; - if (col >= goal) return pos; - } - } - - var spaceStrs = [""]; - function spaceStr(n) { - while (spaceStrs.length <= n) - spaceStrs.push(lst(spaceStrs) + " "); - return spaceStrs[n]; - } - - function lst(arr) { return arr[arr.length-1]; } - - var selectInput = function(node) { node.select(); }; - if (ios) // Mobile Safari apparently has a bug where select() is broken. - selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; - else if (ie) // Suppress mysterious IE10 errors - selectInput = function(node) { try { node.select(); } catch(_e) {} }; - - function indexOf(array, elt) { - for (var i = 0; i < array.length; ++i) - if (array[i] == elt) return i; - return -1; - } - function map(array, f) { - var out = []; - for (var i = 0; i < array.length; i++) out[i] = f(array[i], i); - return out; - } - - function insertSorted(array, value, score) { - var pos = 0, priority = score(value) - while (pos < array.length && score(array[pos]) <= priority) pos++ - array.splice(pos, 0, value) - } - - function nothing() {} - - function createObj(base, props) { - var inst; - if (Object.create) { - inst = Object.create(base); - } else { - nothing.prototype = base; - inst = new nothing(); - } - if (props) copyObj(props, inst); - return inst; - }; - - function copyObj(obj, target, overwrite) { - if (!target) target = {}; - for (var prop in obj) - if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) - target[prop] = obj[prop]; - return target; - } - - function bind(f) { - var args = Array.prototype.slice.call(arguments, 1); - return function(){return f.apply(null, args);}; - } - - var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; - var isWordCharBasic = CodeMirror.isWordChar = function(ch) { - return /\w/.test(ch) || ch > "\x80" && - (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)); - }; - function isWordChar(ch, helper) { - if (!helper) return isWordCharBasic(ch); - if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true; - return helper.test(ch); - } - - function isEmpty(obj) { - for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false; - return true; - } - - // Extending unicode characters. A series of a non-extending char + - // any number of extending chars is treated as a single unit as far - // as editing and measuring is concerned. This is not fully correct, - // since some scripts/fonts/browsers also treat other configurations - // of code points as a group. - 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 ch.charCodeAt(0) >= 768 && extendingChars.test(ch); } - - // DOM UTILITIES - - function elt(tag, content, className, style) { - var e = document.createElement(tag); - if (className) e.className = className; - if (style) e.style.cssText = style; - if (typeof content == "string") e.appendChild(document.createTextNode(content)); - else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]); - return e; - } - - var range; - if (document.createRange) range = function(node, start, end, endNode) { - var r = document.createRange(); - r.setEnd(endNode || node, end); - r.setStart(node, start); - return r; - }; - else range = function(node, start, end) { - var r = document.body.createTextRange(); - try { r.moveToElementText(node.parentNode); } - catch(e) { return r; } - r.collapse(true); - r.moveEnd("character", end); - r.moveStart("character", start); - return r; - }; - - function removeChildren(e) { - for (var count = e.childNodes.length; count > 0; --count) - e.removeChild(e.firstChild); - return e; - } - - function removeChildrenAndAdd(parent, e) { - return removeChildren(parent).appendChild(e); - } - - var contains = CodeMirror.contains = function(parent, child) { - if (child.nodeType == 3) // Android browser always returns false when child is a textnode - child = child.parentNode; - if (parent.contains) - return parent.contains(child); - do { - if (child.nodeType == 11) child = child.host; - if (child == parent) return true; - } while (child = child.parentNode); - }; - - function activeElt() { - var activeElement = document.activeElement; - while (activeElement && activeElement.root && activeElement.root.activeElement) - activeElement = activeElement.root.activeElement; - return activeElement; - } - // Older versions of IE throws unspecified error when touching - // document.activeElement in some cases (during loading, in iframe) - if (ie && ie_version < 11) activeElt = function() { - try { return document.activeElement; } - catch(e) { return document.body; } - }; - - function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); } - var rmClass = CodeMirror.rmClass = function(node, cls) { - var current = node.className; - var match = classTest(cls).exec(current); - if (match) { - var after = current.slice(match.index + match[0].length); - node.className = current.slice(0, match.index) + (after ? match[1] + after : ""); - } - }; - var addClass = CodeMirror.addClass = function(node, cls) { - var current = node.className; - if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls; - }; - function joinClasses(a, b) { - var as = a.split(" "); - for (var i = 0; i < as.length; i++) - if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i]; - return b; - } - - // WINDOW-WIDE EVENTS - - // These must be handled carefully, because naively registering a - // handler for each editor will cause the editors to never be - // garbage collected. - - function forEachCodeMirror(f) { - if (!document.body.getElementsByClassName) return; - var byClass = document.body.getElementsByClassName("CodeMirror"); - for (var i = 0; i < byClass.length; i++) { - var cm = byClass[i].CodeMirror; - if (cm) f(cm); - } - } - - var globalsRegistered = false; - function ensureGlobalHandlers() { - if (globalsRegistered) return; - registerGlobalHandlers(); - globalsRegistered = true; - } - function registerGlobalHandlers() { - // When the window resizes, we need to refresh active editors. - var resizeTimer; - on(window, "resize", function() { - if (resizeTimer == null) resizeTimer = setTimeout(function() { - resizeTimer = null; - forEachCodeMirror(onResize); - }, 100); - }); - // When the window loses focus, we want to show the editor as blurred - on(window, "blur", function() { - forEachCodeMirror(onBlur); - }); - } - - // FEATURE DETECTION - - // Detect drag-and-drop - var dragAndDrop = function() { - // There is *some* kind of drag-and-drop support in IE6-8, but I - // couldn't get it to work yet. - if (ie && ie_version < 9) return false; - var div = elt('div'); - return "draggable" in div || "dragDrop" in div; - }(); - - var zwspSupported; - function zeroWidthElement(measure) { - if (zwspSupported == null) { - var test = elt("span", "\u200b"); - removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); - if (measure.firstChild.offsetHeight != 0) - zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); - } - var node = zwspSupported ? elt("span", "\u200b") : - elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); - node.setAttribute("cm-text", ""); - return node; - } - - // Feature-detect IE's crummy client rect reporting for bidi text - var badBidiRects; - function hasBadBidiRects(measure) { - if (badBidiRects != null) return badBidiRects; - var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")); - var r0 = range(txt, 0, 1).getBoundingClientRect(); - var r1 = range(txt, 1, 2).getBoundingClientRect(); - removeChildren(measure); - if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780) - return badBidiRects = (r1.right - r0.right < 3); - } - - // See if "".split is the broken IE version, if so, provide an - // alternative way to split lines. - var splitLinesAuto = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) { - var pos = 0, result = [], l = string.length; - while (pos <= l) { - var nl = string.indexOf("\n", pos); - if (nl == -1) nl = string.length; - var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); - var rt = line.indexOf("\r"); - if (rt != -1) { - result.push(line.slice(0, rt)); - pos += rt + 1; - } else { - result.push(line); - pos = nl + 1; - } - } - return result; - } : function(string){return string.split(/\r\n?|\n/);}; - - var hasSelection = window.getSelection ? function(te) { - try { return te.selectionStart != te.selectionEnd; } - catch(e) { return false; } - } : function(te) { - try {var range = te.ownerDocument.selection.createRange();} - catch(e) {} - if (!range || range.parentElement() != te) return false; - return range.compareEndPoints("StartToEnd", range) != 0; - }; - - var hasCopyEvent = (function() { - var e = elt("div"); - if ("oncopy" in e) return true; - e.setAttribute("oncopy", "return;"); - return typeof e.oncopy == "function"; - })(); - - var badZoomedRects = null; - function hasBadZoomedRects(measure) { - if (badZoomedRects != null) return badZoomedRects; - var node = removeChildrenAndAdd(measure, elt("span", "x")); - var normal = node.getBoundingClientRect(); - var fromRange = range(node, 0, 1).getBoundingClientRect(); - return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1; - } - - // KEY NAMES - - var keyNames = CodeMirror.keyNames = { - 3: "Enter", 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: "/", 127: "Delete", - 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", - 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", - 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert" - }; - (function() { - // Number keys - for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i); - // Alphabetic keys - for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i); - // Function keys - for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i; - })(); - - // BIDI HELPERS - - function iterateBidiSections(order, from, to, f) { - if (!order) return f(from, to, "ltr"); - var found = false; - for (var i = 0; i < order.length; ++i) { - var part = order[i]; - if (part.from < to && part.to > from || from == to && part.to == from) { - f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr"); - found = true; - } - } - if (!found) f(from, to, "ltr"); - } - - function bidiLeft(part) { return part.level % 2 ? part.to : part.from; } - function bidiRight(part) { return part.level % 2 ? part.from : part.to; } - - function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; } - function lineRight(line) { - var order = getOrder(line); - if (!order) return line.text.length; - return bidiRight(lst(order)); - } - - function lineStart(cm, lineN) { - var line = getLine(cm.doc, lineN); - var visual = visualLine(line); - if (visual != line) lineN = lineNo(visual); - var order = getOrder(visual); - var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual); - return Pos(lineN, ch); - } - function lineEnd(cm, lineN) { - var merged, line = getLine(cm.doc, lineN); - while (merged = collapsedSpanAtEnd(line)) { - line = merged.find(1, true).line; - lineN = null; - } - var order = getOrder(line); - var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line); - return Pos(lineN == null ? lineNo(line) : lineN, ch); - } - function lineStartSmart(cm, pos) { - var start = lineStart(cm, pos.line); - var line = getLine(cm.doc, start.line); - var order = getOrder(line); - if (!order || order[0].level == 0) { - var firstNonWS = Math.max(0, line.text.search(/\S/)); - var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch; - return Pos(start.line, inWS ? 0 : firstNonWS); - } - return start; - } - - function compareBidiLevel(order, a, b) { - var linedir = order[0].level; - if (a == linedir) return true; - if (b == linedir) return false; - return a < b; - } - var bidiOther; - function getBidiPartAt(order, pos) { - bidiOther = null; - for (var i = 0, found; i < order.length; ++i) { - var cur = order[i]; - if (cur.from < pos && cur.to > pos) return i; - if ((cur.from == pos || cur.to == pos)) { - if (found == null) { - found = i; - } else if (compareBidiLevel(order, cur.level, order[found].level)) { - if (cur.from != cur.to) bidiOther = found; - return i; - } else { - if (cur.from != cur.to) bidiOther = i; - return found; - } - } - } - return found; - } - - function moveInLine(line, pos, dir, byUnit) { - if (!byUnit) return pos + dir; - do pos += dir; - while (pos > 0 && isExtendingChar(line.text.charAt(pos))); - return pos; - } - - // This is needed in order to move 'visually' through bi-directional - // text -- i.e., pressing left should make the cursor go left, even - // when in RTL text. The tricky part is the 'jumps', where RTL and - // LTR text touch each other. This often requires the cursor offset - // to move more than one unit, in order to visually move one unit. - function moveVisually(line, start, dir, byUnit) { - var bidi = getOrder(line); - if (!bidi) return moveLogically(line, start, dir, byUnit); - var pos = getBidiPartAt(bidi, start), part = bidi[pos]; - var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit); - - for (;;) { - if (target > part.from && target < part.to) return target; - if (target == part.from || target == part.to) { - if (getBidiPartAt(bidi, target) == pos) return target; - part = bidi[pos += dir]; - return (dir > 0) == part.level % 2 ? part.to : part.from; - } else { - part = bidi[pos += dir]; - if (!part) return null; - if ((dir > 0) == part.level % 2) - target = moveInLine(line, part.to, -1, byUnit); - else - target = moveInLine(line, part.from, 1, byUnit); - } - } - } - - function moveLogically(line, start, dir, byUnit) { - var target = start + dir; - if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir; - return target < 0 || target > line.text.length ? null : target; - } - - // Bidirectional ordering algorithm - // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm - // that this (partially) implements. - - // One-char codes used for character types: - // L (L): Left-to-Right - // R (R): Right-to-Left - // r (AL): Right-to-Left Arabic - // 1 (EN): European Number - // + (ES): European Number Separator - // % (ET): European Number Terminator - // n (AN): Arabic Number - // , (CS): Common Number Separator - // m (NSM): Non-Spacing Mark - // b (BN): Boundary Neutral - // s (B): Paragraph Separator - // t (S): Segment Separator - // w (WS): Whitespace - // N (ON): Other Neutrals - - // Returns null if characters are ordered as they appear - // (left-to-right), or an array of sections ({from, to, level} - // objects) in the order in which they occur visually. - var bidiOrdering = (function() { - // Character types for codepoints 0 to 0xff - var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; - // Character types for codepoints 0x600 to 0x6ff - var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm"; - function charType(code) { - if (code <= 0xf7) return lowTypes.charAt(code); - else if (0x590 <= code && code <= 0x5f4) return "R"; - else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600); - else if (0x6ee <= code && code <= 0x8ac) return "r"; - else if (0x2000 <= code && code <= 0x200b) return "w"; - else if (code == 0x200c) return "b"; - else return "L"; - } - - var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; - var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; - // Browsers seem to always treat the boundaries of block elements as being L. - var outerType = "L"; - - function BidiSpan(level, from, to) { - this.level = level; - this.from = from; this.to = to; - } - - return function(str) { - if (!bidiRE.test(str)) return false; - var len = str.length, types = []; - for (var i = 0, type; i < len; ++i) - types.push(type = charType(str.charCodeAt(i))); - - // W1. Examine each non-spacing mark (NSM) in the level run, and - // change the type of the NSM to the type of the previous - // character. If the NSM is at the start of the level run, it will - // get the type of sor. - for (var i = 0, prev = outerType; i < len; ++i) { - var type = types[i]; - if (type == "m") types[i] = prev; - else prev = type; - } - - // W2. Search backwards from each instance of a European number - // until the first strong type (R, L, AL, or sor) is found. If an - // AL is found, change the type of the European number to Arabic - // number. - // W3. Change all ALs to R. - for (var i = 0, cur = outerType; i < len; ++i) { - var type = types[i]; - if (type == "1" && cur == "r") types[i] = "n"; - else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; } - } - - // W4. A single European separator between two European numbers - // changes to a European number. A single common separator between - // two numbers of the same type changes to that type. - for (var i = 1, prev = types[0]; i < len - 1; ++i) { - var type = types[i]; - if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1"; - else if (type == "," && prev == types[i+1] && - (prev == "1" || prev == "n")) types[i] = prev; - prev = type; - } - - // W5. A sequence of European terminators adjacent to European - // numbers changes to all European numbers. - // W6. Otherwise, separators and terminators change to Other - // Neutral. - for (var i = 0; i < len; ++i) { - var type = types[i]; - if (type == ",") types[i] = "N"; - else if (type == "%") { - for (var end = i + 1; end < len && types[end] == "%"; ++end) {} - var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N"; - for (var j = i; j < end; ++j) types[j] = replace; - i = end - 1; - } - } - - // W7. Search backwards from each instance of a European number - // until the first strong type (R, L, or sor) is found. If an L is - // found, then change the type of the European number to L. - for (var i = 0, cur = outerType; i < len; ++i) { - var type = types[i]; - if (cur == "L" && type == "1") types[i] = "L"; - else if (isStrong.test(type)) cur = type; - } - - // N1. A sequence of neutrals takes the direction of the - // surrounding strong text if the text on both sides has the same - // direction. European and Arabic numbers act as if they were R in - // terms of their influence on neutrals. Start-of-level-run (sor) - // and end-of-level-run (eor) are used at level run boundaries. - // N2. Any remaining neutrals take the embedding direction. - for (var i = 0; i < len; ++i) { - if (isNeutral.test(types[i])) { - for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {} - var before = (i ? types[i-1] : outerType) == "L"; - var after = (end < len ? types[end] : outerType) == "L"; - var replace = before || after ? "L" : "R"; - for (var j = i; j < end; ++j) types[j] = replace; - i = end - 1; - } - } - - // Here we depart from the documented algorithm, in order to avoid - // building up an actual levels array. Since there are only three - // levels (0, 1, 2) in an implementation that doesn't take - // explicit embedding into account, we can build up the order on - // the fly, without following the level-based algorithm. - var order = [], m; - for (var i = 0; i < len;) { - if (countsAsLeft.test(types[i])) { - var start = i; - for (++i; i < len && countsAsLeft.test(types[i]); ++i) {} - order.push(new BidiSpan(0, start, i)); - } else { - var pos = i, at = order.length; - for (++i; i < len && types[i] != "L"; ++i) {} - for (var j = pos; j < i;) { - if (countsAsNum.test(types[j])) { - if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j)); - var nstart = j; - for (++j; j < i && countsAsNum.test(types[j]); ++j) {} - order.splice(at, 0, new BidiSpan(2, nstart, j)); - pos = j; - } else ++j; - } - if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i)); - } - } - if (order[0].level == 1 && (m = str.match(/^\s+/))) { - order[0].from = m[0].length; - order.unshift(new BidiSpan(0, 0, m[0].length)); - } - if (lst(order).level == 1 && (m = str.match(/\s+$/))) { - lst(order).to -= m[0].length; - order.push(new BidiSpan(0, len - m[0].length, len)); - } - if (order[0].level == 2) - order.unshift(new BidiSpan(1, order[0].to, order[0].to)); - if (order[0].level != lst(order).level) - order.push(new BidiSpan(order[0].level, len, len)); - - return order; - }; - })(); - - // THE END - - CodeMirror.version = "5.19.0"; - - return CodeMirror; -}); + } catch(e) {} + } + } + + options.finishInit = function (cm) { + cm.save = save + cm.getTextArea = function () { return textarea; } + cm.toTextArea = function () { + cm.toTextArea = isNaN // Prevent this from being ran twice + save() + textarea.parentNode.removeChild(cm.getWrapperElement()) + textarea.style.display = "" + if (textarea.form) { + off(textarea.form, "submit", save) + if (typeof textarea.form.submit == "function") + { textarea.form.submit = realSubmit } + } + } + } + + textarea.style.display = "none" + var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); }, + options) + return cm +} + +function addLegacyProps(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 +} + +// EDITOR CONSTRUCTOR + +defineOptions(CodeMirror) + +addEditorMethods(CodeMirror) + +// Set up methods on CodeMirror's prototype to redirect to the editor's document. +var dontDelegate = "iter insert remove copy getEditor constructor".split(" ") +for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) + { CodeMirror.prototype[prop] = (function(method) { + return function() {return method.apply(this.doc, arguments)} + })(Doc.prototype[prop]) } } + +eventMixin(Doc) + +// INPUT HANDLING + +CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput} + +// MODE DEFINITION AND QUERYING + +// Extra arguments are stored as the mode's dependencies, which is +// used by (legacy) mechanisms like loadmode.js to automatically +// load a mode. (Preferred mechanism is the require/define calls.) +CodeMirror.defineMode = function(name/*, mode, …*/) { + if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name } + defineMode.apply(this, arguments) +} + +CodeMirror.defineMIME = defineMIME + +// Minimal default mode. +CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); }) +CodeMirror.defineMIME("text/plain", "null") + +// EXTENSIONS + +CodeMirror.defineExtension = function (name, func) { + CodeMirror.prototype[name] = func +} +CodeMirror.defineDocExtension = function (name, func) { + Doc.prototype[name] = func +} + +CodeMirror.fromTextArea = fromTextArea + +addLegacyProps(CodeMirror) + +CodeMirror.version = "5.20.2" + +return CodeMirror; + +}))); \ No newline at end of file diff --git a/media/editors/codemirror/lib/codemirror.min.js b/media/editors/codemirror/lib/codemirror.min.js index 8078d72dadfb2..8642a329b2431 100644 --- a/media/editors/codemirror/lib/codemirror.min.js +++ b/media/editors/codemirror/lib/codemirror.min.js @@ -1,5 +1,5 @@ -!(function(a){if("object"==typeof exports&&"object"==typeof module)module.exports=a();else{if("function"==typeof define&&define.amd)return define([],a);(this||window).CodeMirror=a()}})((function(){"use strict";function a(c,d){if(!(this instanceof a))return new a(c,d);this.options=d=d?Me(d):{},Me(bg,d,!1),n(d);var e=d.value;"string"==typeof e&&(e=new zg(e,d.mode,null,d.lineSeparator)),this.doc=e;var f=new a.inputStyles[d.inputStyle](this),g=this.display=new b(c,e,f);g.wrapper.CodeMirror=this,j(this),h(this),d.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap"),d.autofocus&&!Ef&&g.input.focus(),r(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 Ee,keySeq:null,specialChars:null};var i=this;uf&&vf<11&&setTimeout((function(){i.display.input.reset(!0)}),20),Rb(this),Ye(),vb(this),this.curOp.forceUpdate=!0,Yd(this,e),d.autofocus&&!Ef||i.hasFocus()?setTimeout(Ne(rc,this),20):sc(this);for(var k in cg)cg.hasOwnProperty(k)&&cg[k](this,d[k],dg);w(this),d.finishInit&&d.finishInit(this);for(var l=0;lb.maxLineLength&&(b.maxLineLength=c,b.maxLine=a)}))}function n(a){var b=He(a.gutters,"CodeMirror-linenumbers");b==-1&&a.lineNumbers?a.gutters=a.gutters.concat(["CodeMirror-linenumbers"]):b>-1&&!a.lineNumbers&&(a.gutters=a.gutters.slice(0),a.gutters.splice(b,1))}function o(a){var b=a.display,c=b.gutters.offsetWidth,d=Math.round(a.doc.height+Sa(a.display));return{clientHeight:b.scroller.clientHeight,viewHeight:b.wrapper.clientHeight,scrollWidth:b.scroller.scrollWidth,clientWidth:b.scroller.clientWidth,viewWidth:b.wrapper.clientWidth,barLeft:a.options.fixedGutter?c:0,docHeight:d,scrollHeight:d+Ua(a)+b.barHeight,nativeBarWidth:b.nativeBarWidth,gutterWidth:c}}function p(a,b,c){this.cm=c;var d=this.vert=Re("div",[Re("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),e=this.horiz=Re("div",[Re("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");a(d),a(e),Fg(d,"scroll",(function(){d.clientHeight&&b(d.scrollTop,"vertical")})),Fg(e,"scroll",(function(){e.clientWidth&&b(e.scrollLeft,"horizontal")})),this.checkedZeroWidth=!1,uf&&vf<8&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px")}function q(){}function r(b){b.display.scrollbars&&(b.display.scrollbars.clear(),b.display.scrollbars.addClass&&$g(b.display.wrapper,b.display.scrollbars.addClass)),b.display.scrollbars=new a.scrollbarModel[b.options.scrollbarStyle](function(a){b.display.wrapper.insertBefore(a,b.display.scrollbarFiller),Fg(a,"mousedown",(function(){b.state.focused&&setTimeout((function(){b.display.input.focus()}),0)})),a.setAttribute("cm-not-content","true")},function(a,c){"horizontal"==c?fc(b,a):ec(b,a)},b),b.display.scrollbars.addClass&&_g(b.display.wrapper,b.display.scrollbars.addClass)}function s(a,b){b||(b=o(a));var c=a.display.barWidth,d=a.display.barHeight;t(a,b);for(var e=0;e<4&&c!=a.display.barWidth||d!=a.display.barHeight;e++)c!=a.display.barWidth&&a.options.lineWrapping&&F(a),t(a,o(a)),c=a.display.barWidth,d=a.display.barHeight}function t(a,b){var c=a.display,d=c.scrollbars.update(b);c.sizer.style.paddingRight=(c.barWidth=d.right)+"px",c.sizer.style.paddingBottom=(c.barHeight=d.bottom)+"px",c.heightForcer.style.borderBottom=d.bottom+"px solid transparent",d.right&&d.bottom?(c.scrollbarFiller.style.display="block",c.scrollbarFiller.style.height=d.bottom+"px",c.scrollbarFiller.style.width=d.right+"px"):c.scrollbarFiller.style.display="",d.bottom&&a.options.coverGutterNextToScrollbar&&a.options.fixedGutter?(c.gutterFiller.style.display="block",c.gutterFiller.style.height=d.bottom+"px",c.gutterFiller.style.width=b.gutterWidth+"px"):c.gutterFiller.style.display=""}function u(a,b,c){var d=c&&null!=c.top?Math.max(0,c.top):a.scroller.scrollTop;d=Math.floor(d-Ra(a));var e=c&&null!=c.bottom?c.bottom:d+a.wrapper.clientHeight,f=ce(b,d),g=ce(b,e);if(c&&c.ensure){var h=c.ensure.from.line,i=c.ensure.to.line;h=g&&(f=ce(b,de(Zd(b,i))-a.wrapper.clientHeight),g=i)}return{from:f,to:Math.max(g,f+1)}}function v(a){var b=a.display,c=b.view;if(b.alignWidgets||b.gutters.firstChild&&a.options.fixedGutter){for(var d=y(b)-b.scroller.scrollLeft+a.doc.scrollLeft,e=b.gutters.offsetWidth,f=d+"px",g=0;g=c.viewFrom&&b.visible.to<=c.viewTo&&(null==c.updateLineNumbers||c.updateLineNumbers>=c.viewTo)&&c.renderedView==c.view&&0==Qb(a))return!1;w(a)&&(Mb(a),b.dims=H(a));var e=d.first+d.size,f=Math.max(b.visible.from-a.options.viewportMargin,d.first),g=Math.min(e,b.visible.to+a.options.viewportMargin);c.viewFromg&&c.viewTo-g<20&&(g=Math.min(e,c.viewTo)),Mf&&(f=ud(a.doc,f),g=vd(a.doc,g));var h=f!=c.viewFrom||g!=c.viewTo||c.lastWrapHeight!=b.wrapperHeight||c.lastWrapWidth!=b.wrapperWidth;Pb(a,f,g),c.viewOffset=de(Zd(a.doc,c.viewFrom)),a.display.mover.style.top=c.viewOffset+"px";var i=Qb(a);if(!h&&0==i&&!b.force&&c.renderedView==c.view&&(null==c.updateLineNumbers||c.updateLineNumbers>=c.viewTo))return!1;var j=Ue();return i>4&&(c.lineDiv.style.display="none"),I(a,c.updateLineNumbers,b.dims),i>4&&(c.lineDiv.style.display=""),c.renderedView=c.view,j&&Ue()!=j&&j.offsetHeight&&j.focus(),Se(c.cursorDiv),Se(c.selectionDiv),c.gutters.style.height=c.sizer.style.minHeight=0,h&&(c.lastWrapHeight=b.wrapperHeight,c.lastWrapWidth=b.wrapperWidth,Na(a,400)),c.updateLineNumbers=null,!0}function C(a,b){for(var c=b.viewport,d=!0;(d&&a.options.lineWrapping&&b.oldDisplayWidth!=Va(a)||(c&&null!=c.top&&(c={top:Math.min(a.doc.height+Sa(a.display)-Wa(a),c.top)}),b.visible=u(a.display,a.doc,c),!(b.visible.from>=a.display.viewFrom&&b.visible.to<=a.display.viewTo)))&&B(a,b);d=!1){F(a);var e=o(a);Ia(a),s(a,e),E(a,e)}b.signal(a,"update",a),a.display.viewFrom==a.display.reportedViewFrom&&a.display.viewTo==a.display.reportedViewTo||(b.signal(a,"viewportChange",a,a.display.viewFrom,a.display.viewTo),a.display.reportedViewFrom=a.display.viewFrom,a.display.reportedViewTo=a.display.viewTo)}function D(a,b){var c=new z(a,b);if(B(a,c)){F(a),C(a,c);var d=o(a);Ia(a),s(a,d),E(a,d),c.finish()}}function E(a,b){a.display.sizer.style.minHeight=b.docHeight+"px",a.display.heightForcer.style.top=b.docHeight+"px",a.display.gutters.style.height=b.docHeight+a.display.barHeight+Ua(a)+"px"}function F(a){for(var b=a.display,c=b.lineDiv.offsetTop,d=0;d.001||i<-.001)&&(ae(f.line,e),G(f.line),f.rest))for(var j=0;j-1&&(m=!1),J(a,l,j,c)),m&&(Se(l.lineNumber),l.lineNumber.appendChild(document.createTextNode(x(a.options,j)))),h=l.node.nextSibling}else{var n=R(a,l,j,c);g.insertBefore(n,h)}j+=l.size}for(;h;)h=d(h)}function J(a,b,c,d){for(var e=0;e1)if(Pf&&Pf.text.join("\n")==b){if(d.ranges.length%Pf.text.length==0){i=[];for(var j=0;j=0;j--){var k=d.ranges[j],l=k.from(),m=k.to();k.empty()&&(c&&c>0?l=Nf(l.line,l.ch-c):a.state.overwrite&&!g?m=Nf(m.line,Math.min(Zd(f,m.line).text.length,m.ch+Ge(h).length)):Pf&&Pf.lineWise&&Pf.text.join("\n")==b&&(l=m=Nf(l.line,0)));var n=a.curOp.updateInput,o={from:l,to:m,text:i?i[j%i.length]:h,origin:e||(g?"paste":a.state.cutIncoming?"cut":"+input")};Ac(a.doc,o),ye(a,"inputRead",a,o)}b&&!g&&_(a,b),Mc(a),a.curOp.updateInput=n,a.curOp.typing=!0,a.state.pasteIncoming=a.state.cutIncoming=!1}function $(a,b){var c=a.clipboardData&&a.clipboardData.getData("Text");if(c)return a.preventDefault(),b.isReadOnly()||b.options.disableInput||Eb(b,(function(){Z(b,c,0,null,"paste")})),!0}function _(a,b){if(a.options.electricChars&&a.options.smartIndent)for(var c=a.doc.sel,d=c.ranges.length-1;d>=0;d--){var e=c.ranges[d];if(!(e.head.ch>100||d&&c.ranges[d-1].head.line==e.head.line)){var f=a.getModeAt(e.head),g=!1;if(f.electricChars){for(var h=0;h-1){g=Oc(a,e.head.line,"smart");break}}else f.electricInput&&f.electricInput.test(Zd(a.doc,e.head.line).text.slice(0,e.head.ch))&&(g=Oc(a,e.head.line,"smart"));g&&ye(a,"electricInput",a,e.head.line)}}}function aa(a){for(var b=[],c=[],d=0;d=0){var g=X(f.from(),e.from()),h=W(f.to(),e.to()),i=f.empty()?e.from()==e.head:f.from()==f.head;d<=b&&--b,a.splice(--d,2,new la(i?h:g,i?g:h))}}return new ka(a,b)}function na(a,b){return new ka([new la(a,b||a)],0)}function oa(a,b){return Math.max(a.first,Math.min(b,a.first+a.size-1))}function pa(a,b){if(b.linec?Nf(c,Zd(a,c).text.length):qa(b,Zd(a,b.line).text.length)}function qa(a,b){var c=a.ch;return null==c||c>b?Nf(a.line,b):c<0?Nf(a.line,0):a}function ra(a,b){return b>=a.first&&b=b.ch:h.to>b.ch))){if(e&&(Ig(i,"beforeCursorEnter"),i.explicitlyCleared)){if(f.markedSpans){--g;continue}break}if(!i.atomic)continue;if(c){var j,k=i.find(d<0?1:-1);if((d<0?i.inclusiveRight:i.inclusiveLeft)&&(k=Ha(a,k,-d,k&&k.line==b.line?f:null)),k&&k.line==b.line&&(j=Of(k,c))&&(d<0?j<0:j>0))return Fa(a,k,b,d,e)}var l=i.find(d<0?-1:1);return(d<0?i.inclusiveLeft:i.inclusiveRight)&&(l=Ha(a,l,d,l.line==b.line?f:null)),l?Fa(a,l,b,d,e):null}}return b}function Ga(a,b,c,d,e){var f=d||1,g=Fa(a,b,c,f,e)||!e&&Fa(a,b,c,f,!0)||Fa(a,b,c,-f,e)||!e&&Fa(a,b,c,-f,!0);return g?g:(a.cantEdit=!0,Nf(a.first,0))}function Ha(a,b,c,d){return c<0&&0==b.ch?b.line>a.first?pa(a,Nf(b.line-1)):null:c>0&&b.ch==(d||Zd(a,b.line)).text.length?b.line=a.display.viewTo||h.to().line3&&(d(n,p.top,null,p.bottom),n=j,p.bottomi.bottom||l.bottom==i.bottom&&l.right>i.right)&&(i=l),n0?b.blinker=setInterval((function(){b.cursorDiv.style.visibility=(c=!c)?"":"hidden"}),a.options.cursorBlinkRate):a.options.cursorBlinkRate<0&&(b.cursorDiv.style.visibility="hidden")}}function Na(a,b){a.doc.mode.startState&&a.doc.frontier=a.display.viewTo)){var c=+new Date+a.options.workTime,d=jg(b.mode,Qa(a,b.frontier)),e=[];b.iter(b.frontier,Math.min(b.first+b.size,a.display.viewTo+500),(function(f){if(b.frontier>=a.display.viewFrom){var g=f.styles,h=f.text.length>a.options.maxHighlightLength,i=Id(a,f,h?jg(b.mode,d):d,!0);f.styles=i.styles;var j=f.styleClasses,k=i.classes;k?f.styleClasses=k:j&&(f.styleClasses=null);for(var l=!g||g.length!=f.styles.length||j!=k&&(!j||!k||j.bgClass!=k.bgClass||j.textClass!=k.textClass),m=0;!l&&mc)return Na(a,a.options.workDelay),!0})),e.length&&Eb(a,(function(){for(var b=0;bg;--h){if(h<=f.first)return f.first;var i=Zd(f,h-1);if(i.stateAfter&&(!c||h<=f.frontier))return h;var j=Pg(i.text,null,a.options.tabSize);(null==e||d>j)&&(e=h-1,d=j)}return e}function Qa(a,b,c){var d=a.doc,e=a.display;if(!d.mode.startState)return!0;var f=Pa(a,b,c),g=f>d.first&&Zd(d,f-1).stateAfter;return g=g?jg(d.mode,g):kg(d.mode),d.iter(f,b,(function(c){Kd(a,c.text,g);var h=f==b-1||f%5==0||f>=e.viewFrom&&f2&&f.push((i.bottom+j.top)/2-c.top)}}f.push(c.bottom-c.top)}}function Ya(a,b,c){if(a.line==b)return{map:a.measure.map,cache:a.measure.cache};for(var d=0;dc)return{map:a.measure.maps[d],cache:a.measure.caches[d],before:!0}}function Za(a,b){b=sd(b);var c=be(b),d=a.display.externalMeasured=new Ib(a.doc,b,c);d.lineN=c;var e=d.built=Md(a,d);return d.text=e.pre,Te(a.display.lineMeasure,e.pre),d}function $a(a,b,c,d){return bb(a,ab(a,b),c,d)}function _a(a,b){if(b>=a.display.viewFrom&&b=c.lineN&&bb)&&(f=j-i,e=f-1,b>=j&&(g="right")),null!=e){if(d=a[h+2],i==j&&c==(d.insertLeft?"left":"right")&&(g=c),"left"==c&&0==e)for(;h&&a[h-2]==a[h-3]&&a[h-1].insertLeft;)d=a[(h-=3)+2],g="left";if("right"==c&&e==j-i)for(;h=0&&(c=a[d]).left==c.right;d--);return c}function eb(a,b,c,d){var e,f=cb(b.map,c,d),g=f.node,h=f.start,i=f.end,j=f.collapse;if(3==g.nodeType){for(var k=0;k<4;k++){for(;h&&Qe(b.line.text.charAt(f.coverStart+h));)--h;for(;f.coverStart+i0&&(j=d="right");var l;e=a.options.lineWrapping&&(l=g.getClientRects()).length>1?l["right"==d?l.length-1:0]:g.getBoundingClientRect()}if(uf&&vf<9&&!h&&(!e||!e.left&&!e.right)){var m=g.parentNode.getClientRects()[0];e=m?{left:m.left,right:m.left+ub(a.display),top:m.top,bottom:m.bottom}:Tf}for(var n=e.top-b.rect.top,o=e.bottom-b.rect.top,p=(n+o)/2,q=b.view.measure.heights,k=0;kc.from?g(a-1):g(a,d)}d=d||Zd(a.doc,b.line),e||(e=ab(a,d));var i=ee(d),j=b.ch;if(!i)return g(j);var k=lf(i,j),l=h(j,k);return null!=hh&&(l.other=h(j,hh)),l}function pb(a,b){var c=0,b=pa(a.doc,b);a.options.lineWrapping||(c=ub(a.display)*b.ch);var d=Zd(a.doc,b.line),e=de(d)+Ra(a.display);return{left:c,right:c,top:e,bottom:e+d.height}}function qb(a,b,c,d){var e=Nf(a,b);return e.xRel=d,c&&(e.outside=!0),e}function rb(a,b,c){var d=a.doc;if(c+=a.display.viewOffset,c<0)return qb(d.first,0,!0,-1);var e=ce(d,c),f=d.first+d.size-1;if(e>f)return qb(d.first+d.size-1,Zd(d,f).text.length,!0,1);b<0&&(b=0);for(var g=Zd(d,e);;){var h=sb(a,g,e,b,c),i=qd(g),j=i&&i.find(0,!0);if(!i||!(h.ch>j.from.ch||h.ch==j.from.ch&&h.xRel>0))return h;e=be(g=j.to.line)}}function sb(a,b,c,d,e){function f(d){var e=ob(a,Nf(c,d),"line",b,j);return h=!0,g>e.bottom?e.left-i:gq)return qb(c,n,r,1);for(;;){if(k?n==m||n==nf(b,m,1):n-m<=1){var s=d0&&s1){var v=bb(a,j,s,"right");g<=v.bottom&&g>=v.top&&Math.abs(d-v.right)1?1:0);return w}var x=Math.ceil(l/2),y=m+x;if(k){y=m;for(var z=0;zd?(n=y,q=A,(r=h)&&(q+=1e3),l=x):(m=y,o=A,p=h,l-=x)}}function tb(a){if(null!=a.cachedTextHeight)return a.cachedTextHeight;if(null==Qf){Qf=Re("pre");for(var b=0;b<49;++b)Qf.appendChild(document.createTextNode("x")),Qf.appendChild(Re("br"));Qf.appendChild(document.createTextNode("x"))}Te(a.measure,Qf);var c=Qf.offsetHeight/50;return c>3&&(a.cachedTextHeight=c),Se(a.measure),c||1}function ub(a){if(null!=a.cachedCharWidth)return a.cachedCharWidth;var b=Re("span","xxxxxxxxxx"),c=Re("pre",[b]);Te(a.measure,c);var d=b.getBoundingClientRect(),e=(d.right-d.left)/10;return e>2&&(a.cachedCharWidth=e),e||10}function vb(a){a.curOp={cm:a,viewChanged:!1,startHeight:a.doc.height,forceUpdate:!1,updateInput:null,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,focus:!1,id:++Vf},Uf?Uf.ops.push(a.curOp):a.curOp.ownsGroup=Uf={ops:[a.curOp],delayedCallbacks:[]}}function wb(a){var b=a.delayedCallbacks,c=0;do{for(;c=c.viewTo)||c.maxLineChanged&&b.options.lineWrapping,a.update=a.mustUpdate&&new z(b,a.mustUpdate&&{top:a.scrollTop,ensure:a.scrollToPos},a.forceUpdate)}function Ab(a){a.updatedDisplay=a.mustUpdate&&B(a.cm,a.update)}function Bb(a){var b=a.cm,c=b.display;a.updatedDisplay&&F(b),a.barMeasure=o(b),c.maxLineChanged&&!b.options.lineWrapping&&(a.adjustWidthTo=$a(b,c.maxLine,c.maxLine.text.length).left+3,b.display.sizerWidth=a.adjustWidthTo,a.barMeasure.scrollWidth=Math.max(c.scroller.clientWidth,c.sizer.offsetLeft+a.adjustWidthTo+Ua(b)+b.display.barWidth),a.maxScrollLeft=Math.max(0,c.sizer.offsetLeft+a.adjustWidthTo-Va(b))),(a.updatedDisplay||a.selectionChanged)&&(a.preparedSelection=c.input.prepareSelection(a.focus))}function Cb(a){var b=a.cm;null!=a.adjustWidthTo&&(b.display.sizer.style.minWidth=a.adjustWidthTo+"px",a.maxScrollLeftb)&&(e.updateLineNumbers=b),a.curOp.viewChanged=!0,b>=e.viewTo)Mf&&ud(a.doc,b)e.viewFrom?Mb(a):(e.viewFrom+=d,e.viewTo+=d);else if(b<=e.viewFrom&&c>=e.viewTo)Mb(a);else if(b<=e.viewFrom){var f=Ob(a,c,c+d,1);f?(e.view=e.view.slice(f.index),e.viewFrom=f.lineN,e.viewTo+=d):Mb(a)}else if(c>=e.viewTo){var f=Ob(a,b,b,-1);f?(e.view=e.view.slice(0,f.index),e.viewTo=f.lineN):Mb(a)}else{var g=Ob(a,b,b,-1),h=Ob(a,c,c+d,1);g&&h?(e.view=e.view.slice(0,g.index).concat(Jb(a,g.lineN,h.lineN)).concat(e.view.slice(h.index)),e.viewTo+=d):Mb(a)}var i=e.externalMeasured;i&&(c=e.lineN&&b=d.viewTo)){var f=d.view[Nb(a,b)];if(null!=f.node){var g=f.changes||(f.changes=[]);He(g,c)==-1&&g.push(c)}}}function Mb(a){a.display.viewFrom=a.display.viewTo=a.doc.first,a.display.view=[],a.display.viewOffset=0}function Nb(a,b){if(b>=a.display.viewTo)return null;if(b-=a.display.viewFrom,b<0)return null;for(var c=a.display.view,d=0;d0){if(f==g.length-1)return null;e=i+g[f].size-b,f++}else e=i-b;b+=e,c+=e}for(;ud(a.doc,c)!=c;){if(f==(d<0?0:g.length-1))return null;c+=d*g[f-(d<0?1:0)].size,f+=d}return{index:f,lineN:c}}function Pb(a,b,c){var d=a.display,e=d.view;0==e.length||b>=d.viewTo||c<=d.viewFrom?(d.view=Jb(a,b,c),d.viewFrom=b):(d.viewFrom>b?d.view=Jb(a,b,d.viewFrom).concat(d.view):d.viewFromc&&(d.view=d.view.slice(0,Nb(a,c)))),d.viewTo=c}function Qb(a){for(var b=a.display.view,c=0,d=0;d400}var e=a.display;Fg(e.scroller,"mousedown",Fb(a,Wb)),uf&&vf<11?Fg(e.scroller,"dblclick",Fb(a,(function(b){if(!Ae(a,b)){var c=Vb(a,b);if(c&&!_b(a,b)&&!Ub(a.display,b)){Cg(b);var d=a.findWordAt(c);ua(a.doc,d.anchor,d.head)}}}))):Fg(e.scroller,"dblclick",(function(b){Ae(a,b)||Cg(b)})),Kf||Fg(e.scroller,"contextmenu",(function(b){tc(a,b)}));var f,g={end:0};Fg(e.scroller,"touchstart",(function(b){if(!Ae(a,b)&&!c(b)){clearTimeout(f);var d=+new Date;e.activeTouch={start:d,moved:!1,prev:d-g.end<=300?g:null},1==b.touches.length&&(e.activeTouch.left=b.touches[0].pageX,e.activeTouch.top=b.touches[0].pageY)}})),Fg(e.scroller,"touchmove",(function(){e.activeTouch&&(e.activeTouch.moved=!0)})),Fg(e.scroller,"touchend",(function(c){var f=e.activeTouch;if(f&&!Ub(e,c)&&null!=f.left&&!f.moved&&new Date-f.start<300){var g,h=a.coordsChar(e.activeTouch,"page");g=!f.prev||d(f,f.prev)?new la(h,h):!f.prev.prev||d(f,f.prev.prev)?a.findWordAt(h):new la(Nf(h.line,0),pa(a.doc,Nf(h.line+1,0))),a.setSelection(g.anchor,g.head),a.focus(),Cg(c)}b()})),Fg(e.scroller,"touchcancel",b),Fg(e.scroller,"scroll",(function(){e.scroller.clientHeight&&(ec(a,e.scroller.scrollTop),fc(a,e.scroller.scrollLeft,!0),Ig(a,"scroll",a))})),Fg(e.scroller,"mousewheel",(function(b){gc(a,b)})),Fg(e.scroller,"DOMMouseScroll",(function(b){gc(a,b)})),Fg(e.wrapper,"scroll",(function(){e.wrapper.scrollTop=e.wrapper.scrollLeft=0})),e.dragFunctions={enter:function(b){Ae(a,b)||Eg(b)},over:function(b){Ae(a,b)||(cc(a,b),Eg(b))},start:function(b){bc(a,b)},drop:Fb(a,ac),leave:function(b){Ae(a,b)||dc(a)}};var h=e.input.getField();Fg(h,"keyup",(function(b){oc.call(a,b)})),Fg(h,"keydown",Fb(a,mc)),Fg(h,"keypress",Fb(a,pc)),Fg(h,"focus",(function(b){rc(a,b)})),Fg(h,"blur",(function(b){sc(a,b)}))}function Sb(b,c,d){var e=d&&d!=a.Init;if(!c!=!e){var f=b.display.dragFunctions,g=c?Fg:Hg;g(b.display.scroller,"dragstart",f.start),g(b.display.scroller,"dragenter",f.enter),g(b.display.scroller,"dragover",f.over),g(b.display.scroller,"dragleave",f.leave),g(b.display.scroller,"drop",f.drop)}}function Tb(a){var b=a.display;b.lastWrapHeight==b.wrapper.clientHeight&&b.lastWrapWidth==b.wrapper.clientWidth||(b.cachedCharWidth=b.cachedTextHeight=b.cachedPaddingH=null,b.scrollbarsClipped=!1,a.setSize())}function Ub(a,b){for(var c=ve(b);c!=a.wrapper;c=c.parentNode)if(!c||1==c.nodeType&&"true"==c.getAttribute("cm-ignore-events")||c.parentNode==a.sizer&&c!=a.mover)return!0}function Vb(a,b,c,d){var e=a.display;if(!c&&"true"==ve(b).getAttribute("cm-not-content"))return null;var f,g,h=e.lineSpace.getBoundingClientRect();try{f=b.clientX-h.left,g=b.clientY-h.top}catch(a){return null}var i,j=rb(a,f,g);if(d&&1==j.xRel&&(i=Zd(a.doc,j.line).text).length==j.ch){var k=Pg(i,i.length,a.options.tabSize)-i.length;j=Nf(j.line,Math.max(0,Math.round((f-Ta(a.display).left)/ub(a.display))-k))}return j}function Wb(a){var b=this,c=b.display;if(!(Ae(b,a)||c.activeTouch&&c.input.supportsTouch())){if(c.shift=a.shiftKey,Ub(c,a))return void(wf||(c.scroller.draggable=!1,setTimeout((function(){c.scroller.draggable=!0}),100)));if(!_b(b,a)){var d=Vb(b,a);switch(window.focus(),we(a)){case 1:b.state.selectingText?b.state.selectingText(a):d?Xb(b,a,d):ve(a)==c.scroller&&Cg(a);break;case 2:wf&&(b.state.lastMiddleDown=+new Date),d&&ua(b.doc,d),setTimeout((function(){c.input.focus()}),20),Cg(a);break;case 3:Kf?tc(b,a):qc(b)}}}}function Xb(a,b,c){uf?setTimeout(Ne(Y,a),0):a.curOp.focus=Ue();var d,e=+new Date;Sf&&Sf.time>e-400&&0==Of(Sf.pos,c)?d="triple":Rf&&Rf.time>e-400&&0==Of(Rf.pos,c)?(d="double",Sf={time:e,pos:c}):(d="single",Rf={time:e,pos:c});var f,g=a.doc.sel,h=Ff?b.metaKey:b.ctrlKey;a.options.dragDrop&&bh&&!a.isReadOnly()&&"single"==d&&(f=g.contains(c))>-1&&(Of((f=g.ranges[f]).from(),c)<0||c.xRel>0)&&(Of(f.to(),c)>0||c.xRel<0)?Yb(a,b,c,h):Zb(a,b,c,d,h)}function Yb(a,b,c,d){var e=a.display,f=+new Date,g=Fb(a,(function(h){wf&&(e.scroller.draggable=!1),a.state.draggingText=!1,Hg(document,"mouseup",g),Hg(e.scroller,"drop",g),Math.abs(b.clientX-h.clientX)+Math.abs(b.clientY-h.clientY)<10&&(Cg(h),!d&&+new Date-200s&&e.push(new la(Nf(o,s),Nf(o,Qg(r,n,f))))}e.length||e.push(new la(c,c)),Aa(j,ma(m.ranges.slice(0,l).concat(e),l),{origin:"*mouse",scroll:!1}),a.scrollIntoView(b)}else{var t=k,u=t.anchor,v=b;if("single"!=d){if("double"==d)var w=a.findWordAt(b);else var w=new la(Nf(b.line,0),pa(j,Nf(b.line+1,0)));Of(w.anchor,u)>0?(v=w.head,u=X(t.from(),w.anchor)):(v=w.anchor,u=W(t.to(),w.head))}var e=m.ranges.slice(0);e[l]=new la(pa(j,u),v),Aa(j,ma(e,l),Ng)}}function g(b){var c=++s,e=Vb(a,b,!0,"rect"==d);if(e)if(0!=Of(e,q)){a.curOp.focus=Ue(),f(e);var h=u(i,j);(e.line>=h.to||e.liner.bottom?20:0;k&&setTimeout(Fb(a,(function(){s==c&&(i.scroller.scrollTop+=k,g(b))})),50)}}function h(b){a.state.selectingText=!1,s=1/0,Cg(b),i.input.focus(),Hg(document,"mousemove",t),Hg(document,"mouseup",v),j.history.lastSelOrigin=null}var i=a.display,j=a.doc;Cg(b);var k,l,m=j.sel,n=m.ranges;if(e&&!b.shiftKey?(l=j.sel.contains(c),k=l>-1?n[l]:new la(c,c)):(k=j.sel.primary(),l=j.sel.primIndex),Gf?b.shiftKey&&b.metaKey:b.altKey)d="rect",e||(k=new la(c,c)),c=Vb(a,b,!0,!0),l=-1;else if("double"==d){var o=a.findWordAt(c);k=a.display.shift||j.extend?ta(j,k,o.anchor,o.head):o}else if("triple"==d){var p=new la(Nf(c.line,0),pa(j,Nf(c.line+1,0)));k=a.display.shift||j.extend?ta(j,k,p.anchor,p.head):p}else k=ta(j,k,c);e?l==-1?(l=n.length,Aa(j,ma(n.concat([k]),l),{scroll:!1,origin:"*mouse"})):n.length>1&&n[l].empty()&&"single"==d&&!b.shiftKey?(Aa(j,ma(n.slice(0,l).concat(n.slice(l+1)),0),{scroll:!1,origin:"*mouse"}),m=j.sel):wa(j,l,k,Ng):(l=0,Aa(j,new ka([k],0),Ng),m=j.sel);var q=c,r=i.wrapper.getBoundingClientRect(),s=0,t=Fb(a,(function(a){we(a)?g(a):h(a)})),v=Fb(a,h);a.state.selectingText=v,Fg(document,"mousemove",t),Fg(document,"mouseup",v)}function $b(a,b,c,d){try{var e=b.clientX,f=b.clientY}catch(a){return!1}if(e>=Math.floor(a.display.gutters.getBoundingClientRect().right))return!1;d&&Cg(b);var g=a.display,h=g.lineDiv.getBoundingClientRect();if(f>h.bottom||!Ce(a,c))return ue(b);f-=h.top-g.viewOffset;for(var i=0;i=e){var k=ce(a.doc,f),l=a.options.gutters[i];return Ig(a,c,a,k,l,b),ue(b)}}}function _b(a,b){return $b(a,b,"gutterClick",!0)}function ac(a){var b=this;if(dc(b),!Ae(b,a)&&!Ub(b.display,a)){Cg(a),uf&&(Wf=+new Date);var c=Vb(b,a,!0),d=a.dataTransfer.files;if(c&&!b.isReadOnly())if(d&&d.length&&window.FileReader&&window.File)for(var e=d.length,f=Array(e),g=0,h=function(a,d){if(!b.options.allowDropFileTypes||He(b.options.allowDropFileTypes,a.type)!=-1){var h=new FileReader;h.onload=Fb(b,(function(){var a=h.result;if(/[\x00-\x08\x0e-\x1f]{2}/.test(a)&&(a=""),f[d]=a,++g==e){c=pa(b.doc,c);var i={from:c,to:c,text:b.doc.splitLines(f.join(b.doc.lineSeparator())),origin:"paste"};Ac(b.doc,i),za(b.doc,na(c,ag(i)))}})),h.readAsText(a)}},i=0;i-1)return b.state.draggingText(a),void setTimeout((function(){b.display.input.focus()}),20);try{var f=a.dataTransfer.getData("Text");if(f){if(b.state.draggingText&&!b.state.draggingText.copy)var j=b.listSelections();if(Ba(b.doc,na(c,c)),j)for(var i=0;ig.clientWidth,i=g.scrollHeight>g.clientHeight;if(d&&h||e&&i){if(e&&Ff&&wf)a:for(var j=b.target,k=f.view;j!=g;j=j.parentNode)for(var l=0;l=0;--e)Bc(a,{from:d[e].from,to:d[e].to,text:e?[""]:b.text});else Bc(a,b)}}function Bc(a,b){if(1!=b.text.length||""!=b.text[0]||0!=Of(b.from,b.to)){var c=wc(a,b);je(a,b,c,a.cm?a.cm.curOp.id:NaN),Ec(a,b,c,fd(a,b));var d=[];Xd(a,(function(a,c){c||He(d,a.history)!=-1||(te(a.history,b),d.push(a.history)),Ec(a,b,null,fd(a,b))}))}}function Cc(a,b,c){if(!a.cm||!a.cm.state.suppressEdits||c){for(var d,e=a.history,f=a.sel,g="undo"==b?e.done:e.undone,h="undo"==b?e.undone:e.done,i=0;i=0;--i){var l=d.changes[i];if(l.origin=b,k&&!zc(a,l,!1))return void(g.length=0);j.push(ge(a,l));var m=i?wc(a,l):Ge(g);Ec(a,l,m,hd(a,l)),!i&&a.cm&&a.cm.scrollIntoView({from:l.from,to:ag(l)});var n=[];Xd(a,(function(a,b){b||He(n,a.history)!=-1||(te(a.history,l),n.push(a.history)),Ec(a,l,null,hd(a,l))}))}}}}function Dc(a,b){if(0!=b&&(a.first+=b,a.sel=new ka(Ie(a.sel.ranges,(function(a){return new la(Nf(a.anchor.line+b,a.anchor.ch),Nf(a.head.line+b,a.head.ch))})),a.sel.primIndex),a.cm)){Kb(a.cm,a.first,a.first-b,b);for(var c=a.cm.display,d=c.viewFrom;da.lastLine())){if(b.from.linef&&(b={from:b.from,to:Nf(f,Zd(a,f).text.length),text:[b.text[0]],origin:b.origin}),b.removed=$d(a,b.from,b.to),c||(c=wc(a,b)),a.cm?Fc(a.cm,b,d):Ud(a,b,d),Ba(a,c,Mg)}}function Fc(a,b,c){var d=a.doc,e=a.display,g=b.from,h=b.to,i=!1,j=g.line;a.options.lineWrapping||(j=be(sd(Zd(d,g.line))),d.iter(j,h.line+1,(function(a){if(a==e.maxLine)return i=!0,!0}))),d.sel.contains(b.from,b.to)>-1&&Be(a),Ud(d,b,c,f(a)),a.options.lineWrapping||(d.iter(j,g.line+b.text.length,(function(a){var b=l(a);b>e.maxLineLength&&(e.maxLine=a,e.maxLineLength=b,e.maxLineChanged=!0,i=!1)})),i&&(a.curOp.updateMaxLine=!0)),d.frontier=Math.min(d.frontier,g.line),Na(a,400);var k=b.text.length-(h.line-g.line)-1;b.full?Kb(a):g.line!=h.line||1!=b.text.length||Td(a.doc,b)?Kb(a,g.line,h.line+1,k):Lb(a,g.line,"text");var m=Ce(a,"changes"),n=Ce(a,"change");if(n||m){var o={from:g,to:h,text:b.text,removed:b.removed,origin:b.origin};n&&ye(a,"change",a,o),m&&(a.curOp.changeObjs||(a.curOp.changeObjs=[])).push(o)}a.display.selForContextMenu=null}function Gc(a,b,c,d,e){if(d||(d=c),Of(d,c)<0){var f=d;d=c,c=f}"string"==typeof b&&(b=a.splitLines(b)),Ac(a,{from:c,to:d,text:b,origin:e})}function Hc(a,b){if(!Ae(a,"scrollCursorIntoView")){var c=a.display,d=c.sizer.getBoundingClientRect(),e=null;if(b.top+d.top<0?e=!0:b.bottom+d.top>(window.innerHeight||document.documentElement.clientHeight)&&(e=!1),null!=e&&!Cf){var f=Re("div","​",null,"position: absolute; top: "+(b.top-c.viewOffset-Ra(a.display))+"px; height: "+(b.bottom-b.top+Ua(a)+c.barHeight)+"px; left: "+b.left+"px; width: 2px;");a.display.lineSpace.appendChild(f),f.scrollIntoView(e),a.display.lineSpace.removeChild(f)}}}function Ic(a,b,c,d){null==d&&(d=0);for(var e=0;e<5;e++){var f=!1,g=ob(a,b),h=c&&c!=b?ob(a,c):g,i=Kc(a,Math.min(g.left,h.left),Math.min(g.top,h.top)-d,Math.max(g.left,h.left),Math.max(g.bottom,h.bottom)+d),j=a.doc.scrollTop,k=a.doc.scrollLeft;if(null!=i.scrollTop&&(ec(a,i.scrollTop),Math.abs(a.doc.scrollTop-j)>1&&(f=!0)),null!=i.scrollLeft&&(fc(a,i.scrollLeft),Math.abs(a.doc.scrollLeft-k)>1&&(f=!0)),!f)break}return g}function Jc(a,b,c,d,e){var f=Kc(a,b,c,d,e);null!=f.scrollTop&&ec(a,f.scrollTop),null!=f.scrollLeft&&fc(a,f.scrollLeft)}function Kc(a,b,c,d,e){var f=a.display,g=tb(a.display);c<0&&(c=0);var h=a.curOp&&null!=a.curOp.scrollTop?a.curOp.scrollTop:f.scroller.scrollTop,i=Wa(a),j={};e-c>i&&(e=c+i);var k=a.doc.height+Sa(f),l=ck-g;if(ch+i){var n=Math.min(c,(m?k:e)-i);n!=h&&(j.scrollTop=n)}var o=a.curOp&&null!=a.curOp.scrollLeft?a.curOp.scrollLeft:f.scroller.scrollLeft,p=Va(a)-(a.options.fixedGutter?f.gutters.offsetWidth:0),q=d-b>p; -return q&&(d=b+p),b<10?j.scrollLeft=0:bp+o-3&&(j.scrollLeft=d+(q?0:10)-p),j}function Lc(a,b,c){null==b&&null==c||Nc(a),null!=b&&(a.curOp.scrollLeft=(null==a.curOp.scrollLeft?a.doc.scrollLeft:a.curOp.scrollLeft)+b),null!=c&&(a.curOp.scrollTop=(null==a.curOp.scrollTop?a.doc.scrollTop:a.curOp.scrollTop)+c)}function Mc(a){Nc(a);var b=a.getCursor(),c=b,d=b;a.options.lineWrapping||(c=b.ch?Nf(b.line,b.ch-1):b,d=Nf(b.line,b.ch+1)),a.curOp.scrollToPos={from:c,to:d,margin:a.options.cursorScrollMargin,isCursor:!0}}function Nc(a){var b=a.curOp.scrollToPos;if(b){a.curOp.scrollToPos=null;var c=pb(a,b.from),d=pb(a,b.to),e=Kc(a,Math.min(c.left,d.left),Math.min(c.top,d.top)-b.margin,Math.max(c.right,d.right),Math.max(c.bottom,d.bottom)+b.margin);a.scrollTo(e.scrollLeft,e.scrollTop)}}function Oc(a,b,c,d){var e,f=a.doc;null==c&&(c="add"),"smart"==c&&(f.mode.indent?e=Qa(a,b):c="prev");var g=a.options.tabSize,h=Zd(f,b),i=Pg(h.text,null,g);h.stateAfter&&(h.stateAfter=null);var j,k=h.text.match(/^\s*/)[0];if(d||/\S/.test(h.text)){if("smart"==c&&(j=f.mode.indent(e,h.text.slice(k.length),h.text),j==Lg||j>150)){if(!d)return;c="prev"}}else j=0,c="not";"prev"==c?j=b>f.first?Pg(Zd(f,b-1).text,null,g):0:"add"==c?j=i+a.options.indentUnit:"subtract"==c?j=i-a.options.indentUnit:"number"==typeof c&&(j=i+c),j=Math.max(0,j);var l="",m=0;if(a.options.indentWithTabs)for(var n=Math.floor(j/g);n;--n)m+=g,l+="\t";if(m=0;b--)Gc(a.doc,"",d[b].from,d[b].to,"+delete");Mc(a)}))}function Rc(a,b,c,d,e){function f(){var b=h+c;return!(b=a.first+a.size)&&(h=b,k=Zd(a,b))}function g(a){var b=(e?nf:of)(k,i,c,!0);if(null==b){if(a||!f())return!1;i=e?(c<0?ff:ef)(k):c<0?k.text.length:0}else i=b;return!0}var h=b.line,i=b.ch,j=c,k=Zd(a,h);if("char"==d)g();else if("column"==d)g(!0);else if("word"==d||"group"==d)for(var l=null,m="group"==d,n=a.cm&&a.cm.getHelper(b,"wordChars"),o=!0;!(c<0)||g(!o);o=!1){var p=k.text.charAt(i)||"\n",q=Oe(p,n)?"w":m&&"\n"==p?"n":!m||/\s/.test(p)?null:"p";if(!m||o||q||(q="s"),l&&l!=q){c<0&&(c=1,g());break}if(q&&(l=q),c>0&&!g(!o))break}var r=Ga(a,Nf(h,i),b,j,!0);return Of(b,r)||(r.hitSide=!0),r}function Sc(a,b,c,d){var e,f=a.doc,g=b.left;if("page"==d){var h=Math.min(a.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight),i=Math.max(h-.5*tb(a.display),3);e=(c>0?b.bottom:b.top)+c*i}else"line"==d&&(e=c>0?b.bottom+3:b.top-3);for(;;){var j=rb(a,g,e);if(!j.outside)break;if(c<0?e<=0:e>=f.height){j.hitSide=!0;break}e+=5*c}return j}function Tc(b,c,d,e){a.defaults[b]=c,d&&(cg[b]=e?function(a,b,c){c!=dg&&d(a,b,c)}:d)}function Uc(a){for(var b,c,d,e,f=a.split(/-(?!$)/),a=f[f.length-1],g=0;g0||0==g&&f.clearWhenEmpty!==!1)return f;if(f.replacedWith&&(f.collapsed=!0,f.widgetNode=Re("span",[f.replacedWith],"CodeMirror-widget"),d.handleMouseEvents||f.widgetNode.setAttribute("cm-ignore-events","true"),d.insertLeft&&(f.widgetNode.insertLeft=!0)),f.collapsed){if(rd(a,b.line,b,c,f)||b.line!=c.line&&rd(a,c.line,b,c,f))throw new Error("Inserting collapsed marker partially overlapping an existing one");Mf=!0}f.addToHistory&&je(a,{from:b,to:c,origin:"markText"},a.sel,NaN);var h,i=b.line,j=a.cm;if(a.iter(i,c.line+1,(function(a){j&&f.collapsed&&!j.options.lineWrapping&&sd(a)==j.display.maxLine&&(h=!0),f.collapsed&&i!=b.line&&ae(a,0),cd(a,new _c(f,i==b.line?b.ch:null,i==c.line?c.ch:null)),++i})),f.collapsed&&a.iter(b.line,c.line+1,(function(b){wd(a,b)&&ae(b,0)})),f.clearOnEnter&&Fg(f,"beforeCursorEnter",(function(){f.clear()})),f.readOnly&&(Lf=!0,(a.history.done.length||a.history.undone.length)&&a.clearHistory()),f.collapsed&&(f.id=++rg,f.atomic=!0),j){if(h&&(j.curOp.updateMaxLine=!0),f.collapsed)Kb(j,b.line,c.line+1);else if(f.className||f.title||f.startStyle||f.endStyle||f.css)for(var k=b.line;k<=c.line;k++)Lb(j,k,"text");f.atomic&&Da(j.doc),ye(j,"markerAdded",j,f)}return f}function Xc(a,b,c,d,e){d=Me(d),d.shared=!1;var f=[Wc(a,b,c,d,e)],g=f[0],h=d.widgetNode;return Xd(a,(function(a){h&&(d.widgetNode=h.cloneNode(!0)),f.push(Wc(a,pa(a,b),pa(a,c),d,e));for(var i=0;i=b:f.to>b);(d||(d=[])).push(new _c(g,f.from,i?null:f.to))}}return d}function ed(a,b,c){if(a)for(var d,e=0;e=b:f.to>b);if(h||f.from==b&&"bookmark"==g.type&&(!c||f.marker.insertLeft)){var i=null==f.from||(g.inclusiveLeft?f.from<=b:f.from0&&h)for(var l=0;l0)){var k=[i,1],l=Of(j.from,h.from),m=Of(j.to,h.to);(l<0||!g.inclusiveLeft&&!l)&&k.push({from:j.from,to:h.from}),(m>0||!g.inclusiveRight&&!m)&&k.push({from:h.to,to:j.to}),e.splice.apply(e,k),i+=k.length-1}}return e}function jd(a){var b=a.markedSpans;if(b){for(var c=0;c=0&&l<=0||k<=0&&l>=0)&&(k<=0&&(i.marker.inclusiveRight&&e.inclusiveLeft?Of(j.to,c)>=0:Of(j.to,c)>0)||k>=0&&(i.marker.inclusiveRight&&e.inclusiveLeft?Of(j.from,d)<=0:Of(j.from,d)<0)))return!0}}}function sd(a){for(var b;b=pd(a);)a=b.find(-1,!0).line;return a}function td(a){for(var b,c;b=qd(a);)a=b.find(1,!0).line,(c||(c=[])).push(a);return c}function ud(a,b){var c=Zd(a,b),d=sd(c);return c==d?b:be(d)}function vd(a,b){if(b>a.lastLine())return b;var c,d=Zd(a,b);if(!wd(a,d))return b;for(;c=qd(d);)d=c.find(1,!0).line;return be(d)+1}function wd(a,b){var c=Mf&&b.markedSpans;if(c)for(var d,e=0;ec.start)return g}throw new Error("Mode "+b.name+" failed to advance stream.")}function Gd(a,b,c,d){function e(a){return{start:l.start,end:l.pos,string:l.current(),type:f||null,state:a?jg(g.mode,k):k}}var f,g=a.doc,h=g.mode;b=pa(g,b);var i,j=Zd(g,b.line),k=Qa(a,b.line,c),l=new qg(j.text,a.options.tabSize);for(d&&(i=[]);(d||l.posa.options.maxHighlightLength?(h=!1,g&&Kd(a,b,d,l.pos),l.pos=b.length,i=null):i=Dd(Fd(c,l,d,m),f),m){var n=m[0].name;n&&(i="m-"+(i?n+" "+i:n))}if(!h||k!=i){for(;ja&&e.splice(i,1,a,e[i+1],d),i+=2,j=Math.min(a,d)}if(b)if(h.opaque)e.splice(c,i-c,a,"cm-overlay "+b),i=c+2;else for(;ca.options.maxHighlightLength?jg(a.doc.mode,d):d);b.stateAfter=d,b.styles=e.styles,e.classes?b.styleClasses=e.classes:b.styleClasses&&(b.styleClasses=null),c===a.doc.frontier&&a.doc.frontier++}return b.styles}function Kd(a,b,c,d){var e=a.doc.mode,f=new qg(b,a.options.tabSize);for(f.start=f.pos=d||0,""==b&&Ed(e,c);!f.eol();)Fd(e,f,c),f.start=f.pos}function Ld(a,b){if(!a||/^\s*$/.test(a))return null;var c=b.addModeClass?xg:wg;return c[a]||(c[a]=a.replace(/\S+/g,"cm-$&"))}function Md(a,b){var c=Re("span",null,null,wf?"padding-right: .1px":null),d={pre:Re("pre",[c],"CodeMirror-line"),content:c,col:0,pos:0,cm:a,trailingSpace:!1,splitSpaces:(uf||wf)&&a.getOption("lineWrapping")};b.measure={};for(var e=0;e<=(b.rest?b.rest.length:0);e++){var f,g=e?b.rest[e-1]:b.line;d.pos=0,d.addToken=Od,_e(a.display.measure)&&(f=ee(g))&&(d.addToken=Qd(d.addToken,f)),d.map=[];var h=b!=a.display.externalMeasured&&be(g);Sd(g,d,Jd(a,g,h)),g.styleClasses&&(g.styleClasses.bgClass&&(d.bgClass=We(g.styleClasses.bgClass,d.bgClass||"")),g.styleClasses.textClass&&(d.textClass=We(g.styleClasses.textClass,d.textClass||""))),0==d.map.length&&d.map.push(0,0,d.content.appendChild($e(a.display.measure))),0==e?(b.measure.map=d.map,b.measure.cache={}):((b.measure.maps||(b.measure.maps=[])).push(d.map),(b.measure.caches||(b.measure.caches=[])).push({}))}if(wf){var i=d.content.lastChild;(/\bcm-tab\b/.test(i.className)||i.querySelector&&i.querySelector(".cm-tab"))&&(d.content.className="cm-tab-wrap-hack")}return Ig(a,"renderLine",a,b.line,d.pre),d.pre.className&&(d.textClass=We(d.pre.className,d.textClass||"")),d}function Nd(a){var b=Re("span","•","cm-invalidchar");return b.title="\\u"+a.charCodeAt(0).toString(16),b.setAttribute("aria-label",b.title),b}function Od(a,b,c,d,e,f,g){if(b){var h=a.splitSpaces?Pd(b,a.trailingSpace):b,i=a.cm.state.specialChars,j=!1;if(i.test(b))for(var k=document.createDocumentFragment(),l=0;;){i.lastIndex=l;var m=i.exec(b),n=m?m.index-l:b.length-l;if(n){var o=document.createTextNode(h.slice(l,l+n));uf&&vf<9?k.appendChild(Re("span",[o])):k.appendChild(o),a.map.push(a.pos,a.pos+n,o),a.col+=n,a.pos+=n}if(!m)break;if(l+=n+1,"\t"==m[0]){var p=a.cm.options.tabSize,q=p-a.col%p,o=k.appendChild(Re("span",Fe(q),"cm-tab"));o.setAttribute("role","presentation"),o.setAttribute("cm-text","\t"),a.col+=q}else if("\r"==m[0]||"\n"==m[0]){var o=k.appendChild(Re("span","\r"==m[0]?"␍":"␤","cm-invalidchar"));o.setAttribute("cm-text",m[0]),a.col+=1}else{var o=a.cm.options.specialCharPlaceholder(m[0]);o.setAttribute("cm-text",m[0]),uf&&vf<9?k.appendChild(Re("span",[o])):k.appendChild(o),a.col+=1}a.map.push(a.pos,a.pos+1,o),a.pos++}else{a.col+=b.length;var k=document.createTextNode(h);a.map.push(a.pos,a.pos+b.length,k),uf&&vf<9&&(j=!0),a.pos+=b.length}if(a.trailingSpace=32==h.charCodeAt(b.length-1),c||d||e||j||g){var r=c||"";d&&(r+=d),e&&(r+=e);var s=Re("span",[k],r,g);return f&&(s.title=f),a.content.appendChild(s)}a.content.appendChild(k)}}function Pd(a,b){if(a.length>1&&!/ /.test(a))return a;for(var c=b,d="",e=0;ej&&m.from<=j)break}if(m.to>=k)return a(c,d,e,f,g,h,i);a(c,d.slice(0,m.to-j),e,f,null,h,i),f=null,d=d.slice(m.to-j),j=m.to}}}function Rd(a,b,c,d){var e=!d&&c.widgetNode;e&&a.map.push(a.pos,a.pos+b,e),!d&&a.cm.display.input.needsContentAttribute&&(e||(e=a.content.appendChild(document.createElement("span"))),e.setAttribute("cm-marker",c.id)),e&&(a.cm.display.input.setUneditable(e),a.content.appendChild(e)),a.pos+=b,a.trailingSpace=!1}function Sd(a,b,c){var d=a.markedSpans,e=a.text,f=0;if(d)for(var g,h,i,j,k,l,m,n=e.length,o=0,p=1,q="",r=0;;){if(r==o){i=j=k=l=h="",m=null,r=1/0;for(var s,t=[],u=0;uo||w.collapsed&&v.to==o&&v.from==o)?(null!=v.to&&v.to!=o&&r>v.to&&(r=v.to,j=""),w.className&&(i+=" "+w.className),w.css&&(h=(h?h+";":"")+w.css),w.startStyle&&v.from==o&&(k+=" "+w.startStyle),w.endStyle&&v.to==r&&(s||(s=[])).push(w.endStyle,v.to),w.title&&!l&&(l=w.title),w.collapsed&&(!m||nd(m.marker,w)<0)&&(m=v)):v.from>o&&r>v.from&&(r=v.from)}if(s)for(var u=0;u=n)break;for(var x=Math.min(n,r);;){if(q){var y=o+q.length;if(!m){var z=y>x?q.slice(0,x-o):q;b.addToken(b,z,g?g+i:i,k,o+z.length==r?j:"",l,h)}if(y>=x){q=q.slice(x-o),o=x;break}o=y,k=""}q=e.slice(f,f=c[p++]),g=Ld(c[p++],b.cm.options)}}else for(var p=1;p1&&a.remove(h.line+1,o-1),a.insert(h.line+1,p)}ye(a,"change",a,b)}function Vd(a){this.lines=a,this.parent=null;for(var b=0,c=0;b=a.size)throw new Error("There is no line "+(b+a.first)+" in the document.");for(var c=a;!c.lines;)for(var d=0;;++d){var e=c.children[d],f=e.chunkSize();if(b1&&!a.done[a.done.length-2].ranges?(a.done.pop(),Ge(a.done)):void 0}function je(a,b,c,d){var e=a.history;e.undone.length=0;var f,g=+new Date;if((e.lastOp==d||e.lastOrigin==b.origin&&b.origin&&("+"==b.origin.charAt(0)&&a.cm&&e.lastModTime>g-a.cm.options.historyEventDelay||"*"==b.origin.charAt(0)))&&(f=ie(e,e.lastOp==d))){var h=Ge(f.changes);0==Of(b.from,b.to)&&0==Of(b.from,h.to)?h.to=ag(b):f.changes.push(ge(a,b))}else{var i=Ge(e.done);for(i&&i.ranges||me(a.sel,e.done),f={changes:[ge(a,b)],generation:e.generation},e.done.push(f);e.done.length>e.undoDepth;)e.done.shift(),e.done[0].ranges||e.done.shift()}e.done.push(c),e.generation=++e.maxGeneration,e.lastModTime=e.lastSelTime=g,e.lastOp=e.lastSelOp=d,e.lastOrigin=e.lastSelOrigin=b.origin,h||Ig(a,"historyAdded")}function ke(a,b,c,d){var e=b.charAt(0);return"*"==e||"+"==e&&c.ranges.length==d.ranges.length&&c.somethingSelected()==d.somethingSelected()&&new Date-a.history.lastSelTime<=(a.cm?a.cm.options.historyEventDelay:500)}function le(a,b,c,d){var e=a.history,f=d&&d.origin;c==e.lastSelOp||f&&e.lastSelOrigin==f&&(e.lastModTime==e.lastSelTime&&e.lastOrigin==f||ke(a,f,Ge(e.done),b))?e.done[e.done.length-1]=b:me(b,e.done),e.lastSelTime=+new Date,e.lastSelOrigin=f,e.lastSelOp=c,d&&d.clearRedo!==!1&&he(e.undone)}function me(a,b){var c=Ge(b);c&&c.ranges&&c.equals(a)||b.push(a)}function ne(a,b,c,d){var e=b["spans_"+a.id],f=0;a.iter(Math.max(a.first,c),Math.min(a.first+a.size,d),(function(c){c.markedSpans&&((e||(e=b["spans_"+a.id]={}))[f]=c.markedSpans),++f}))}function oe(a){if(!a)return null;for(var b,c=0;c-1&&(Ge(h)[l]=k[l],delete k[l])}}}return e}function re(a,b,c,d){c0?d.slice():Gg:d||Gg}function ye(a,b){function c(a){return function(){a.apply(null,f)}}var d=xe(a,b,!1);if(d.length){var e,f=Array.prototype.slice.call(arguments,2);Uf?e=Uf.delayedCallbacks:Jg?e=Jg:(e=Jg=[],setTimeout(ze,0));for(var g=0;g0}function De(a){a.prototype.on=function(a,b){Fg(this,a,b)},a.prototype.off=function(a,b){Hg(this,a,b)}}function Ee(){this.id=null}function Fe(a){for(;Rg.length<=a;)Rg.push(Ge(Rg)+" ");return Rg[a]}function Ge(a){return a[a.length-1]}function He(a,b){for(var c=0;c-1&&Vg(a))||b.test(a):Vg(a)}function Pe(a){for(var b in a)if(a.hasOwnProperty(b)&&a[b])return!1;return!0}function Qe(a){return a.charCodeAt(0)>=768&&Wg.test(a)}function Re(a,b,c,d){var e=document.createElement(a);if(c&&(e.className=c),d&&(e.style.cssText=d),"string"==typeof b)e.appendChild(document.createTextNode(b));else if(b)for(var f=0;f0;--b)a.removeChild(a.firstChild);return a}function Te(a,b){return Se(a).appendChild(b)}function Ue(){for(var a=document.activeElement;a&&a.root&&a.root.activeElement;)a=a.root.activeElement;return a}function Ve(a){return new RegExp("(^|\\s)"+a+"(?:$|\\s)\\s*")}function We(a,b){for(var c=a.split(" "),d=0;d2&&!(uf&&vf<8))}var c=Yg?Re("span","​"):Re("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px");return c.setAttribute("cm-text",""),c}function _e(a){if(null!=Zg)return Zg;var b=Te(a,document.createTextNode("AخA")),c=Tg(b,0,1).getBoundingClientRect(),d=Tg(b,1,2).getBoundingClientRect();return Se(a),!(!c||c.left==c.right)&&(Zg=d.right-c.right<3)}function af(a){if(null!=fh)return fh;var b=Te(a,Re("span","x")),c=b.getBoundingClientRect(),d=Tg(b,0,1).getBoundingClientRect();return fh=Math.abs(c.left-d.left)>1}function bf(a,b,c,d){if(!a)return d(b,c,"ltr");for(var e=!1,f=0;fb||b==c&&g.to==b)&&(d(Math.max(g.from,b),Math.min(g.to,c),1==g.level?"rtl":"ltr"),e=!0)}e||d(b,c,"ltr")}function cf(a){return a.level%2?a.to:a.from}function df(a){return a.level%2?a.from:a.to}function ef(a){var b=ee(a);return b?cf(b[0]):0}function ff(a){var b=ee(a);return b?df(Ge(b)):a.text.length}function gf(a,b){var c=Zd(a.doc,b),d=sd(c);d!=c&&(b=be(d));var e=ee(d),f=e?e[0].level%2?ff(d):ef(d):0;return Nf(b,f)}function hf(a,b){for(var c,d=Zd(a.doc,b);c=qd(d);)d=c.find(1,!0).line,b=null;var e=ee(d),f=e?e[0].level%2?ef(d):ff(d):d.text.length;return Nf(null==b?be(d):b,f)}function jf(a,b){var c=gf(a,b.line),d=Zd(a.doc,c.line),e=ee(d);if(!e||0==e[0].level){var f=Math.max(0,d.text.search(/\S/)),g=b.line==c.line&&b.ch<=f&&b.ch;return Nf(c.line,g?0:f)}return c}function kf(a,b,c){var d=a[0].level;return b==d||c!=d&&bb)return d;if(e.from==b||e.to==b){if(null!=c)return kf(a,e.level,a[c].level)?(e.from!=e.to&&(hh=c),d):(e.from!=e.to&&(hh=d),c);c=d}}return c}function mf(a,b,c,d){if(!d)return b+c;do b+=c;while(b>0&&Qe(a.text.charAt(b)));return b}function nf(a,b,c,d){var e=ee(a);if(!e)return of(a,b,c,d);for(var f=lf(e,b),g=e[f],h=mf(a,b,g.level%2?-c:c,d);;){if(h>g.from&&h0==g.level%2?g.to:g.from);if(g=e[f+=c],!g)return null;h=c>0==g.level%2?mf(a,g.to,-1,d):mf(a,g.from,1,d)}}function of(a,b,c,d){var e=b+c;if(d)for(;e>0&&Qe(a.text.charAt(e));)e+=c;return e<0||e>a.text.length?null:e}var pf=navigator.userAgent,qf=navigator.platform,rf=/gecko\/\d/i.test(pf),sf=/MSIE \d/.test(pf),tf=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(pf),uf=sf||tf,vf=uf&&(sf?document.documentMode||6:tf[1]),wf=/WebKit\//.test(pf),xf=wf&&/Qt\/\d+\.\d+/.test(pf),yf=/Chrome\//.test(pf),zf=/Opera\//.test(pf),Af=/Apple Computer/.test(navigator.vendor),Bf=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(pf),Cf=/PhantomJS/.test(pf),Df=/AppleWebKit/.test(pf)&&/Mobile\/\w+/.test(pf),Ef=Df||/Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(pf),Ff=Df||/Mac/.test(qf),Gf=/\bCrOS\b/.test(pf),Hf=/win/i.test(qf),If=zf&&pf.match(/Version\/(\d*\.\d*)/);If&&(If=Number(If[1])),If&&If>=15&&(zf=!1,wf=!0);var Jf=Ff&&(xf||zf&&(null==If||If<12.11)),Kf=rf||uf&&vf>=9,Lf=!1,Mf=!1;p.prototype=Me({update:function(a){var b=a.scrollWidth>a.clientWidth+1,c=a.scrollHeight>a.clientHeight+1,d=a.nativeBarWidth;if(c){this.vert.style.display="block",this.vert.style.bottom=b?d+"px":"0";var e=a.viewHeight-(b?d:0);this.vert.firstChild.style.height=Math.max(0,a.scrollHeight-a.clientHeight+e)+"px"}else this.vert.style.display="",this.vert.firstChild.style.height="0";if(b){this.horiz.style.display="block",this.horiz.style.right=c?d+"px":"0",this.horiz.style.left=a.barLeft+"px";var f=a.viewWidth-a.barLeft-(c?d:0);this.horiz.firstChild.style.width=a.scrollWidth-a.clientWidth+f+"px"}else this.horiz.style.display="",this.horiz.firstChild.style.width="0";return!this.checkedZeroWidth&&a.clientHeight>0&&(0==d&&this.zeroWidthHack(),this.checkedZeroWidth=!0),{right:c?d:0,bottom:b?d:0}},setScrollLeft:function(a){this.horiz.scrollLeft!=a&&(this.horiz.scrollLeft=a),this.disableHoriz&&this.enableZeroWidthBar(this.horiz,this.disableHoriz)},setScrollTop:function(a){this.vert.scrollTop!=a&&(this.vert.scrollTop=a),this.disableVert&&this.enableZeroWidthBar(this.vert,this.disableVert); -},zeroWidthHack:function(){var a=Ff&&!Bf?"12px":"18px";this.horiz.style.height=this.vert.style.width=a,this.horiz.style.pointerEvents=this.vert.style.pointerEvents="none",this.disableHoriz=new Ee,this.disableVert=new Ee},enableZeroWidthBar:function(a,b){function c(){var d=a.getBoundingClientRect(),e=document.elementFromPoint(d.left+1,d.bottom-1);e!=a?a.style.pointerEvents="none":b.set(1e3,c)}a.style.pointerEvents="auto",b.set(1e3,c)},clear:function(){var a=this.horiz.parentNode;a.removeChild(this.horiz),a.removeChild(this.vert)}},p.prototype),q.prototype=Me({update:function(){return{bottom:0,right:0}},setScrollLeft:function(){},setScrollTop:function(){},clear:function(){}},q.prototype),a.scrollbarModel={native:p,null:q},z.prototype.signal=function(a,b){Ce(a,b)&&this.events.push(arguments)},z.prototype.finish=function(){for(var a=0;a=9&&c.hasSelection&&(c.hasSelection=null),c.poll()})),Fg(f,"paste",(function(a){Ae(d,a)||$(a,d)||(d.state.pasteIncoming=!0,c.fastPoll())})),Fg(f,"cut",b),Fg(f,"copy",b),Fg(a.scroller,"paste",(function(b){Ub(a,b)||Ae(d,b)||(d.state.pasteIncoming=!0,c.focus())})),Fg(a.lineSpace,"selectstart",(function(b){Ub(a,b)||Cg(b)})),Fg(f,"compositionstart",(function(){var a=d.getCursor("from");c.composing&&c.composing.range.clear(),c.composing={start:a,range:d.markText(a,d.getCursor("to"),{className:"CodeMirror-composing"})}})),Fg(f,"compositionend",(function(){c.composing&&(c.poll(),c.composing.range.clear(),c.composing=null)}))},prepareSelection:function(){var a=this.cm,b=a.display,c=a.doc,d=Ja(a);if(a.options.moveInputWithCursor){var e=ob(a,c.sel.primary().head,"div"),f=b.wrapper.getBoundingClientRect(),g=b.lineDiv.getBoundingClientRect();d.teTop=Math.max(0,Math.min(b.wrapper.clientHeight-10,e.top+g.top-f.top)),d.teLeft=Math.max(0,Math.min(b.wrapper.clientWidth-10,e.left+g.left-f.left))}return d},showSelection:function(a){var b=this.cm,c=b.display;Te(c.cursorDiv,a.cursors),Te(c.selectionDiv,a.selection),null!=a.teTop&&(this.wrapper.style.top=a.teTop+"px",this.wrapper.style.left=a.teLeft+"px")},reset:function(a){if(!this.contextMenuPending){var b,c,d=this.cm,e=d.doc;if(d.somethingSelected()){this.prevInput="";var f=e.sel.primary();b=eh&&(f.to().line-f.from().line>100||(c=d.getSelection()).length>1e3);var g=b?"-":c||d.getSelection();this.textarea.value=g,d.state.focused&&Sg(this.textarea),uf&&vf>=9&&(this.hasSelection=g)}else a||(this.prevInput=this.textarea.value="",uf&&vf>=9&&(this.hasSelection=null));this.inaccurateSelection=b}},getField:function(){return this.textarea},supportsTouch:function(){return!1},focus:function(){if("nocursor"!=this.cm.options.readOnly&&(!Ef||Ue()!=this.textarea))try{this.textarea.focus()}catch(a){}},blur:function(){this.textarea.blur()},resetPosition:function(){this.wrapper.style.top=this.wrapper.style.left=0},receivedFocus:function(){this.slowPoll()},slowPoll:function(){var a=this;a.pollingFast||a.polling.set(this.cm.options.pollInterval,(function(){a.poll(),a.cm.state.focused&&a.slowPoll()}))},fastPoll:function(){function a(){var d=c.poll();d||b?(c.pollingFast=!1,c.slowPoll()):(b=!0,c.polling.set(60,a))}var b=!1,c=this;c.pollingFast=!0,c.polling.set(20,a)},poll:function(){var a=this.cm,b=this.textarea,c=this.prevInput;if(this.contextMenuPending||!a.state.focused||dh(b)&&!c&&!this.composing||a.isReadOnly()||a.options.disableInput||a.state.keySeq)return!1;var d=b.value;if(d==c&&!a.somethingSelected())return!1;if(uf&&vf>=9&&this.hasSelection===d||Ff&&/[\uf700-\uf7ff]/.test(d))return a.display.input.reset(),!1;if(a.doc.sel==a.display.selForContextMenu){var e=d.charCodeAt(0);if(8203!=e||c||(c="​"),8666==e)return this.reset(),this.cm.execCommand("undo")}for(var f=0,g=Math.min(c.length,d.length);f1e3||d.indexOf("\n")>-1?b.value=h.prevInput="":h.prevInput=d,h.composing&&(h.composing.range.clear(),h.composing.range=a.markText(h.composing.start,a.getCursor("to"),{className:"CodeMirror-composing"}))})),!0},ensurePolled:function(){this.pollingFast&&this.poll()&&(this.pollingFast=!1)},onKeyPress:function(){uf&&vf>=9&&(this.hasSelection=null),this.fastPoll()},onContextMenu:function(a){function b(){if(null!=g.selectionStart){var a=e.somethingSelected(),b="​"+(a?g.value:"");g.value="⇚",g.value=b,d.prevInput=a?"":"​",g.selectionStart=1,g.selectionEnd=b.length,f.selForContextMenu=e.doc.sel}}function c(){if(d.contextMenuPending=!1,d.wrapper.style.cssText=l,g.style.cssText=k,uf&&vf<9&&f.scrollbars.setScrollTop(f.scroller.scrollTop=i),null!=g.selectionStart){(!uf||uf&&vf<9)&&b();var a=0,c=function(){f.selForContextMenu==e.doc.sel&&0==g.selectionStart&&g.selectionEnd>0&&"​"==d.prevInput?Fb(e,lg.selectAll)(e):a++<10?f.detectingSelectAll=setTimeout(c,500):f.input.reset()};f.detectingSelectAll=setTimeout(c,200)}}var d=this,e=d.cm,f=e.display,g=d.textarea,h=Vb(e,a),i=f.scroller.scrollTop;if(h&&!zf){var j=e.options.resetSelectionOnContextMenu;j&&e.doc.sel.contains(h)==-1&&Fb(e,Aa)(e.doc,na(h),Mg);var k=g.style.cssText,l=d.wrapper.style.cssText;d.wrapper.style.cssText="position: absolute";var m=d.wrapper.getBoundingClientRect();if(g.style.cssText="position: absolute; width: 30px; height: 30px; top: "+(a.clientY-m.top-5)+"px; left: "+(a.clientX-m.left-5)+"px; z-index: 1000; background: "+(uf?"rgba(255, 255, 255, .05)":"transparent")+"; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);",wf)var n=window.scrollY;if(f.input.focus(),wf&&window.scrollTo(null,n),f.input.reset(),e.somethingSelected()||(g.value=d.prevInput=" "),d.contextMenuPending=!0,f.selForContextMenu=e.doc.sel,clearTimeout(f.detectingSelectAll),uf&&vf>=9&&b(),Kf){Eg(a);var o=function(){Hg(window,"mouseup",o),setTimeout(c,20)};Fg(window,"mouseup",o)}else setTimeout(c,50)}},readOnlyChanged:function(a){a||this.reset()},setUneditable:Ke,needsContentAttribute:!1},ca.prototype),ea.prototype=Me({init:function(a){function b(a){if(!Ae(d,a)){if(d.somethingSelected())Pf={lineWise:!1,text:d.getSelections()},"cut"==a.type&&d.replaceSelection("",null,"cut");else{if(!d.options.lineWiseCopyCut)return;var b=aa(d);Pf={lineWise:!0,text:b.text},"cut"==a.type&&d.operation((function(){d.setSelections(b.ranges,0,Mg),d.replaceSelection("",null,"cut")}))}if(a.clipboardData){a.clipboardData.clearData();var f=Pf.text.join("\n");if(a.clipboardData.setData("Text",f),a.clipboardData.getData("Text")==f)return void a.preventDefault()}var g=da(),h=g.firstChild;d.display.lineSpace.insertBefore(g,d.display.lineSpace.firstChild),h.value=Pf.text.join("\n");var i=document.activeElement;Sg(h),setTimeout((function(){d.display.lineSpace.removeChild(g),i.focus(),i==e&&c.showPrimarySelection()}),50)}}var c=this,d=c.cm,e=c.div=a.lineDiv;ba(e,d.options.spellcheck),Fg(e,"paste",(function(a){Ae(d,a)||$(a,d)||vf<=11&&setTimeout(Fb(d,(function(){c.pollContent()||Kb(d)})),20)})),Fg(e,"compositionstart",(function(a){var b=a.data;if(c.composing={sel:d.doc.sel,data:b,startData:b},b){var e=d.doc.sel.primary(),f=d.getLine(e.head.line),g=f.indexOf(b,Math.max(0,e.head.ch-b.length));g>-1&&g<=e.head.ch&&(c.composing.sel=na(Nf(e.head.line,g),Nf(e.head.line,g+b.length)))}})),Fg(e,"compositionupdate",(function(a){c.composing.data=a.data})),Fg(e,"compositionend",(function(a){var b=c.composing;b&&(a.data==b.startData||/\u200b/.test(a.data)||(b.data=a.data),setTimeout((function(){b.handled||c.applyComposition(b),c.composing==b&&(c.composing=null)}),50))})),Fg(e,"touchstart",(function(){c.forceCompositionEnd()})),Fg(e,"input",(function(){c.composing||!d.isReadOnly()&&c.pollContent()||Eb(c.cm,(function(){Kb(d)}))})),Fg(e,"copy",b),Fg(e,"cut",b)},prepareSelection:function(){var a=Ja(this.cm,!1);return a.focus=this.cm.state.focused,a},showSelection:function(a,b){a&&this.cm.display.view.length&&((a.focus||b)&&this.showPrimarySelection(),this.showMultipleSelections(a))},showPrimarySelection:function(){var a=window.getSelection(),b=this.cm.doc.sel.primary(),c=ha(this.cm,a.anchorNode,a.anchorOffset),d=ha(this.cm,a.focusNode,a.focusOffset);if(!c||c.bad||!d||d.bad||0!=Of(X(c,d),b.from())||0!=Of(W(c,d),b.to())){var e=fa(this.cm,b.from()),f=fa(this.cm,b.to());if(e||f){var g=this.cm.display.view,h=a.rangeCount&&a.getRangeAt(0);if(e){if(!f){var i=g[g.length-1].measure,j=i.maps?i.maps[i.maps.length-1]:i.map;f={node:j[j.length-1],offset:j[j.length-2]-j[j.length-3]}}}else e={node:g[0].measure.map[2],offset:0};try{var k=Tg(e.node,e.offset,f.offset,f.node)}catch(a){}k&&(!rf&&this.cm.state.focused?(a.collapse(e.node,e.offset),k.collapsed||a.addRange(k)):(a.removeAllRanges(),a.addRange(k)),h&&null==a.anchorNode?a.addRange(h):rf&&this.startGracePeriod()),this.rememberSelection()}}},startGracePeriod:function(){var a=this;clearTimeout(this.gracePeriod),this.gracePeriod=setTimeout((function(){a.gracePeriod=!1,a.selectionChanged()&&a.cm.operation((function(){a.cm.curOp.selectionChanged=!0}))}),20)},showMultipleSelections:function(a){Te(this.cm.display.cursorDiv,a.cursors),Te(this.cm.display.selectionDiv,a.selection)},rememberSelection:function(){var a=window.getSelection();this.lastAnchorNode=a.anchorNode,this.lastAnchorOffset=a.anchorOffset,this.lastFocusNode=a.focusNode,this.lastFocusOffset=a.focusOffset},selectionInEditor:function(){var a=window.getSelection();if(!a.rangeCount)return!1;var b=a.getRangeAt(0).commonAncestorContainer;return Xg(this.div,b)},focus:function(){"nocursor"!=this.cm.options.readOnly&&this.div.focus()},blur:function(){this.div.blur()},getField:function(){return this.div},supportsTouch:function(){return!0},receivedFocus:function(){function a(){b.cm.state.focused&&(b.pollSelection(),b.polling.set(b.cm.options.pollInterval,a))}var b=this;this.selectionInEditor()?this.pollSelection():Eb(this.cm,(function(){b.cm.curOp.selectionChanged=!0})),this.polling.set(this.cm.options.pollInterval,a)},selectionChanged:function(){var a=window.getSelection();return a.anchorNode!=this.lastAnchorNode||a.anchorOffset!=this.lastAnchorOffset||a.focusNode!=this.lastFocusNode||a.focusOffset!=this.lastFocusOffset},pollSelection:function(){if(!this.composing&&!this.gracePeriod&&this.selectionChanged()){var a=window.getSelection(),b=this.cm;this.rememberSelection();var c=ha(b,a.anchorNode,a.anchorOffset),d=ha(b,a.focusNode,a.focusOffset);c&&d&&Eb(b,(function(){Aa(b.doc,na(c,d),Mg),(c.bad||d.bad)&&(b.curOp.selectionChanged=!0)}))}},pollContent:function(){var a=this.cm,b=a.display,c=a.doc.sel.primary(),d=c.from(),e=c.to();if(d.lineb.viewTo-1)return!1;var f;if(d.line==b.viewFrom||0==(f=Nb(a,d.line)))var g=be(b.view[0].line),h=b.view[0].node;else var g=be(b.view[f].line),h=b.view[f-1].node.nextSibling;var i=Nb(a,e.line);if(i==b.view.length-1)var j=b.viewTo-1,k=b.lineDiv.lastChild;else var j=be(b.view[i+1].line)-1,k=b.view[i+1].node.previousSibling;for(var l=a.doc.splitLines(ja(a,h,k,g,j)),m=$d(a.doc,Nf(g,0),Nf(j,Zd(a.doc,j).text.length));l.length>1&&m.length>1;)if(Ge(l)==Ge(m))l.pop(),m.pop(),j--;else{if(l[0]!=m[0])break;l.shift(),m.shift(),g++}for(var n=0,o=0,p=l[0],q=m[0],r=Math.min(p.length,q.length);n1||l[0]||Of(v,w)?(Gc(a.doc,l,v,w,"+input"),!0):void 0},ensurePolled:function(){this.forceCompositionEnd()},reset:function(){this.forceCompositionEnd()},forceCompositionEnd:function(){this.composing&&!this.composing.handled&&(this.applyComposition(this.composing),this.composing.handled=!0,this.div.blur(),this.div.focus())},applyComposition:function(a){this.cm.isReadOnly()?Fb(this.cm,Kb)(this.cm):a.data&&a.data!=a.startData&&Fb(this.cm,Z)(this.cm,a.data,0,a.sel)},setUneditable:function(a){a.contentEditable="false"},onKeyPress:function(a){a.preventDefault(),this.cm.isReadOnly()||Fb(this.cm,Z)(this.cm,String.fromCharCode(null==a.charCode?a.keyCode:a.charCode),0)},readOnlyChanged:function(a){this.div.contentEditable=String("nocursor"!=a)},onContextMenu:Ke,resetPosition:Ke,needsContentAttribute:!0},ea.prototype),a.inputStyles={textarea:ca,contenteditable:ea},ka.prototype={primary:function(){return this.ranges[this.primIndex]},equals:function(a){if(a==this)return!0;if(a.primIndex!=this.primIndex||a.ranges.length!=this.ranges.length)return!1;for(var b=0;b=0&&Of(a,d.to())<=0)return c}return-1}},la.prototype={from:function(){return X(this.anchor,this.head)},to:function(){return W(this.anchor,this.head)},empty:function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch}};var Qf,Rf,Sf,Tf={left:0,right:0,top:0,bottom:0},Uf=null,Vf=0,Wf=0,Xf=0,Yf=null;uf?Yf=-.53:rf?Yf=15:yf?Yf=-.7:Af&&(Yf=-1/3);var Zf=function(a){var b=a.wheelDeltaX,c=a.wheelDeltaY;return null==b&&a.detail&&a.axis==a.HORIZONTAL_AXIS&&(b=a.detail),null==c&&a.detail&&a.axis==a.VERTICAL_AXIS?c=a.detail:null==c&&(c=a.wheelDelta),{x:b,y:c}};a.wheelEventPixels=function(a){var b=Zf(a);return b.x*=Yf,b.y*=Yf,b};var $f=new Ee,_f=null,ag=a.changeEnd=function(a){return a.text?Nf(a.from.line+a.text.length-1,Ge(a.text).length+(1==a.text.length?a.from.ch:0)):a.to};a.prototype={constructor:a,focus:function(){window.focus(),this.display.input.focus()},setOption:function(a,b){var c=this.options,d=c[a];c[a]==b&&"mode"!=a||(c[a]=b,cg.hasOwnProperty(a)&&Fb(this,cg[a])(this,b,d))},getOption:function(a){return this.options[a]},getDoc:function(){return this.doc},addKeyMap:function(a,b){this.state.keyMaps[b?"push":"unshift"](Vc(a))},removeKeyMap:function(a){for(var b=this.state.keyMaps,c=0;cc&&(Oc(this,e.head.line,a,!0),c=e.head.line,d==this.doc.sel.primIndex&&Mc(this));else{var f=e.from(),g=e.to(),h=Math.max(c,f.line);c=Math.min(this.lastLine(),g.line-(g.ch?0:1))+1;for(var i=h;i0&&wa(this.doc,d,new la(f,j[d].to()),Mg)}}})),getTokenAt:function(a,b){return Gd(this,a,b)},getLineTokens:function(a,b){return Gd(this,Nf(a),b,!0)},getTokenTypeAt:function(a){a=pa(this.doc,a);var b,c=Jd(this,Zd(this.doc,a.line)),d=0,e=(c.length-1)/2,f=a.ch;if(0==f)b=c[2];else for(;;){var g=d+e>>1;if((g?c[2*g-1]:0)>=f)e=g;else{if(!(c[2*g+1]e&&(a=e,d=!0),c=Zd(this.doc,a)}else c=a;return lb(this,c,{top:0,left:0},b||"page").top+(d?this.doc.height-de(c):0)},defaultTextHeight:function(){return tb(this.display)},defaultCharWidth:function(){return ub(this.display)},setGutterMarker:Gb((function(a,b,c){return Pc(this.doc,a,"gutter",(function(a){var d=a.gutterMarkers||(a.gutterMarkers={});return d[b]=c,!c&&Pe(d)&&(a.gutterMarkers=null),!0}))})),clearGutter:Gb((function(a){var b=this,c=b.doc,d=c.first;c.iter((function(c){c.gutterMarkers&&c.gutterMarkers[a]&&(c.gutterMarkers[a]=null,Lb(b,d,"gutter"),Pe(c.gutterMarkers)&&(c.gutterMarkers=null)),++d}))})),lineInfo:function(a){if("number"==typeof a){if(!ra(this.doc,a))return null;var b=a;if(a=Zd(this.doc,a),!a)return null}else{var b=be(a);if(null==b)return null}return{line:b,handle:a,text:a.text,gutterMarkers:a.gutterMarkers,textClass:a.textClass,bgClass:a.bgClass,wrapClass:a.wrapClass,widgets:a.widgets}},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(a,b,c,d,e){var f=this.display;a=ob(this,pa(this.doc,a));var g=a.bottom,h=a.left;if(b.style.position="absolute",b.setAttribute("cm-ignore-events","true"),this.display.input.setUneditable(b),f.sizer.appendChild(b),"over"==d)g=a.top;else if("above"==d||"near"==d){var i=Math.max(f.wrapper.clientHeight,this.doc.height),j=Math.max(f.sizer.clientWidth,f.lineSpace.clientWidth);("above"==d||a.bottom+b.offsetHeight>i)&&a.top>b.offsetHeight?g=a.top-b.offsetHeight:a.bottom+b.offsetHeight<=i&&(g=a.bottom),h+b.offsetWidth>j&&(h=j-b.offsetWidth)}b.style.top=g+"px",b.style.left=b.style.right="","right"==e?(h=f.sizer.clientWidth-b.offsetWidth,b.style.right="0px"):("left"==e?h=0:"middle"==e&&(h=(f.sizer.clientWidth-b.offsetWidth)/2),b.style.left=h+"px"),c&&Jc(this,h,g,h+b.offsetWidth,g+b.offsetHeight)},triggerOnKeyDown:Gb(mc),triggerOnKeyPress:Gb(pc),triggerOnKeyUp:oc,execCommand:function(a){if(lg.hasOwnProperty(a))return lg[a].call(null,this)},triggerElectric:Gb((function(a){_(this,a)})),findPosH:function(a,b,c,d){var e=1;b<0&&(e=-1,b=-b);for(var f=0,g=pa(this.doc,a);f0&&h(c.charAt(d-1));)--d;for(;e.5)&&g(this),Ig(this,"refresh",this)})),swapDoc:Gb((function(a){var b=this.doc;return b.cm=null,Yd(this,a),ib(this),this.display.input.reset(),this.scrollTo(a.scrollLeft,a.scrollTop),this.curOp.forceScroll=!0,ye(this,"swapDoc",this,b),b})),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}},De(a);var bg=a.defaults={},cg=a.optionHandlers={},dg=a.Init={toString:function(){return"CodeMirror.Init"}};Tc("value","",(function(a,b){a.setValue(b)}),!0),Tc("mode",null,(function(a,b){a.doc.modeOption=b,c(a)}),!0),Tc("indentUnit",2,c,!0),Tc("indentWithTabs",!1),Tc("smartIndent",!0),Tc("tabSize",4,(function(a){d(a),ib(a),Kb(a)}),!0),Tc("lineSeparator",null,(function(a,b){if(a.doc.lineSep=b,b){var c=[],d=a.doc.first;a.doc.iter((function(a){for(var e=0;;){var f=a.text.indexOf(b,e);if(f==-1)break;e=f+b.length,c.push(Nf(d,f))}d++}));for(var e=c.length-1;e>=0;e--)Gc(a.doc,b,c[e],Nf(c[e].line,c[e].ch+b.length))}})),Tc("specialChars",/[\u0000-\u001f\u007f\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g,(function(b,c,d){b.state.specialChars=new RegExp(c.source+(c.test("\t")?"":"|\t"),"g"),d!=a.Init&&b.refresh()})),Tc("specialCharPlaceholder",Nd,(function(a){a.refresh()}),!0),Tc("electricChars",!0),Tc("inputStyle",Ef?"contenteditable":"textarea",(function(){throw new Error("inputStyle can not (yet) be changed in a running editor")}),!0),Tc("spellcheck",!1,(function(a,b){a.getInputField().spellcheck=b}),!0),Tc("rtlMoveVisually",!Hf),Tc("wholeLineUpdateBefore",!0),Tc("theme","default",(function(a){h(a),i(a)}),!0),Tc("keyMap","default",(function(b,c,d){var e=Vc(c),f=d!=a.Init&&Vc(d);f&&f.detach&&f.detach(b,e),e.attach&&e.attach(b,f||null)})),Tc("extraKeys",null),Tc("lineWrapping",!1,e,!0),Tc("gutters",[],(function(a){n(a.options),i(a)}),!0),Tc("fixedGutter",!0,(function(a,b){a.display.gutters.style.left=b?y(a.display)+"px":"0",a.refresh()}),!0),Tc("coverGutterNextToScrollbar",!1,(function(a){s(a)}),!0),Tc("scrollbarStyle","native",(function(a){r(a),s(a),a.display.scrollbars.setScrollTop(a.doc.scrollTop),a.display.scrollbars.setScrollLeft(a.doc.scrollLeft)}),!0),Tc("lineNumbers",!1,(function(a){n(a.options),i(a)}),!0),Tc("firstLineNumber",1,i,!0),Tc("lineNumberFormatter",(function(a){return a}),i,!0),Tc("showCursorWhenSelecting",!1,Ia,!0),Tc("resetSelectionOnContextMenu",!0),Tc("lineWiseCopyCut",!0),Tc("readOnly",!1,(function(a,b){"nocursor"==b?(sc(a),a.display.input.blur(),a.display.disabled=!0):a.display.disabled=!1,a.display.input.readOnlyChanged(b)})),Tc("disableInput",!1,(function(a,b){b||a.display.input.reset()}),!0),Tc("dragDrop",!0,Sb),Tc("allowDropFileTypes",null),Tc("cursorBlinkRate",530),Tc("cursorScrollMargin",0),Tc("cursorHeight",1,Ia,!0),Tc("singleCursorHeightPerLine",!0,Ia,!0),Tc("workTime",100),Tc("workDelay",100),Tc("flattenSpans",!0,d,!0),Tc("addModeClass",!1,d,!0),Tc("pollInterval",100),Tc("undoDepth",200,(function(a,b){a.doc.history.undoDepth=b})),Tc("historyEventDelay",1250),Tc("viewportMargin",10,(function(a){a.refresh()}),!0),Tc("maxHighlightLength",1e4,d,!0),Tc("moveInputWithCursor",!0,(function(a,b){b||a.display.input.resetPosition()})),Tc("tabindex",null,(function(a,b){a.display.input.getField().tabIndex=b||""})),Tc("autofocus",null);var eg=a.modes={},fg=a.mimeModes={};a.defineMode=function(b,c){a.defaults.mode||"null"==b||(a.defaults.mode=b),arguments.length>2&&(c.dependencies=Array.prototype.slice.call(arguments,2)),eg[b]=c},a.defineMIME=function(a,b){fg[a]=b},a.resolveMode=function(b){if("string"==typeof b&&fg.hasOwnProperty(b))b=fg[b];else if(b&&"string"==typeof b.name&&fg.hasOwnProperty(b.name)){var c=fg[b.name];"string"==typeof c&&(c={name:c}),b=Le(c,b),b.name=c.name}else{if("string"==typeof b&&/^[\w\-]+\/[\w\-]+\+xml$/.test(b))return a.resolveMode("application/xml");if("string"==typeof b&&/^[\w\-]+\/[\w\-]+\+json$/.test(b))return a.resolveMode("application/json")}return"string"==typeof b?{name:b}:b||{name:"null"}},a.getMode=function(b,c){var c=a.resolveMode(c),d=eg[c.name];if(!d)return a.getMode(b,"text/plain");var e=d(b,c);if(gg.hasOwnProperty(c.name)){var f=gg[c.name];for(var g in f)f.hasOwnProperty(g)&&(e.hasOwnProperty(g)&&(e["_"+g]=e[g]),e[g]=f[g])}if(e.name=c.name,c.helperType&&(e.helperType=c.helperType),c.modeProps)for(var g in c.modeProps)e[g]=c.modeProps[g];return e},a.defineMode("null",(function(){return{token:function(a){a.skipToEnd()}}})),a.defineMIME("text/plain","null");var gg=a.modeExtensions={};a.extendMode=function(a,b){var c=gg.hasOwnProperty(a)?gg[a]:gg[a]={};Me(b,c)},a.defineExtension=function(b,c){a.prototype[b]=c},a.defineDocExtension=function(a,b){zg.prototype[a]=b},a.defineOption=Tc;var hg=[];a.defineInitHook=function(a){hg.push(a)};var ig=a.helpers={};a.registerHelper=function(b,c,d){ig.hasOwnProperty(b)||(ig[b]=a[b]={_global:[]}),ig[b][c]=d},a.registerGlobalHelper=function(b,c,d,e){a.registerHelper(b,c,e),ig[b]._global.push({pred:d,val:e})};var jg=a.copyState=function(a,b){if(b===!0)return b;if(a.copyState)return a.copyState(b);var c={};for(var d in b){var e=b[d];e instanceof Array&&(e=e.concat([])),c[d]=e}return c},kg=a.startState=function(a,b,c){return!a.startState||a.startState(b,c)};a.innerMode=function(a,b){for(;a.innerMode;){var c=a.innerMode(b);if(!c||c.mode==a)break;b=c.state,a=c.mode}return c||{mode:a,state:b}};var lg=a.commands={selectAll:function(a){a.setSelection(Nf(a.firstLine(),0),Nf(a.lastLine()),Mg)},singleSelection:function(a){a.setSelection(a.getCursor("anchor"),a.getCursor("head"),Mg)},killLine:function(a){Qc(a,(function(b){if(b.empty()){var c=Zd(a.doc,b.head.line).text.length;return b.head.ch==c&&b.head.line0)e=new Nf(e.line,e.ch+1),a.replaceRange(f.charAt(e.ch-1)+f.charAt(e.ch-2),Nf(e.line,e.ch-2),e,"+transpose");else if(e.line>a.doc.first){var g=Zd(a.doc,e.line-1).text;g&&a.replaceRange(f.charAt(0)+a.doc.lineSeparator()+g.charAt(g.length-1),Nf(e.line-1,g.length-1),Nf(e.line,1),"+transpose")}c.push(new la(e,e))}a.setSelections(c)}))},newlineAndIndent:function(a){Eb(a,(function(){for(var b=a.listSelections().length,c=0;c=this.string.length},sol:function(){return this.pos==this.lineStart},peek:function(){return this.string.charAt(this.pos)||void 0},next:function(){if(this.posb},eatSpace:function(){for(var a=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>a},skipToEnd:function(){this.pos=this.string.length},skipTo:function(a){var b=this.string.indexOf(a,this.pos);if(b>-1)return this.pos=b,!0},backUp:function(a){this.pos-=a},column:function(){return this.lastColumnPos0?null:(d&&b!==!1&&(this.pos+=d[0].length),d)}var e=function(a){return c?a.toLowerCase():a},f=this.string.substr(this.pos,a.length);if(e(f)==e(a))return b!==!1&&(this.pos+=a.length),!0},current:function(){return this.string.slice(this.start,this.pos)},hideFirstChars:function(a,b){this.lineStart+=a;try{return b()}finally{this.lineStart-=a}}};var rg=0,sg=a.TextMarker=function(a,b){this.lines=[],this.type=b,this.doc=a,this.id=++rg};De(sg),sg.prototype.clear=function(){if(!this.explicitlyCleared){var a=this.doc.cm,b=a&&!a.curOp;if(b&&vb(a),Ce(this,"clear")){var c=this.find();c&&ye(this,"clear",c.from,c.to)}for(var d=null,e=null,f=0;fa.display.maxLineLength&&(a.display.maxLine=i,a.display.maxLineLength=j,a.display.maxLineChanged=!0)}null!=d&&a&&this.collapsed&&Kb(a,d,e+1),this.lines.length=0,this.explicitlyCleared=!0,this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,a&&Da(a.doc)),a&&ye(a,"markerCleared",a,this),b&&xb(a),this.parent&&this.parent.clear()}},sg.prototype.find=function(a,b){null==a&&"bookmark"==this.type&&(a=1);for(var c,d,e=0;e1||!(this.children[0]instanceof Vd))){var h=[];this.collapse(h),this.children=[new Vd(h)],this.children[0].parent=this}},collapse:function(a){for(var b=0;b50){for(var g=e.lines.length%25+25,h=g;h10);a.parent.maybeSpill()}},iterN:function(a,b,c){for(var d=0;d=0;f--)Ac(this,d[f]);h?za(this,h):this.cm&&Mc(this.cm)})),undo:Hb((function(){Cc(this,"undo")})),redo:Hb((function(){Cc(this,"redo")})),undoSelection:Hb((function(){Cc(this,"undo",!0)})),redoSelection:Hb((function(){Cc(this,"redo",!0)})),setExtending:function(a){this.extend=a},getExtending:function(){return this.extend},historySize:function(){for(var a=this.history,b=0,c=0,d=0;d=a.ch)&&b.push(e.marker.parent||e.marker)}return b},findMarks:function(a,b,c){a=pa(this,a),b=pa(this,b);var d=[],e=a.line;return this.iter(a.line,b.line+1,(function(f){var g=f.markedSpans;if(g)for(var h=0;h=i.to||null==i.from&&e!=a.line||null!=i.from&&e==b.line&&i.from>=b.ch||c&&!c(i.marker)||d.push(i.marker.parent||i.marker)}++e})),d},getAllMarks:function(){var a=[];return this.iter((function(b){var c=b.markedSpans;if(c)for(var d=0;da?(b=a,!0):(a-=f,void++c)})),pa(this,Nf(c,b))},indexFromPos:function(a){a=pa(this,a);var b=a.ch;if(a.lineb&&(b=a.from),null!=a.to&&a.to=b)return g+(b-f);g+=h-f,g+=c-g%c,f=h+1}},Qg=a.findColumn=function(a,b,c){for(var d=0,e=0;;){var f=a.indexOf("\t",d);f==-1&&(f=a.length);var g=f-d;if(f==a.length||e+g>=b)return d+Math.min(g,b-e);if(e+=f-d,e+=c-e%c,d=f+1,e>=b)return d}},Rg=[""],Sg=function(a){a.select()};Df?Sg=function(a){a.selectionStart=0,a.selectionEnd=a.value.length}:uf&&(Sg=function(a){try{a.select()}catch(a){}});var Tg,Ug=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,Vg=a.isWordChar=function(a){return/\w/.test(a)||a>"€"&&(a.toUpperCase()!=a.toLowerCase()||Ug.test(a))},Wg=/[\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]/;Tg=document.createRange?function(a,b,c,d){var e=document.createRange();return e.setEnd(d||a,c),e.setStart(a,b),e}:function(a,b,c){var d=document.body.createTextRange();try{d.moveToElementText(a.parentNode)}catch(a){return d}return d.collapse(!0),d.moveEnd("character",c),d.moveStart("character",b),d};var Xg=a.contains=function(a,b){if(3==b.nodeType&&(b=b.parentNode),a.contains)return a.contains(b);do if(11==b.nodeType&&(b=b.host),b==a)return!0;while(b=b.parentNode)};uf&&vf<11&&(Ue=function(){try{return document.activeElement}catch(a){return document.body}});var Yg,Zg,$g=a.rmClass=function(a,b){var c=a.className,d=Ve(b).exec(c);if(d){var e=c.slice(d.index+d[0].length);a.className=c.slice(0,d.index)+(e?d[1]+e:"")}},_g=a.addClass=function(a,b){var c=a.className;Ve(b).test(c)||(a.className+=(c?" ":"")+b)},ah=!1,bh=(function(){if(uf&&vf<9)return!1;var a=Re("div");return"draggable"in a||"dragDrop"in a})(),ch=a.splitLines=3!="\n\nb".split(/\n/).length?function(a){for(var b=0,c=[],d=a.length;b<=d;){var e=a.indexOf("\n",b);e==-1&&(e=a.length);var f=a.slice(b,"\r"==a.charAt(e-1)?e-1:e),g=f.indexOf("\r");g!=-1?(c.push(f.slice(0,g)),b+=g+1):(c.push(f),b=e+1)}return c}:function(a){return a.split(/\r\n?|\n/)},dh=window.getSelection?function(a){try{return a.selectionStart!=a.selectionEnd}catch(a){return!1}}:function(a){try{var b=a.ownerDocument.selection.createRange()}catch(a){}return!(!b||b.parentElement()!=a)&&0!=b.compareEndPoints("StartToEnd",b)},eh=(function(){var a=Re("div");return"oncopy"in a||(a.setAttribute("oncopy","return;"),"function"==typeof a.oncopy)})(),fh=null,gh=a.keyNames={3:"Enter",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:"/",127:"Delete",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'",63232:"Up",63233:"Down",63234:"Left",63235:"Right",63272:"Delete",63273:"Home",63275:"End",63276:"PageUp",63277:"PageDown",63302:"Insert"};!(function(){for(var a=0;a<10;a++)gh[a+48]=gh[a+96]=String(a);for(var a=65;a<=90;a++)gh[a]=String.fromCharCode(a);for(var a=1;a<=12;a++)gh[a+111]=gh[a+63235]="F"+a})();var hh,ih=(function(){function a(a){return a<=247?c.charAt(a):1424<=a&&a<=1524?"R":1536<=a&&a<=1773?d.charAt(a-1536):1774<=a&&a<=2220?"r":8192<=a&&a<=8203?"w":8204==a?"b":"L"}function b(a,b,c){this.level=a,this.from=b,this.to=c}var c="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",d="rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm",e=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,f=/[stwN]/,g=/[LRr]/,h=/[Lb1n]/,i=/[1n]/,j="L";return function(c){if(!e.test(c))return!1;for(var d,k=c.length,l=[],m=0;m0;--b)a.removeChild(a.firstChild);return a}function c(a,c){return b(a).appendChild(c)}function d(a,b,c,d){var e=document.createElement(a);if(c&&(e.className=c),d&&(e.style.cssText=d),"string"==typeof b)e.appendChild(document.createTextNode(b));else if(b)for(var f=0;f=b)return g+(b-f);g+=h-f,g+=c-g%c,f=h+1}}function k(){this.id=null}function l(a,b){for(var c=0;c=b)return d+Math.min(g,b-e);if(e+=f-d,e+=c-e%c,d=f+1,e>=b)return d}}function n(a){for(;Hg.length<=a;)Hg.push(o(Hg)+" ");return Hg[a]}function o(a){return a[a.length-1]}function p(a,b){for(var c=[],d=0;d"€"&&(a.toUpperCase()!=a.toLowerCase()||Ig.test(a))}function u(a,b){return b?!!(b.source.indexOf("\\w")>-1&&t(a))||b.test(a):t(a)}function v(a){for(var b in a)if(a.hasOwnProperty(b)&&a[b])return!1;return!0}function w(a){return a.charCodeAt(0)>=768&&Jg.test(a)}function x(a,b,c){var e=this;this.input=c,e.scrollbarFiller=d("div",null,"CodeMirror-scrollbar-filler"),e.scrollbarFiller.setAttribute("cm-not-content","true"),e.gutterFiller=d("div",null,"CodeMirror-gutter-filler"),e.gutterFiller.setAttribute("cm-not-content","true"),e.lineDiv=d("div",null,"CodeMirror-code"),e.selectionDiv=d("div",null,null,"position: relative; z-index: 1"),e.cursorDiv=d("div",null,"CodeMirror-cursors"),e.measure=d("div",null,"CodeMirror-measure"),e.lineMeasure=d("div",null,"CodeMirror-measure"),e.lineSpace=d("div",[e.measure,e.lineMeasure,e.selectionDiv,e.cursorDiv,e.lineDiv],null,"position: relative; outline: none"),e.mover=d("div",[d("div",[e.lineSpace],"CodeMirror-lines")],null,"position: relative"),e.sizer=d("div",[e.mover],"CodeMirror-sizer"),e.sizerWidth=null,e.heightForcer=d("div",null,null,"position: absolute; height: "+Cg+"px; width: 1px;"),e.gutters=d("div",null,"CodeMirror-gutters"),e.lineGutter=null,e.scroller=d("div",[e.sizer,e.heightForcer,e.gutters],"CodeMirror-scroll"),e.scroller.setAttribute("tabIndex","-1"),e.wrapper=d("div",[e.scrollbarFiller,e.gutterFiller,e.scroller],"CodeMirror"),fg&&gg<8&&(e.gutters.style.zIndex=-1,e.scroller.style.paddingRight=0),hg||cg&&pg||(e.scroller.draggable=!0),a&&(a.appendChild?a.appendChild(e.wrapper):a(e.wrapper)),e.viewFrom=e.viewTo=b.first,e.reportedViewFrom=e.reportedViewTo=b.first,e.view=[],e.renderedView=null,e.externalMeasured=null,e.viewOffset=0,e.lastWrapHeight=e.lastWrapWidth=0,e.updateLineNumbers=null,e.nativeBarWidth=e.barHeight=e.barWidth=0,e.scrollbarsClipped=!1,e.lineNumWidth=e.lineNumInnerWidth=e.lineNumChars=null,e.alignWidgets=!1,e.cachedCharWidth=e.cachedTextHeight=e.cachedPaddingH=null,e.maxLine=null,e.maxLineLength=0,e.maxLineChanged=!1,e.wheelDX=e.wheelDY=e.wheelStartX=e.wheelStartY=null,e.shift=!1,e.selForContextMenu=null,e.activeTouch=null,c.init(e)}function y(a,b){if(b-=a.first,b<0||b>=a.size)throw new Error("There is no line "+(b+a.first)+" in the document.");for(var c=a;!c.lines;)for(var d=0;;++d){var e=c.children[d],f=e.chunkSize();if(b=a.first&&bc?G(c,y(a,c).text.length):N(b,y(a,b.line).text.length)}function N(a,b){var c=a.ch;return null==c||c>b?G(a.line,b):c<0?G(a.line,0):a}function O(a,b){for(var c=[],d=0;d=b:f.to>b);(d||(d=[])).push(new R(g,f.from,i?null:f.to))}}return d}function W(a,b,c){var d;if(a)for(var e=0;e=b:f.to>b);if(h||f.from==b&&"bookmark"==g.type&&(!c||f.marker.insertLeft)){var i=null==f.from||(g.inclusiveLeft?f.from<=b:f.from0&&h)for(var v=0;v0)){var k=[i,1],m=H(j.from,h.from),n=H(j.to,h.to);(m<0||!g.inclusiveLeft&&!m)&&k.push({from:j.from,to:h.from}),(n>0||!g.inclusiveRight&&!n)&&k.push({from:h.to,to:j.to}),e.splice.apply(e,k),i+=k.length-1}}return e}function $(a){var b=a.markedSpans;if(b){for(var c=0;c=0&&l<=0||k<=0&&l>=0)&&(k<=0&&(i.marker.inclusiveRight&&e.inclusiveLeft?H(j.to,c)>=0:H(j.to,c)>0)||k>=0&&(i.marker.inclusiveRight&&e.inclusiveLeft?H(j.from,d)<=0:H(j.from,d)<0)))return!0}}}function ha(a){for(var b;b=ea(a);)a=b.find(-1,!0).line;return a}function ia(a){for(var b,c;b=fa(a);)a=b.find(1,!0).line,(c||(c=[])).push(a);return c}function ja(a,b){var c=y(a,b),d=ha(c);return c==d?b:C(d)}function ka(a,b){if(b>a.lastLine())return b;var c,d=y(a,b);if(!la(a,d))return b;for(;c=fa(d);)d=c.find(1,!0).line;return C(d)+1}function la(a,b){var c=Lg&&b.markedSpans;if(c)for(var d=void 0,e=0;eb.maxLineLength&&(b.maxLineLength=c,b.maxLine=a)}))}function qa(a,b,c,d){if(!a)return d(b,c,"ltr");for(var e=!1,f=0;fb||b==c&&g.to==b)&&(d(Math.max(g.from,b),Math.min(g.to,c),1==g.level?"rtl":"ltr"),e=!0)}e||d(b,c,"ltr")}function ra(a){return a.level%2?a.to:a.from}function sa(a){return a.level%2?a.from:a.to}function ta(a){var b=Aa(a);return b?ra(b[0]):0}function ua(a){var b=Aa(a);return b?sa(o(b)):a.text.length}function va(a,b,c){var d=a[0].level;return b==d||c!=d&&bb)return d;if(e.from==b||e.to==b){if(null!=c)return va(a,e.level,a[c].level)?(e.from!=e.to&&(Mg=c),d):(e.from!=e.to&&(Mg=d),c);c=d}}return c}function xa(a,b,c,d){if(!d)return b+c;do b+=c;while(b>0&&w(a.text.charAt(b)));return b}function ya(a,b,c,d){var e=Aa(a);if(!e)return za(a,b,c,d);for(var f=wa(e,b),g=e[f],h=xa(a,b,g.level%2?-c:c,d);;){if(h>g.from&&h0==g.level%2?g.to:g.from);if(g=e[f+=c],!g)return null;h=c>0==g.level%2?xa(a,g.to,-1,d):xa(a,g.from,1,d)}}function za(a,b,c,d){var e=b+c;if(d)for(;e>0&&w(a.text.charAt(e));)e+=c;return e<0||e>a.text.length?null:e}function Aa(a){var b=a.order;return null==b&&(b=a.order=Ng(a.text)),b}function Ba(a,b,c){var d=a._handlers&&a._handlers[b];return c?d&&d.length>0?d.slice():Pg:d||Pg}function Ca(a,b,c){if(a.removeEventListener)a.removeEventListener(b,c,!1);else if(a.detachEvent)a.detachEvent("on"+b,c);else for(var d=Ba(a,b,!1),e=0;e0}function Ha(a){a.prototype.on=function(a,b){Og(this,a,b)},a.prototype.off=function(a,b){Ca(this,a,b)}}function Ia(a){a.preventDefault?a.preventDefault():a.returnValue=!1}function Ja(a){a.stopPropagation?a.stopPropagation():a.cancelBubble=!0}function Ka(a){return null!=a.defaultPrevented?a.defaultPrevented:0==a.returnValue}function La(a){Ia(a),Ja(a)}function Ma(a){return a.target||a.srcElement}function Na(a){var b=a.which;return null==b&&(1&a.button?b=1:2&a.button?b=3:4&a.button&&(b=2)),qg&&a.ctrlKey&&1==b&&(b=3),b}function Oa(a){if(null==Ag){var b=d("span","​");c(a,d("span",[b,document.createTextNode("x")])),0!=a.firstChild.offsetHeight&&(Ag=b.offsetWidth<=1&&b.offsetHeight>2&&!(fg&&gg<8))}var e=Ag?d("span","​"):d("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px");return e.setAttribute("cm-text",""),e}function Pa(a){if(null!=Bg)return Bg;var d=c(a,document.createTextNode("AخA")),e=ug(d,0,1).getBoundingClientRect(),f=ug(d,1,2).getBoundingClientRect();return b(a),!(!e||e.left==e.right)&&(Bg=f.right-e.right<3)}function Qa(a){if(null!=Ug)return Ug;var b=c(a,d("span","x")),e=b.getBoundingClientRect(),f=ug(b,0,1).getBoundingClientRect();return Ug=Math.abs(e.left-f.left)>1}function Ra(a,b){arguments.length>2&&(b.dependencies=Array.prototype.slice.call(arguments,2)),Vg[a]=b}function Sa(a,b){Wg[a]=b}function Ta(a){if("string"==typeof a&&Wg.hasOwnProperty(a))a=Wg[a];else if(a&&"string"==typeof a.name&&Wg.hasOwnProperty(a.name)){var b=Wg[a.name];"string"==typeof b&&(b={name:b}),a=s(b,a),a.name=b.name}else{if("string"==typeof a&&/^[\w\-]+\/[\w\-]+\+xml$/.test(a))return Ta("application/xml");if("string"==typeof a&&/^[\w\-]+\/[\w\-]+\+json$/.test(a))return Ta("application/json")}return"string"==typeof a?{name:a}:a||{name:"null"}}function Ua(a,b){b=Ta(b);var c=Vg[b.name];if(!c)return Ua(a,"text/plain");var d=c(a,b);if(Xg.hasOwnProperty(b.name)){var e=Xg[b.name];for(var f in e)e.hasOwnProperty(f)&&(d.hasOwnProperty(f)&&(d["_"+f]=d[f]),d[f]=e[f])}if(d.name=b.name,b.helperType&&(d.helperType=b.helperType),b.modeProps)for(var g in b.modeProps)d[g]=b.modeProps[g];return d}function Va(a,b){var c=Xg.hasOwnProperty(a)?Xg[a]:Xg[a]={};i(b,c)}function Wa(a,b){if(b===!0)return b;if(a.copyState)return a.copyState(b);var c={};for(var d in b){var e=b[d];e instanceof Array&&(e=e.concat([])),c[d]=e}return c}function Xa(a,b){for(var c;a.innerMode&&(c=a.innerMode(b),c&&c.mode!=a);)b=c.state,a=c.mode;return c||{mode:a,state:b}}function Ya(a,b,c){return!a.startState||a.startState(b,c)}function Za(a,b,c,d){var e=[a.state.modeGen],f={};fb(a,b.text,a.doc.mode,c,(function(a,b){return e.push(a,b)}),f,d);for(var g=function(c){var d=a.state.overlays[c],g=1,h=0;fb(a,b.text,d.mode,!0,(function(a,b){for(var c=g;ha&&e.splice(g,1,a,e[g+1],f),g+=2,h=Math.min(a,f)}if(b)if(d.opaque)e.splice(c,g-c,a,"overlay "+b),g=c+2;else for(;ca.options.maxHighlightLength?Wa(a.doc.mode,d):d);b.stateAfter=d,b.styles=e.styles,e.classes?b.styleClasses=e.classes:b.styleClasses&&(b.styleClasses=null),c===a.doc.frontier&&a.doc.frontier++}return b.styles}function _a(a,b,c){var d=a.doc,e=a.display;if(!d.mode.startState)return!0;var f=gb(a,b,c),g=f>d.first&&y(d,f-1).stateAfter;return g=g?Wa(d.mode,g):Ya(d.mode),d.iter(f,b,(function(c){ab(a,c.text,g);var h=f==b-1||f%5==0||f>=e.viewFrom&&fb.start)return f}throw new Error("Mode "+a.name+" failed to advance stream.")}function db(a,b,c,d){var e,f=function(a){return{start:l.start,end:l.pos,string:l.current(),type:e||null,state:a?Wa(g.mode,k):k}},g=a.doc,h=g.mode;b=M(g,b);var i,j=y(g,b.line),k=_a(a,b.line,c),l=new Yg(j.text,a.options.tabSize);for(d&&(i=[]);(d||l.posa.options.maxHighlightLength?(h=!1,g&&ab(a,b,d,l.pos),l.pos=b.length,i=null):i=eb(cb(c,l,d,m),f),m){var n=m[0].name;n&&(i="m-"+(i?n+" "+i:n))}if(!h||k!=i){for(;jg;--h){if(h<=f.first)return f.first;var i=y(f,h-1);if(i.stateAfter&&(!c||h<=f.frontier))return h;var k=j(i.text,null,a.options.tabSize);(null==e||d>k)&&(e=h-1,d=k)}return e}function hb(a,b,c){this.text=a,_(this,b),this.height=c?c(this):1}function ib(a,b,c,d){a.text=b,a.stateAfter&&(a.stateAfter=null),a.styles&&(a.styles=null),null!=a.order&&(a.order=null),$(a),_(a,c);var e=d?d(a):1;e!=a.height&&B(a,e)}function jb(a){a.parent=null,$(a)}function kb(a,b){if(!a||/^\s*$/.test(a))return null;var c=b.addModeClass?_g:$g;return c[a]||(c[a]=a.replace(/\S+/g,"cm-$&"))}function lb(a,b){var c=d("span",null,null,hg?"padding-right: .1px":null),e={pre:d("pre",[c],"CodeMirror-line"),content:c,col:0,pos:0,cm:a,trailingSpace:!1,splitSpaces:(fg||hg)&&a.getOption("lineWrapping")};b.measure={};for(var f=0;f<=(b.rest?b.rest.length:0);f++){var h=f?b.rest[f-1]:b.line,i=void 0;e.pos=0,e.addToken=nb,Pa(a.display.measure)&&(i=Aa(h))&&(e.addToken=pb(e.addToken,i)),e.map=[];var j=b!=a.display.externalMeasured&&C(h);rb(h,e,$a(a,h,j)),h.styleClasses&&(h.styleClasses.bgClass&&(e.bgClass=g(h.styleClasses.bgClass,e.bgClass||"")),h.styleClasses.textClass&&(e.textClass=g(h.styleClasses.textClass,e.textClass||""))),0==e.map.length&&e.map.push(0,0,e.content.appendChild(Oa(a.display.measure))),0==f?(b.measure.map=e.map,b.measure.cache={}):((b.measure.maps||(b.measure.maps=[])).push(e.map),(b.measure.caches||(b.measure.caches=[])).push({}))}if(hg){var k=e.content.lastChild;(/\bcm-tab\b/.test(k.className)||k.querySelector&&k.querySelector(".cm-tab"))&&(e.content.className="cm-tab-wrap-hack")}return Da(a,"renderLine",a,b.line,e.pre),e.pre.className&&(e.textClass=g(e.pre.className,e.textClass||"")),e}function mb(a){var b=d("span","•","cm-invalidchar");return b.title="\\u"+a.charCodeAt(0).toString(16),b.setAttribute("aria-label",b.title),b}function nb(a,b,c,e,f,g,h){if(b){var i,j=a.splitSpaces?ob(b,a.trailingSpace):b,k=a.cm.state.specialChars,l=!1;if(k.test(b)){i=document.createDocumentFragment();for(var m=0;;){k.lastIndex=m;var o=k.exec(b),p=o?o.index-m:b.length-m;if(p){var q=document.createTextNode(j.slice(m,m+p));fg&&gg<9?i.appendChild(d("span",[q])):i.appendChild(q),a.map.push(a.pos,a.pos+p,q),a.col+=p,a.pos+=p}if(!o)break;m+=p+1;var r=void 0;if("\t"==o[0]){var s=a.cm.options.tabSize,t=s-a.col%s;r=i.appendChild(d("span",n(t),"cm-tab")),r.setAttribute("role","presentation"),r.setAttribute("cm-text","\t"),a.col+=t}else"\r"==o[0]||"\n"==o[0]?(r=i.appendChild(d("span","\r"==o[0]?"␍":"␤","cm-invalidchar")),r.setAttribute("cm-text",o[0]),a.col+=1):(r=a.cm.options.specialCharPlaceholder(o[0]),r.setAttribute("cm-text",o[0]),fg&&gg<9?i.appendChild(d("span",[r])):i.appendChild(r),a.col+=1);a.map.push(a.pos,a.pos+1,r),a.pos++}}else a.col+=b.length,i=document.createTextNode(j),a.map.push(a.pos,a.pos+b.length,i),fg&&gg<9&&(l=!0),a.pos+=b.length;if(a.trailingSpace=32==j.charCodeAt(b.length-1),c||e||f||l||h){var u=c||"";e&&(u+=e),f&&(u+=f);var v=d("span",[i],u,h);return g&&(v.title=g),a.content.appendChild(v)}a.content.appendChild(i)}}function ob(a,b){if(a.length>1&&!/ /.test(a))return a;for(var c=b,d="",e=0;ej&&l.from<=j));m++);if(l.to>=k)return a(c,d,e,f,g,h,i);a(c,d.slice(0,l.to-j),e,f,null,h,i),f=null,d=d.slice(l.to-j),j=l.to}}}function qb(a,b,c,d){var e=!d&&c.widgetNode;e&&a.map.push(a.pos,a.pos+b,e),!d&&a.cm.display.input.needsContentAttribute&&(e||(e=a.content.appendChild(document.createElement("span"))),e.setAttribute("cm-marker",c.id)),e&&(a.cm.display.input.setUneditable(e),a.content.appendChild(e)),a.pos+=b,a.trailingSpace=!1}function rb(a,b,c){var d=a.markedSpans,e=a.text,f=0;if(d)for(var g,h,i,j,k,l,m,n=e.length,o=0,p=1,q="",r=0;;){if(r==o){i=j=k=l=h="",m=null,r=1/0;for(var s=[],t=void 0,u=0;uo||w.collapsed&&v.to==o&&v.from==o)?(null!=v.to&&v.to!=o&&r>v.to&&(r=v.to,j=""),w.className&&(i+=" "+w.className),w.css&&(h=(h?h+";":"")+w.css),w.startStyle&&v.from==o&&(k+=" "+w.startStyle),w.endStyle&&v.to==r&&(t||(t=[])).push(w.endStyle,v.to),w.title&&!l&&(l=w.title),w.collapsed&&(!m||ca(m.marker,w)<0)&&(m=v)):v.from>o&&r>v.from&&(r=v.from)}if(t)for(var x=0;x=n)break;for(var z=Math.min(n,r);;){if(q){var A=o+q.length;if(!m){var B=A>z?q.slice(0,z-o):q;b.addToken(b,B,g?g+i:i,k,o+B.length==r?j:"",l,h)}if(A>=z){q=q.slice(z-o),o=z;break}o=A,k=""}q=e.slice(f,f=c[p++]),g=kb(c[p++],b.cm.options)}}else for(var C=1;C2&&f.push((i.bottom+j.top)/2-c.top)}}f.push(c.bottom-c.top)}}function Ub(a,b,c){if(a.line==b)return{map:a.measure.map,cache:a.measure.cache};for(var d=0;dc)return{map:a.measure.maps[e],cache:a.measure.caches[e],before:!0}}function Vb(a,b){b=ha(b);var d=C(b),e=a.display.externalMeasured=new sb(a.doc,b,d);e.lineN=d;var f=e.built=lb(a,e);return e.text=f.pre,c(a.display.lineMeasure,f.pre),e}function Wb(a,b,c,d){return Zb(a,Yb(a,b),c,d)}function Xb(a,b){if(b>=a.display.viewFrom&&b=c.lineN&&bb)&&(f=i-h,e=f-1,b>=i&&(g="right")),null!=e){if(d=a[j+2],h==i&&c==(d.insertLeft?"left":"right")&&(g=c),"left"==c&&0==e)for(;j&&a[j-2]==a[j-3]&&a[j-1].insertLeft;)d=a[(j-=3)+2],g="left";if("right"==c&&e==i-h)for(;j=0&&(c=a[e]).left==c.right;e--);return c}function ac(a,b,c,d){var e,f=$b(b.map,c,d),g=f.node,h=f.start,i=f.end,j=f.collapse;if(3==g.nodeType){for(var k=0;k<4;k++){for(;h&&w(b.line.text.charAt(f.coverStart+h));)--h;for(;f.coverStart+i0&&(j=d="right"); +var l;e=a.options.lineWrapping&&(l=g.getClientRects()).length>1?l["right"==d?l.length-1:0]:g.getBoundingClientRect()}if(fg&&gg<9&&!h&&(!e||!e.left&&!e.right)){var m=g.parentNode.getClientRects()[0];e=m?{left:m.left,right:m.left+qc(a.display),top:m.top,bottom:m.bottom}:ch}for(var n=e.top-b.rect.top,o=e.bottom-b.rect.top,p=(n+o)/2,q=b.view.measure.heights,r=0;rc.from?g(a-1):g(a,d)}d=d||y(a.doc,b.line),e||(e=Yb(a,d));var i=Aa(d),j=b.ch;if(!i)return g(j);var k=wa(i,j),l=h(j,k);return null!=Mg&&(l.other=h(j,Mg)),l}function lc(a,b){var c=0;b=M(a.doc,b),a.options.lineWrapping||(c=qc(a.display)*b.ch);var d=y(a.doc,b.line),e=na(d)+Nb(a.display);return{left:c,right:c,top:e,bottom:e+d.height}}function mc(a,b,c,d){var e=G(a,b);return e.xRel=d,c&&(e.outside=!0),e}function nc(a,b,c){var d=a.doc;if(c+=a.display.viewOffset,c<0)return mc(d.first,0,!0,-1);var e=D(d,c),f=d.first+d.size-1;if(e>f)return mc(d.first+d.size-1,y(d,f).text.length,!0,1);b<0&&(b=0);for(var g=y(d,e);;){var h=oc(a,g,e,b,c),i=fa(g),j=i&&i.find(0,!0);if(!i||!(h.ch>j.from.ch||h.ch==j.from.ch&&h.xRel>0))return h;e=C(g=j.to.line)}}function oc(a,b,c,d,e){function f(d){var e=kc(a,G(c,d),"line",b,j);return h=!0,g>e.bottom?e.left-i:gq)return mc(c,n,r,1);for(;;){if(k?n==m||n==ya(b,m,1):n-m<=1){var s=d0&&s1){var v=Zb(a,j,s,"right");g<=v.bottom&&g>=v.top&&Math.abs(d-v.right)1?1:0);return x}var y=Math.ceil(l/2),z=m+y;if(k){z=m;for(var A=0;Ad?(n=z,q=B,(r=h)&&(q+=1e3),l=y):(m=z,o=B,p=h,l-=y)}}function pc(a){if(null!=a.cachedTextHeight)return a.cachedTextHeight;if(null==Zg){Zg=d("pre");for(var e=0;e<49;++e)Zg.appendChild(document.createTextNode("x")),Zg.appendChild(d("br"));Zg.appendChild(document.createTextNode("x"))}c(a.measure,Zg);var f=Zg.offsetHeight/50;return f>3&&(a.cachedTextHeight=f),b(a.measure),f||1}function qc(a){if(null!=a.cachedCharWidth)return a.cachedCharWidth;var b=d("span","xxxxxxxxxx"),e=d("pre",[b]);c(a.measure,e);var f=b.getBoundingClientRect(),g=(f.right-f.left)/10;return g>2&&(a.cachedCharWidth=g),g||10}function rc(a){for(var b=a.display,c={},d={},e=b.gutters.clientLeft,f=b.gutters.firstChild,g=0;f;f=f.nextSibling,++g)c[a.options.gutters[g]]=f.offsetLeft+f.clientLeft+e,d[a.options.gutters[g]]=f.clientWidth;return{fixedPos:sc(b),gutterTotalWidth:b.gutters.offsetWidth,gutterLeft:c,gutterWidth:d,wrapperWidth:b.wrapper.clientWidth}}function sc(a){return a.scroller.getBoundingClientRect().left-a.sizer.getBoundingClientRect().left}function tc(a){var b=pc(a.display),c=a.options.lineWrapping,d=c&&Math.max(5,a.display.scroller.clientWidth/qc(a.display)-3);return function(e){if(la(a.doc,e))return 0;var f=0;if(e.widgets)for(var g=0;g=a.display.viewTo)return null;if(b-=a.display.viewFrom,b<0)return null;for(var c=a.display.view,d=0;d=a.display.viewTo||h.to().line3&&(e(n,p.top,null,p.bottom),n=k,p.bottomi.bottom||j.bottom==i.bottom&&j.right>i.right)&&(i=j),n0?b.blinker=setInterval((function(){return b.cursorDiv.style.visibility=(c=!c)?"":"hidden"}),a.options.cursorBlinkRate):a.options.cursorBlinkRate<0&&(b.cursorDiv.style.visibility="hidden")}}function Cc(a){a.state.focused||(a.display.input.focus(),Ec(a))}function Dc(a){a.state.delayingBlurEvent=!0,setTimeout((function(){a.state.delayingBlurEvent&&(a.state.delayingBlurEvent=!1,Fc(a))}),100)}function Ec(a,b){a.state.delayingBlurEvent&&(a.state.delayingBlurEvent=!1),"nocursor"!=a.options.readOnly&&(a.state.focused||(Da(a,"focus",a,b),a.state.focused=!0,f(a.display.wrapper,"CodeMirror-focused"),a.curOp||a.display.selForContextMenu==a.doc.sel||(a.display.input.reset(),hg&&setTimeout((function(){return a.display.input.reset(!0)}),20)),a.display.input.receivedFocus()),Bc(a))}function Fc(a,b){a.state.delayingBlurEvent||(a.state.focused&&(Da(a,"blur",a,b),a.state.focused=!1,xg(a.display.wrapper,"CodeMirror-focused")),clearInterval(a.display.blinker),setTimeout((function(){a.state.focused||(a.display.shift=!1)}),150))}function Gc(a){var b=a.display,c=b.view;if(b.alignWidgets||b.gutters.firstChild&&a.options.fixedGutter){for(var d=sc(b)-b.scroller.scrollLeft+a.doc.scrollLeft,e=b.gutters.offsetWidth,f=d+"px",g=0;g.001||i<-.001)&&(B(e.line,f),Jc(e.line),e.rest))for(var j=0;j=g&&(f=D(b,na(y(b,i))-a.wrapper.clientHeight),g=i)}return{from:f,to:Math.max(g,f+1)}}function Lc(a,b){Math.abs(a.doc.scrollTop-b)<2||(a.doc.scrollTop=b,cg||zd(a,{top:b}),a.display.scroller.scrollTop!=b&&(a.display.scroller.scrollTop=b),a.display.scrollbars.setScrollTop(b),cg&&zd(a),td(a,100))}function Mc(a,b,c){(c?b==a.doc.scrollLeft:Math.abs(a.doc.scrollLeft-b)<2)||(b=Math.min(b,a.display.scroller.scrollWidth-a.display.scroller.clientWidth),a.doc.scrollLeft=b,Gc(a),a.display.scroller.scrollLeft!=b&&(a.display.scroller.scrollLeft=b),a.display.scrollbars.setScrollLeft(b))}function Nc(a){var b=a.wheelDeltaX,c=a.wheelDeltaY;return null==b&&a.detail&&a.axis==a.HORIZONTAL_AXIS&&(b=a.detail),null==c&&a.detail&&a.axis==a.VERTICAL_AXIS?c=a.detail:null==c&&(c=a.wheelDelta),{x:b,y:c}}function Oc(a){var b=Nc(a);return b.x*=eh,b.y*=eh,b}function Pc(a,b){var c=Nc(b),d=c.x,e=c.y,f=a.display,g=f.scroller,h=g.scrollWidth>g.clientWidth,i=g.scrollHeight>g.clientHeight;if(d&&h||e&&i){if(e&&qg&&hg)a:for(var j=b.target,k=f.view;j!=g;j=j.parentNode)for(var l=0;l(window.innerHeight||document.documentElement.clientHeight)&&(f=!1),null!=f&&!ng){var g=d("div","​",null,"position: absolute;\n top: "+(b.top-c.viewOffset-Nb(a.display))+"px;\n height: "+(b.bottom-b.top+Qb(a)+c.barHeight)+"px;\n left: "+b.left+"px; width: 2px;");a.display.lineSpace.appendChild(g),g.scrollIntoView(f),a.display.lineSpace.removeChild(g)}}}function Xc(a,b,c,d){null==d&&(d=0);for(var e,f=0;f<5;f++){var g=!1;e=kc(a,b);var h=c&&c!=b?kc(a,c):e,i=Zc(a,Math.min(e.left,h.left),Math.min(e.top,h.top)-d,Math.max(e.left,h.left),Math.max(e.bottom,h.bottom)+d),j=a.doc.scrollTop,k=a.doc.scrollLeft;if(null!=i.scrollTop&&(Lc(a,i.scrollTop),Math.abs(a.doc.scrollTop-j)>1&&(g=!0)),null!=i.scrollLeft&&(Mc(a,i.scrollLeft),Math.abs(a.doc.scrollLeft-k)>1&&(g=!0)),!g)break}return e}function Yc(a,b,c,d,e){var f=Zc(a,b,c,d,e);null!=f.scrollTop&&Lc(a,f.scrollTop),null!=f.scrollLeft&&Mc(a,f.scrollLeft)}function Zc(a,b,c,d,e){var f=a.display,g=pc(a.display);c<0&&(c=0);var h=a.curOp&&null!=a.curOp.scrollTop?a.curOp.scrollTop:f.scroller.scrollTop,i=Sb(a),j={};e-c>i&&(e=c+i);var k=a.doc.height+Ob(f),l=ck-g;if(ch+i){var n=Math.min(c,(m?k:e)-i);n!=h&&(j.scrollTop=n)}var o=a.curOp&&null!=a.curOp.scrollLeft?a.curOp.scrollLeft:f.scroller.scrollLeft,p=Rb(a)-(a.options.fixedGutter?f.gutters.offsetWidth:0),q=d-b>p;return q&&(d=b+p),b<10?j.scrollLeft=0:bp+o-3&&(j.scrollLeft=d+(q?0:10)-p),j}function $c(a,b,c){null==b&&null==c||ad(a),null!=b&&(a.curOp.scrollLeft=(null==a.curOp.scrollLeft?a.doc.scrollLeft:a.curOp.scrollLeft)+b),null!=c&&(a.curOp.scrollTop=(null==a.curOp.scrollTop?a.doc.scrollTop:a.curOp.scrollTop)+c)}function _c(a){ad(a);var b=a.getCursor(),c=b,d=b;a.options.lineWrapping||(c=b.ch?G(b.line,b.ch-1):b,d=G(b.line,b.ch+1)),a.curOp.scrollToPos={from:c,to:d,margin:a.options.cursorScrollMargin,isCursor:!0}}function ad(a){var b=a.curOp.scrollToPos;if(b){a.curOp.scrollToPos=null;var c=lc(a,b.from),d=lc(a,b.to),e=Zc(a,Math.min(c.left,d.left),Math.min(c.top,d.top)-b.margin,Math.max(c.right,d.right),Math.max(c.bottom,d.bottom)+b.margin);a.scrollTo(e.scrollLeft,e.scrollTop)}}function bd(a){a.curOp={cm:a,viewChanged:!1,startHeight:a.doc.height,forceUpdate:!1,updateInput:null,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,focus:!1,id:++gh},ub(a.curOp)}function cd(a){var b=a.curOp;wb(b,(function(a){for(var b=0;b=c.viewTo)||c.maxLineChanged&&b.options.lineWrapping,a.update=a.mustUpdate&&new vd(b,a.mustUpdate&&{top:a.scrollTop,ensure:a.scrollToPos},a.forceUpdate)}function fd(a){a.updatedDisplay=a.mustUpdate&&xd(a.cm,a.update)}function gd(a){var b=a.cm,c=b.display;a.updatedDisplay&&Ic(b),a.barMeasure=Qc(b),c.maxLineChanged&&!b.options.lineWrapping&&(a.adjustWidthTo=Wb(b,c.maxLine,c.maxLine.text.length).left+3,b.display.sizerWidth=a.adjustWidthTo,a.barMeasure.scrollWidth=Math.max(c.scroller.clientWidth,c.sizer.offsetLeft+a.adjustWidthTo+Qb(b)+b.display.barWidth),a.maxScrollLeft=Math.max(0,c.sizer.offsetLeft+a.adjustWidthTo-Rb(b))),(a.updatedDisplay||a.selectionChanged)&&(a.preparedSelection=c.input.prepareSelection(a.focus))}function hd(a){var b=a.cm;null!=a.adjustWidthTo&&(b.display.sizer.style.minWidth=a.adjustWidthTo+"px",a.maxScrollLeftb)&&(e.updateLineNumbers=b),a.curOp.viewChanged=!0,b>=e.viewTo)Lg&&ja(a.doc,b)e.viewFrom?pd(a):(e.viewFrom+=d,e.viewTo+=d);else if(b<=e.viewFrom&&c>=e.viewTo)pd(a);else if(b<=e.viewFrom){var f=qd(a,c,c+d,1);f?(e.view=e.view.slice(f.index),e.viewFrom=f.lineN,e.viewTo+=d):pd(a)}else if(c>=e.viewTo){var g=qd(a,b,b,-1);g?(e.view=e.view.slice(0,g.index),e.viewTo=g.lineN):pd(a)}else{var h=qd(a,b,b,-1),i=qd(a,c,c+d,1);h&&i?(e.view=e.view.slice(0,h.index).concat(tb(a,h.lineN,i.lineN)).concat(e.view.slice(i.index)),e.viewTo+=d):pd(a)}var j=e.externalMeasured;j&&(c=e.lineN&&b=d.viewTo)){var f=d.view[wc(a,b)];if(null!=f.node){var g=f.changes||(f.changes=[]);l(g,c)==-1&&g.push(c)}}}function pd(a){a.display.viewFrom=a.display.viewTo=a.doc.first,a.display.view=[],a.display.viewOffset=0}function qd(a,b,c,d){var e,f=wc(a,b),g=a.display.view;if(!Lg||c==a.doc.first+a.doc.size)return{index:f,lineN:c};for(var h=a.display.viewFrom,i=0;i0){if(f==g.length-1)return null;e=h+g[f].size-b,f++}else e=h-b;b+=e,c+=e}for(;ja(a.doc,c)!=c;){if(f==(d<0?0:g.length-1))return null;c+=d*g[f-(d<0?1:0)].size,f+=d}return{index:f,lineN:c}}function rd(a,b,c){var d=a.display,e=d.view;0==e.length||b>=d.viewTo||c<=d.viewFrom?(d.view=tb(a,b,c),d.viewFrom=b):(d.viewFrom>b?d.view=tb(a,b,d.viewFrom).concat(d.view):d.viewFromc&&(d.view=d.view.slice(0,wc(a,c)))),d.viewTo=c}function sd(a){for(var b=a.display.view,c=0,d=0;d=a.display.viewTo)){var c=+new Date+a.options.workTime,d=Wa(b.mode,_a(a,b.frontier)),e=[];b.iter(b.frontier,Math.min(b.first+b.size,a.display.viewTo+500),(function(f){if(b.frontier>=a.display.viewFrom){var g=f.styles,h=f.text.length>a.options.maxHighlightLength,i=Za(a,f,h?Wa(b.mode,d):d,!0);f.styles=i.styles;var j=f.styleClasses,k=i.classes;k?f.styleClasses=k:j&&(f.styleClasses=null);for(var l=!g||g.length!=f.styles.length||j!=k&&(!j||!k||j.bgClass!=k.bgClass||j.textClass!=k.textClass),m=0;!l&&mc)return td(a,a.options.workDelay),!0})),e.length&&jd(a,(function(){for(var b=0;b=d.viewFrom&&c.visible.to<=d.viewTo&&(null==d.updateLineNumbers||d.updateLineNumbers>=d.viewTo)&&d.renderedView==d.view&&0==sd(a))return!1;Hc(a)&&(pd(a),c.dims=rc(a));var f=e.first+e.size,g=Math.max(c.visible.from-a.options.viewportMargin,e.first),h=Math.min(f,c.visible.to+a.options.viewportMargin);d.viewFromh&&d.viewTo-h<20&&(h=Math.min(f,d.viewTo)),Lg&&(g=ja(a.doc,g),h=ka(a.doc,h));var i=g!=d.viewFrom||h!=d.viewTo||d.lastWrapHeight!=c.wrapperHeight||d.lastWrapWidth!=c.wrapperWidth;rd(a,g,h),d.viewOffset=na(y(a.doc,d.viewFrom)),a.display.mover.style.top=d.viewOffset+"px";var j=sd(a);if(!i&&0==j&&!c.force&&d.renderedView==d.view&&(null==d.updateLineNumbers||d.updateLineNumbers>=d.viewTo))return!1;var k=yg();return j>4&&(d.lineDiv.style.display="none"),Ad(a,d.updateLineNumbers,c.dims),j>4&&(d.lineDiv.style.display=""),d.renderedView=d.view,k&&yg()!=k&&k.offsetHeight&&k.focus(),b(d.cursorDiv),b(d.selectionDiv),d.gutters.style.height=d.sizer.style.minHeight=0,i&&(d.lastWrapHeight=c.wrapperHeight,d.lastWrapWidth=c.wrapperWidth,td(a,400)),d.updateLineNumbers=null,!0}function yd(a,b){for(var c=b.viewport,d=!0;(d&&a.options.lineWrapping&&b.oldDisplayWidth!=Rb(a)||(c&&null!=c.top&&(c={top:Math.min(a.doc.height+Ob(a.display)-Sb(a),c.top)}),b.visible=Kc(a.display,a.doc,c),!(b.visible.from>=a.display.viewFrom&&b.visible.to<=a.display.viewTo)))&&xd(a,b);d=!1){Ic(a);var e=Qc(a);xc(a),Tc(a,e),Cd(a,e)}b.signal(a,"update",a),a.display.viewFrom==a.display.reportedViewFrom&&a.display.viewTo==a.display.reportedViewTo||(b.signal(a,"viewportChange",a,a.display.viewFrom,a.display.viewTo),a.display.reportedViewFrom=a.display.viewFrom,a.display.reportedViewTo=a.display.viewTo)}function zd(a,b){var c=new vd(a,b);if(xd(a,c)){Ic(a),yd(a,c);var d=Qc(a);xc(a),Tc(a,d),Cd(a,d),c.finish()}}function Ad(a,c,d){function e(b){var c=b.nextSibling;return hg&&qg&&a.display.currentWheelTarget==b?b.style.display="none":b.parentNode.removeChild(b),c}for(var f=a.display,g=a.options.lineNumbers,h=f.lineDiv,i=h.firstChild,j=f.view,k=f.viewFrom,m=0;m-1&&(o=!1),zb(a,n,k,d)),o&&(b(n.lineNumber),n.lineNumber.appendChild(document.createTextNode(F(a.options,k)))),i=n.node.nextSibling}else{var p=Hb(a,n,k,d);h.insertBefore(p,i)}k+=n.size}for(;i;)i=e(i)}function Bd(a){var b=a.display.gutters.offsetWidth;a.display.sizer.style.marginLeft=b+"px"}function Cd(a,b){a.display.sizer.style.minHeight=b.docHeight+"px",a.display.heightForcer.style.top=b.docHeight+"px",a.display.gutters.style.height=b.docHeight+a.display.barHeight+Qb(a)+"px"}function Dd(a){var c=a.display.gutters,e=a.options.gutters;b(c);for(var f=0;f-1&&!a.lineNumbers&&(a.gutters=a.gutters.slice(0),a.gutters.splice(b,1))}function Fd(a,b){this.ranges=a,this.primIndex=b}function Gd(a,b){this.anchor=a,this.head=b}function Hd(a,b){var c=a[b];a.sort((function(a,b){return H(a.from(),b.from())})),b=l(a,c);for(var d=1;d=0){var g=K(f.from(),e.from()),h=J(f.to(),e.to()),i=f.empty()?e.from()==e.head:f.from()==f.head;d<=b&&--b,a.splice(--d,2,new Gd(i?h:g,i?g:h))}}return new Fd(a,b)}function Id(a,b){return new Fd([new Gd(a,b||a)],0)}function Jd(a){return a.text?G(a.from.line+a.text.length-1,o(a.text).length+(1==a.text.length?a.from.ch:0)):a.to}function Kd(a,b){if(H(a,b.from)<0)return a;if(H(a,b.to)<=0)return Jd(b);var c=a.line+b.text.length-(b.to.line-b.from.line)-1,d=a.ch;return a.line==b.to.line&&(d+=Jd(b).ch-b.to.ch),G(c,d)}function Ld(a,b){for(var c=[],d=0;d1&&a.remove(h.line+1,p-1),a.insert(h.line+1,s)}xb(a,"change",a,b)}function Sd(a,b,c){function d(a,e,f){if(a.linked)for(var g=0;g1&&!a.done[a.done.length-2].ranges?(a.done.pop(),o(a.done)):void 0}function Yd(a,b,c,d){var e=a.history;e.undone.length=0;var f,g,h=+new Date;if((e.lastOp==d||e.lastOrigin==b.origin&&b.origin&&("+"==b.origin.charAt(0)&&a.cm&&e.lastModTime>h-a.cm.options.historyEventDelay||"*"==b.origin.charAt(0)))&&(f=Xd(e,e.lastOp==d)))g=o(f.changes),0==H(b.from,b.to)&&0==H(b.from,g.to)?g.to=Jd(b):f.changes.push(Vd(a,b));else{var i=o(e.done);for(i&&i.ranges||_d(a.sel,e.done),f={changes:[Vd(a,b)],generation:e.generation},e.done.push(f);e.done.length>e.undoDepth;)e.done.shift(),e.done[0].ranges||e.done.shift()}e.done.push(c),e.generation=++e.maxGeneration,e.lastModTime=e.lastSelTime=h,e.lastOp=e.lastSelOp=d,e.lastOrigin=e.lastSelOrigin=b.origin,g||Da(a,"historyAdded")}function Zd(a,b,c,d){var e=b.charAt(0);return"*"==e||"+"==e&&c.ranges.length==d.ranges.length&&c.somethingSelected()==d.somethingSelected()&&new Date-a.history.lastSelTime<=(a.cm?a.cm.options.historyEventDelay:500)}function $d(a,b,c,d){var e=a.history,f=d&&d.origin;c==e.lastSelOp||f&&e.lastSelOrigin==f&&(e.lastModTime==e.lastSelTime&&e.lastOrigin==f||Zd(a,f,o(e.done),b))?e.done[e.done.length-1]=b:_d(b,e.done),e.lastSelTime=+new Date,e.lastSelOrigin=f,e.lastSelOp=c,d&&d.clearRedo!==!1&&Wd(e.undone)}function _d(a,b){var c=o(b);c&&c.ranges&&c.equals(a)||b.push(a)}function ae(a,b,c,d){var e=b["spans_"+a.id],f=0;a.iter(Math.max(a.first,c),Math.min(a.first+a.size,d),(function(c){c.markedSpans&&((e||(e=b["spans_"+a.id]={}))[f]=c.markedSpans),++f}))}function be(a){if(!a)return null;for(var b,c=0;c-1&&(o(h)[m]=j[m],delete j[m])}}}return d}function fe(a,b,c,d){if(a.cm&&a.cm.display.shift||a.extend){var e=b.anchor;if(d){var f=H(c,e)<0;f!=H(d,e)<0?(e=c,c=d):f!=H(c,d)<0&&(c=d)}return new Gd(e,c)}return new Gd(d||c,c)}function ge(a,b,c,d){me(a,new Fd([fe(a,a.sel.primary(),b,c)],0),d)}function he(a,b,c){for(var d=[],e=0;e=b.ch:h.to>b.ch))){if(e&&(Da(i,"beforeCursorEnter"),i.explicitlyCleared)){if(f.markedSpans){--g;continue}break}if(!i.atomic)continue;if(c){var j=i.find(d<0?1:-1),k=void 0;if((d<0?i.inclusiveRight:i.inclusiveLeft)&&(j=te(a,j,-d,j&&j.line==b.line?f:null)),j&&j.line==b.line&&(k=H(j,c))&&(d<0?k<0:k>0))return re(a,j,b,d,e)}var l=i.find(d<0?-1:1);return(d<0?i.inclusiveLeft:i.inclusiveRight)&&(l=te(a,l,d,l.line==b.line?f:null)),l?re(a,l,b,d,e):null}}return b}function se(a,b,c,d,e){var f=d||1,g=re(a,b,c,f,e)||!e&&re(a,b,c,f,!0)||re(a,b,c,-f,e)||!e&&re(a,b,c,-f,!0);return g?g:(a.cantEdit=!0,G(a.first,0))}function te(a,b,c,d){return c<0&&0==b.ch?b.line>a.first?M(a,G(b.line-1)):null:c>0&&b.ch==(d||y(a,b.line)).text.length?b.line=0;--e)xe(a,{from:d[e].from,to:d[e].to,text:e?[""]:b.text});else xe(a,b)}}function xe(a,b){if(1!=b.text.length||""!=b.text[0]||0!=H(b.from,b.to)){var c=Ld(a,b);Yd(a,b,c,a.cm?a.cm.curOp.id:NaN),Ae(a,b,c,X(a,b));var d=[];Sd(a,(function(a,c){c||l(d,a.history)!=-1||(Fe(a.history,b),d.push(a.history)),Ae(a,b,null,X(a,b))}))}}function ye(a,b,c){if(!a.cm||!a.cm.state.suppressEdits||c){for(var d,e=a.history,f=a.sel,g="undo"==b?e.done:e.undone,h="undo"==b?e.undone:e.done,i=0;i=0;--n){var p=m(n);if(p)return p.v}}}}function ze(a,b){if(0!=b&&(a.first+=b,a.sel=new Fd(p(a.sel.ranges,(function(a){return new Gd(G(a.anchor.line+b,a.anchor.ch),G(a.head.line+b,a.head.ch))})),a.sel.primIndex),a.cm)){nd(a.cm,a.first,a.first-b,b);for(var c=a.cm.display,d=c.viewFrom;da.lastLine())){if(b.from.linef&&(b={from:b.from,to:G(f,y(a,f).text.length),text:[b.text[0]],origin:b.origin}),b.removed=z(a,b.from,b.to),c||(c=Ld(a,b)),a.cm?Be(a.cm,b,d):Rd(a,b,d),ne(a,c,Eg)}}function Be(a,b,c){var d=a.doc,e=a.display,f=b.from,g=b.to,h=!1,i=f.line;a.options.lineWrapping||(i=C(ha(y(d,f.line))),d.iter(i,g.line+1,(function(a){if(a==e.maxLine)return h=!0,!0}))),d.sel.contains(b.from,b.to)>-1&&Fa(a),Rd(d,b,c,tc(a)),a.options.lineWrapping||(d.iter(i,f.line+b.text.length,(function(a){var b=oa(a);b>e.maxLineLength&&(e.maxLine=a,e.maxLineLength=b,e.maxLineChanged=!0,h=!1)})),h&&(a.curOp.updateMaxLine=!0)),d.frontier=Math.min(d.frontier,f.line),td(a,400);var j=b.text.length-(g.line-f.line)-1;b.full?nd(a):f.line!=g.line||1!=b.text.length||Qd(a.doc,b)?nd(a,f.line,g.line+1,j):od(a,f.line,"text");var k=Ga(a,"changes"),l=Ga(a,"change");if(l||k){var m={from:f,to:g,text:b.text,removed:b.removed,origin:b.origin};l&&xb(a,"change",a,m),k&&(a.curOp.changeObjs||(a.curOp.changeObjs=[])).push(m)}a.display.selForContextMenu=null}function Ce(a,b,c,d,e){if(d||(d=c),H(d,c)<0){var f=d;d=c,c=f}"string"==typeof b&&(b=a.splitLines(b)),we(a,{from:c,to:d,text:b,origin:e})}function De(a,b,c,d){c0||0==h&&g.clearWhenEmpty!==!1)return g;if(g.replacedWith&&(g.collapsed=!0,g.widgetNode=d("span",[g.replacedWith],"CodeMirror-widget"),e.handleMouseEvents||g.widgetNode.setAttribute("cm-ignore-events","true"),e.insertLeft&&(g.widgetNode.insertLeft=!0)),g.collapsed){if(ga(a,b.line,b,c,g)||b.line!=c.line&&ga(a,c.line,b,c,g))throw new Error("Inserting collapsed marker partially overlapping an existing one");Q()}g.addToHistory&&Yd(a,{from:b,to:c,origin:"markText"},a.sel,NaN);var j,k=b.line,l=a.cm;if(a.iter(k,c.line+1,(function(a){l&&g.collapsed&&!l.options.lineWrapping&&ha(a)==l.display.maxLine&&(j=!0),g.collapsed&&k!=b.line&&B(a,0),U(a,new R(g,k==b.line?b.ch:null,k==c.line?c.ch:null)),++k})),g.collapsed&&a.iter(b.line,c.line+1,(function(b){la(a,b)&&B(b,0)})),g.clearOnEnter&&Og(g,"beforeCursorEnter",(function(){return g.clear()})),g.readOnly&&(P(),(a.history.done.length||a.history.undone.length)&&a.clearHistory()),g.collapsed&&(g.id=++hh,g.atomic=!0),l){if(j&&(l.curOp.updateMaxLine=!0),g.collapsed)nd(l,b.line,c.line+1);else if(g.className||g.title||g.startStyle||g.endStyle||g.css)for(var m=b.line;m<=c.line;m++)od(l,m,"text");g.atomic&&pe(l.doc),xb(l,"markerAdded",l,g)}return g}function Oe(a,b){var c=this;this.markers=a,this.primary=b;for(var d=0;d-1)return b.state.draggingText(a),void setTimeout((function(){return b.display.input.focus()}),20);try{var j=a.dataTransfer.getData("Text");if(j){var k;if(b.state.draggingText&&!b.state.draggingText.copy&&(k=b.listSelections()),ne(b.doc,Id(c,c)),k)for(var m=0;m=0;b--)Ce(a.doc,"",d[b].from,d[b].to,"+delete");_c(a)}))}function gf(a,b){var c=y(a.doc,b),d=ha(c);d!=c&&(b=C(d));var e=Aa(d),f=e?e[0].level%2?ua(d):ta(d):0;return G(b,f)}function hf(a,b){for(var c,d=y(a.doc,b);c=fa(d);)d=c.find(1,!0).line,b=null;var e=Aa(d),f=e?e[0].level%2?ta(d):ua(d):d.text.length;return G(null==b?C(d):b,f)}function jf(a,b){var c=gf(a,b.line),d=y(a.doc,c.line),e=Aa(d);if(!e||0==e[0].level){var f=Math.max(0,d.text.search(/\S/)),g=b.line==c.line&&b.ch<=f&&b.ch;return G(c.line,g?0:f)}return c}function kf(a,b,c){if("string"==typeof b&&(b=th[b],!b))return!1;a.display.input.ensurePolled();var d=a.display.shift,e=!1;try{a.isReadOnly()&&(a.state.suppressEdits=!0),c&&(a.display.shift=!1),e=b(a)!=Dg}finally{a.display.shift=d,a.state.suppressEdits=!1}return e}function lf(a,b,c){for(var d=0;de-400&&0==H(sh.pos,c)?d="triple":rh&&rh.time>e-400&&0==H(rh.pos,c)?(d="double",sh={time:e,pos:c}):(d="single",rh={time:e,pos:c});var f,g=a.doc.sel,i=qg?b.metaKey:b.ctrlKey;a.options.dragDrop&&Qg&&!a.isReadOnly()&&"single"==d&&(f=g.contains(c))>-1&&(H((f=g.ranges[f]).from(),c)<0||c.xRel>0)&&(H(f.to(),c)>0||c.xRel<0)?vf(a,b,c,i):wf(a,b,c,d,i)}function vf(a,b,c,d){var e=a.display,f=+new Date,g=kd(a,(function(h){hg&&(e.scroller.draggable=!1),a.state.draggingText=!1,Ca(document,"mouseup",g),Ca(e.scroller,"drop",g),Math.abs(b.clientX-h.clientX)+Math.abs(b.clientY-h.clientY)<10&&(Ia(h),!d&&+new Date-200u&&e.push(new Gd(G(q,u),G(q,m(t,p,f))))}e.length||e.push(new Gd(c,c)),me(k,Hd(o.ranges.slice(0,n).concat(e),n),{origin:"*mouse",scroll:!1}),a.scrollIntoView(b)}else{var v=l,w=v.anchor,x=b;if("single"!=d){var z;z="double"==d?a.findWordAt(b):new Gd(G(b.line,0),M(k,G(b.line+1,0))),H(z.anchor,w)>0?(x=z.head,w=K(v.from(),z.anchor)):(x=z.anchor,w=J(v.to(),z.head))}var A=o.ranges.slice(0);A[n]=new Gd(M(k,w),x),me(k,Hd(A,n),Fg)}}function g(b){var c=++u,e=vc(a,b,!0,"rect"==d);if(e)if(0!=H(e,s)){a.curOp.focus=yg(),f(e);var h=Kc(i,k);(e.line>=h.to||e.linet.bottom?20:0;j&&setTimeout(kd(a,(function(){u==c&&(i.scroller.scrollTop+=j,g(b))})),50)}}function h(b){a.state.selectingText=!1,u=1/0,Ia(b),i.input.focus(),Ca(document,"mousemove",v),Ca(document,"mouseup",w),k.history.lastSelOrigin=null}var i=a.display,k=a.doc;Ia(b);var l,n,o=k.sel,p=o.ranges;if(e&&!b.shiftKey?(n=k.sel.contains(c),l=n>-1?p[n]:new Gd(c,c)):(l=k.sel.primary(),n=k.sel.primIndex),rg?b.shiftKey&&b.metaKey:b.altKey)d="rect",e||(l=new Gd(c,c)),c=vc(a,b,!0,!0),n=-1;else if("double"==d){var q=a.findWordAt(c);l=a.display.shift||k.extend?fe(k,l,q.anchor,q.head):q}else if("triple"==d){var r=new Gd(G(c.line,0),M(k,G(c.line+1,0)));l=a.display.shift||k.extend?fe(k,l,r.anchor,r.head):r}else l=fe(k,l,c);e?n==-1?(n=p.length,me(k,Hd(p.concat([l]),n),{scroll:!1,origin:"*mouse"})):p.length>1&&p[n].empty()&&"single"==d&&!b.shiftKey?(me(k,Hd(p.slice(0,n).concat(p.slice(n+1)),0),{scroll:!1,origin:"*mouse"}),o=k.sel):ie(k,n,l,Fg):(n=0,me(k,new Fd([l],0),Fg),o=k.sel);var s=c,t=i.wrapper.getBoundingClientRect(),u=0,v=kd(a,(function(a){Na(a)?g(a):h(a)})),w=kd(a,h);a.state.selectingText=w,Og(document,"mousemove",v),Og(document,"mouseup",w)}function xf(a,b,c,d){var e,f;try{e=b.clientX,f=b.clientY}catch(a){return!1}if(e>=Math.floor(a.display.gutters.getBoundingClientRect().right))return!1;d&&Ia(b);var g=a.display,h=g.lineDiv.getBoundingClientRect();if(f>h.bottom||!Ga(a,c))return Ka(b);f-=h.top-g.viewOffset;for(var i=0;i=e){var k=D(a.doc,f),l=a.options.gutters[i];return Da(a,c,a,k,l,b),Ka(b)}}}function yf(a,b){return xf(a,b,"gutterClick",!0)}function zf(a,b){Mb(a.display,b)||Af(a,b)||Ea(a,b,"contextmenu")||a.display.input.onContextMenu(b)}function Af(a,b){return!!Ga(a,"gutterContextMenu")&&xf(a,b,"gutterContextMenu",!1)}function Bf(a){a.display.wrapper.className=a.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+a.options.theme.replace(/(^|\s)\s*/g," cm-s-"),ec(a)}function Cf(a){function b(b,d,e,f){a.defaults[b]=d,e&&(c[b]=f?function(a,b,c){c!=wh&&e(a,b,c)}:e)}var c=a.optionHandlers;a.defineOption=b,a.Init=wh,b("value","",(function(a,b){return a.setValue(b)}),!0),b("mode",null,(function(a,b){a.doc.modeOption=b,Od(a)}),!0),b("indentUnit",2,Od,!0),b("indentWithTabs",!1),b("smartIndent",!0),b("tabSize",4,(function(a){Pd(a),ec(a),nd(a)}),!0),b("lineSeparator",null,(function(a,b){if(a.doc.lineSep=b,b){var c=[],d=a.doc.first;a.doc.iter((function(a){for(var e=0;;){var f=a.text.indexOf(b,e);if(f==-1)break;e=f+b.length,c.push(G(d,f))}d++}));for(var e=c.length-1;e>=0;e--)Ce(a.doc,b,c[e],G(c[e].line,c[e].ch+b.length))}})),b("specialChars",/[\u0000-\u001f\u007f\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g,(function(a,b,c){a.state.specialChars=new RegExp(b.source+(b.test("\t")?"":"|\t"),"g"),c!=wh&&a.refresh()})),b("specialCharPlaceholder",mb,(function(a){return a.refresh()}),!0),b("electricChars",!0),b("inputStyle",pg?"contenteditable":"textarea",(function(){throw new Error("inputStyle can not (yet) be changed in a running editor")}),!0),b("spellcheck",!1,(function(a,b){return a.getInputField().spellcheck=b}),!0),b("rtlMoveVisually",!sg),b("wholeLineUpdateBefore",!0),b("theme","default",(function(a){Bf(a),Df(a)}),!0),b("keyMap","default",(function(a,b,c){var d=ef(b),e=c!=wh&&ef(c);e&&e.detach&&e.detach(a,d),d.attach&&d.attach(a,e||null)})),b("extraKeys",null),b("lineWrapping",!1,Ff,!0),b("gutters",[],(function(a){Ed(a.options),Df(a)}),!0),b("fixedGutter",!0,(function(a,b){a.display.gutters.style.left=b?sc(a.display)+"px":"0",a.refresh()}),!0),b("coverGutterNextToScrollbar",!1,(function(a){return Tc(a)}),!0),b("scrollbarStyle","native",(function(a){Vc(a),Tc(a),a.display.scrollbars.setScrollTop(a.doc.scrollTop),a.display.scrollbars.setScrollLeft(a.doc.scrollLeft)}),!0),b("lineNumbers",!1,(function(a){Ed(a.options),Df(a)}),!0),b("firstLineNumber",1,Df,!0),b("lineNumberFormatter",(function(a){return a}),Df,!0),b("showCursorWhenSelecting",!1,xc,!0),b("resetSelectionOnContextMenu",!0),b("lineWiseCopyCut",!0),b("readOnly",!1,(function(a,b){"nocursor"==b?(Fc(a),a.display.input.blur(),a.display.disabled=!0):a.display.disabled=!1,a.display.input.readOnlyChanged(b)})),b("disableInput",!1,(function(a,b){b||a.display.input.reset()}),!0),b("dragDrop",!0,Ef),b("allowDropFileTypes",null),b("cursorBlinkRate",530),b("cursorScrollMargin",0),b("cursorHeight",1,xc,!0),b("singleCursorHeightPerLine",!0,xc,!0),b("workTime",100),b("workDelay",100),b("flattenSpans",!0,Pd,!0),b("addModeClass",!1,Pd,!0),b("pollInterval",100),b("undoDepth",200,(function(a,b){return a.doc.history.undoDepth=b})),b("historyEventDelay",1250),b("viewportMargin",10,(function(a){return a.refresh()}),!0),b("maxHighlightLength",1e4,Pd,!0),b("moveInputWithCursor",!0,(function(a,b){b||a.display.input.resetPosition()})),b("tabindex",null,(function(a,b){return a.display.input.getField().tabIndex=b||""})),b("autofocus",null)}function Df(a){Dd(a),nd(a),setTimeout((function(){return Gc(a)}),20)}function Ef(a,b,c){var d=c&&c!=wh;if(!b!=!d){var e=a.display.dragFunctions,f=b?Og:Ca;f(a.display.scroller,"dragstart",e.start),f(a.display.scroller,"dragenter",e.enter),f(a.display.scroller,"dragover",e.over),f(a.display.scroller,"dragleave",e.leave),f(a.display.scroller,"drop",e.drop)}}function Ff(a){a.options.lineWrapping?(f(a.display.wrapper,"CodeMirror-wrap"),a.display.sizer.style.minWidth="",a.display.sizerWidth=null):(xg(a.display.wrapper,"CodeMirror-wrap"),pa(a)),uc(a),nd(a),ec(a),setTimeout((function(){return Tc(a)}),100)}function Gf(a,b){var c=this;if(!(this instanceof Gf))return new Gf(a,b);this.options=b=b?i(b):{},i(xh,b,!1),Ed(b);var d=b.value;"string"==typeof d&&(d=new jh(d,b.mode,null,b.lineSeparator)),this.doc=d;var e=new Gf.inputStyles[b.inputStyle](this),f=this.display=new x(a,d,e);f.wrapper.CodeMirror=this,Dd(this),Bf(this),b.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap"),b.autofocus&&!pg&&f.input.focus(),Vc(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 k,keySeq:null,specialChars:null},fg&&gg<11&&setTimeout((function(){return c.display.input.reset(!0)}),20),Hf(this),Ye(),bd(this),this.curOp.forceUpdate=!0,Td(this,d),b.autofocus&&!pg||this.hasFocus()?setTimeout(h(Ec,this),20):Fc(this);for(var g in yh)yh.hasOwnProperty(g)&&yh[g](c,b[g],wh);Hc(this),b.finishInit&&b.finishInit(this);for(var j=0;j400}var e=a.display;Og(e.scroller,"mousedown",kd(a,tf)),fg&&gg<11?Og(e.scroller,"dblclick",kd(a,(function(b){if(!Ea(a,b)){var c=vc(a,b);if(c&&!yf(a,b)&&!Mb(a.display,b)){Ia(b);var d=a.findWordAt(c);ge(a.doc,d.anchor,d.head)}}}))):Og(e.scroller,"dblclick",(function(b){return Ea(a,b)||Ia(b)})),wg||Og(e.scroller,"contextmenu",(function(b){return zf(a,b)}));var f,g={end:0};Og(e.scroller,"touchstart",(function(b){if(!Ea(a,b)&&!c(b)){clearTimeout(f);var d=+new Date;e.activeTouch={start:d,moved:!1,prev:d-g.end<=300?g:null},1==b.touches.length&&(e.activeTouch.left=b.touches[0].pageX,e.activeTouch.top=b.touches[0].pageY)}})),Og(e.scroller,"touchmove",(function(){e.activeTouch&&(e.activeTouch.moved=!0)})),Og(e.scroller,"touchend",(function(c){var f=e.activeTouch;if(f&&!Mb(e,c)&&null!=f.left&&!f.moved&&new Date-f.start<300){var g,h=a.coordsChar(e.activeTouch,"page");g=!f.prev||d(f,f.prev)?new Gd(h,h):!f.prev.prev||d(f,f.prev.prev)?a.findWordAt(h):new Gd(G(h.line,0),M(a.doc,G(h.line+1,0))),a.setSelection(g.anchor,g.head),a.focus(),Ia(c)}b()})),Og(e.scroller,"touchcancel",b),Og(e.scroller,"scroll",(function(){e.scroller.clientHeight&&(Lc(a,e.scroller.scrollTop),Mc(a,e.scroller.scrollLeft,!0),Da(a,"scroll",a))})),Og(e.scroller,"mousewheel",(function(b){return Pc(a,b)})),Og(e.scroller,"DOMMouseScroll",(function(b){return Pc(a,b)})),Og(e.wrapper,"scroll",(function(){return e.wrapper.scrollTop=e.wrapper.scrollLeft=0})),e.dragFunctions={enter:function(b){Ea(a,b)||La(b)},over:function(b){Ea(a,b)||(Ve(a,b),La(b))},start:function(b){return Ue(a,b)},drop:kd(a,Te),leave:function(b){Ea(a,b)||We(a)}};var h=e.input.getField();Og(h,"keyup",(function(b){return rf.call(a,b)})),Og(h,"keydown",kd(a,pf)),Og(h,"keypress",kd(a,sf)),Og(h,"focus",(function(b){return Ec(a,b)})),Og(h,"blur",(function(b){return Fc(a,b)}))}function If(a,b,c,d){var e,f=a.doc;null==c&&(c="add"),"smart"==c&&(f.mode.indent?e=_a(a,b):c="prev");var g=a.options.tabSize,h=y(f,b),i=j(h.text,null,g);h.stateAfter&&(h.stateAfter=null);var k,l=h.text.match(/^\s*/)[0];if(d||/\S/.test(h.text)){if("smart"==c&&(k=f.mode.indent(e,h.text.slice(l.length),h.text),k==Dg||k>150)){if(!d)return;c="prev"}}else k=0,c="not";"prev"==c?k=b>f.first?j(y(f,b-1).text,null,g):0:"add"==c?k=i+a.options.indentUnit:"subtract"==c?k=i-a.options.indentUnit:"number"==typeof c&&(k=i+c),k=Math.max(0,k);var m="",o=0;if(a.options.indentWithTabs)for(var p=Math.floor(k/g);p;--p)o+=g,m+="\t";if(o1)if(Ah&&Ah.text.join("\n")==b){if(d.ranges.length%Ah.text.length==0){i=[];for(var j=0;j=0;l--){var m=d.ranges[l],n=m.from(),q=m.to();m.empty()&&(c&&c>0?n=G(n.line,n.ch-c):a.state.overwrite&&!g?q=G(q.line,Math.min(y(f,q.line).text.length,q.ch+o(h).length)):Ah&&Ah.lineWise&&Ah.text.join("\n")==b&&(n=q=G(n.line,0))),k=a.curOp.updateInput;var r={from:n,to:q,text:i?i[l%i.length]:h,origin:e||(g?"paste":a.state.cutIncoming?"cut":"+input")};we(a.doc,r),xb(a,"inputRead",a,r)}b&&!g&&Mf(a,b),_c(a),a.curOp.updateInput=k,a.curOp.typing=!0,a.state.pasteIncoming=a.state.cutIncoming=!1}function Lf(a,b){var c=a.clipboardData&&a.clipboardData.getData("Text");if(c)return a.preventDefault(),b.isReadOnly()||b.options.disableInput||jd(b,(function(){return Kf(b,c,0,null,"paste")})),!0}function Mf(a,b){if(a.options.electricChars&&a.options.smartIndent)for(var c=a.doc.sel,d=c.ranges.length-1;d>=0;d--){var e=c.ranges[d];if(!(e.head.ch>100||d&&c.ranges[d-1].head.line==e.head.line)){var f=a.getModeAt(e.head),g=!1;if(f.electricChars){for(var h=0;h-1){g=If(a,e.head.line,"smart");break}}else f.electricInput&&f.electricInput.test(y(a.doc,e.head.line).text.slice(0,e.head.ch))&&(g=If(a,e.head.line,"smart"));g&&xb(a,"electricInput",a,e.head.line)}}}function Nf(a){for(var b=[],c=[],d=0;dd&&(If(b,f.head.line,a,!0),d=f.head.line,e==b.doc.sel.primIndex&&_c(b));else{var g=f.from(),h=f.to(),i=Math.max(d,g.line);d=Math.min(b.lastLine(),h.line-(h.ch?0:1))+1;for(var j=i;j0&&ie(b.doc,e,new Gd(g,k[e].to()),Eg)}}})),getTokenAt:function(a,b){return db(this,a,b)},getLineTokens:function(a,b){return db(this,G(a),b,!0)},getTokenTypeAt:function(a){a=M(this.doc,a);var b,c=$a(this,y(this.doc,a.line)),d=0,e=(c.length-1)/2,f=a.ch;if(0==f)b=c[2];else for(;;){var g=d+e>>1;if((g?c[2*g-1]:0)>=f)e=g;else{if(!(c[2*g+1]e&&(a=e,d=!0),c=y(this.doc,a)}else c=a;return hc(this,c,{top:0,left:0},b||"page").top+(d?this.doc.height-na(c):0)},defaultTextHeight:function(){return pc(this.display)},defaultCharWidth:function(){return qc(this.display)},setGutterMarker:ld((function(a,b,c){return Ge(this.doc,a,"gutter",(function(a){var d=a.gutterMarkers||(a.gutterMarkers={});return d[b]=c,!c&&v(d)&&(a.gutterMarkers=null),!0}))})),clearGutter:ld((function(a){var b=this,c=this.doc,d=c.first;c.iter((function(c){c.gutterMarkers&&c.gutterMarkers[a]&&(c.gutterMarkers[a]=null,od(b,d,"gutter"),v(c.gutterMarkers)&&(c.gutterMarkers=null)),++d}))})),lineInfo:function(a){var b;if("number"==typeof a){if(!E(this.doc,a))return null;if(b=a,a=y(this.doc,a),!a)return null}else if(b=C(a),null==b)return null;return{line:b,handle:a,text:a.text,gutterMarkers:a.gutterMarkers,textClass:a.textClass,bgClass:a.bgClass,wrapClass:a.wrapClass,widgets:a.widgets}},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(a,b,c,d,e){var f=this.display;a=kc(this,M(this.doc,a));var g=a.bottom,h=a.left;if(b.style.position="absolute",b.setAttribute("cm-ignore-events","true"),this.display.input.setUneditable(b),f.sizer.appendChild(b),"over"==d)g=a.top;else if("above"==d||"near"==d){var i=Math.max(f.wrapper.clientHeight,this.doc.height),j=Math.max(f.sizer.clientWidth,f.lineSpace.clientWidth);("above"==d||a.bottom+b.offsetHeight>i)&&a.top>b.offsetHeight?g=a.top-b.offsetHeight:a.bottom+b.offsetHeight<=i&&(g=a.bottom),h+b.offsetWidth>j&&(h=j-b.offsetWidth)}b.style.top=g+"px",b.style.left=b.style.right="","right"==e?(h=f.sizer.clientWidth-b.offsetWidth,b.style.right="0px"):("left"==e?h=0:"middle"==e&&(h=(f.sizer.clientWidth-b.offsetWidth)/2),b.style.left=h+"px"),c&&Yc(this,h,g,h+b.offsetWidth,g+b.offsetHeight)},triggerOnKeyDown:ld(pf),triggerOnKeyPress:ld(sf),triggerOnKeyUp:rf,execCommand:function(a){if(th.hasOwnProperty(a))return th[a].call(null,this)},triggerElectric:ld((function(a){Mf(this,a)})),findPosH:function(a,b,c,d){var e=this,f=1;b<0&&(f=-1,b=-b);for(var g=M(this.doc,a),h=0;h0&&h(c.charAt(d-1));)--d;for(;e.5)&&uc(this),Da(this,"refresh",this)})),swapDoc:ld((function(a){var b=this.doc;return b.cm=null,Td(this,a),ec(this),this.display.input.reset(),this.scrollTo(a.scrollLeft,a.scrollTop),this.curOp.forceScroll=!0,xb(this,"swapDoc",this,b),b})),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}},Ha(a),a.registerHelper=function(b,d,e){c.hasOwnProperty(b)||(c[b]=a[b]={_global:[]}),c[b][d]=e},a.registerGlobalHelper=function(b,d,e,f){a.registerHelper(b,d,f),c[b]._global.push({pred:e,val:f})}}function Rf(a,b,c,d,e){function f(){var b=h+c;return!(b=a.first+a.size)&&(h=b,k=y(a,b))}function g(a){var b=(e?ya:za)(k,i,c,!0);if(null==b){if(a||!f())return!1;i=e?(c<0?ua:ta)(k):c<0?k.text.length:0}else i=b;return!0}var h=b.line,i=b.ch,j=c,k=y(a,h);if("char"==d)g();else if("column"==d)g(!0);else if("word"==d||"group"==d)for(var l=null,m="group"==d,n=a.cm&&a.cm.getHelper(b,"wordChars"),o=!0;!(c<0)||g(!o);o=!1){var p=k.text.charAt(i)||"\n",q=u(p,n)?"w":m&&"\n"==p?"n":!m||/\s/.test(p)?null:"p";if(!m||o||q||(q="s"),l&&l!=q){c<0&&(c=1,g());break}if(q&&(l=q),c>0&&!g(!o))break}var r=se(a,G(h,i),b,j,!0);return H(b,r)||(r.hitSide=!0),r}function Sf(a,b,c,d){var e,f=a.doc,g=b.left;if("page"==d){var h=Math.min(a.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight),i=Math.max(h-.5*pc(a.display),3);e=(c>0?b.bottom:b.top)+c*i}else"line"==d&&(e=c>0?b.bottom+3:b.top-3);for(var j;j=nc(a,g,e),j.outside;){if(c<0?e<=0:e>=f.height){j.hitSide=!0;break}e+=5*c}return j}function Tf(a){this.cm=a,this.lastAnchorNode=this.lastAnchorOffset=this.lastFocusNode=this.lastFocusOffset=null,this.polling=new k,this.gracePeriod=!1}function Uf(a,b){var c=Xb(a,b.line);if(!c||c.hidden)return null;var d=y(a.doc,b.line),e=Ub(c,d,b.line),f=Aa(d),g="left";if(f){var h=wa(f,b.ch);g=h%2?"right":"left"}var i=$b(e.map,b.ch,g);return i.offset="right"==i.collapse?i.end:i.start,i}function Vf(a,b){return b&&(a.bad=!0),a}function Wf(a,b,c,d,e){function f(a){return function(b){return b.id==a}}function g(b){if(1==b.nodeType){var c=b.getAttribute("cm-text");if(null!=c)return""==c&&(c=b.textContent.replace(/\u200b/g,"")),void(h+=c);var k,l=b.getAttribute("cm-marker");if(l){var m=a.findMarks(G(d,0),G(e+1,0),f(+l));return void(m.length&&(k=m[0].find())&&(h+=z(a.doc,k.from,k.to).join(j)))}if("false"==b.getAttribute("contenteditable"))return;for(var n=0;n=15&&(kg=!1,hg=!0);var ug,vg=qg&&(ig||kg&&(null==tg||tg<12.11)),wg=cg||fg&&gg>=9,xg=function(b,c){var d=b.className,e=a(c).exec(d);if(e){var f=d.slice(e.index+e[0].length);b.className=d.slice(0,e.index)+(f?e[1]+f:"")}};ug=document.createRange?function(a,b,c,d){var e=document.createRange();return e.setEnd(d||a,c),e.setStart(a,b),e}:function(a,b,c){var d=document.body.createTextRange();try{d.moveToElementText(a.parentNode)}catch(a){return d}return d.collapse(!0),d.moveEnd("character",c),d.moveStart("character",b),d};var yg=function(){for(var a=document.activeElement;a&&a.root&&a.root.activeElement;)a=a.root.activeElement;return a};fg&&gg<11&&(yg=function(){try{return document.activeElement}catch(a){return document.body}});var zg=function(a){a.select()};og?zg=function(a){a.selectionStart=0,a.selectionEnd=a.value.length}:fg&&(zg=function(a){try{a.select()}catch(a){}}),k.prototype.set=function(a,b){clearTimeout(this.id),this.id=setTimeout(b,a)};var Ag,Bg,Cg=30,Dg={toString:function(){return"CodeMirror.Pass"}},Eg={scroll:!1},Fg={origin:"*mouse"},Gg={origin:"+move"},Hg=[""],Ig=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,Jg=/[\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]/,Kg=!1,Lg=!1,Mg=null,Ng=(function(){function a(a){return a<=247?c.charAt(a):1424<=a&&a<=1524?"R":1536<=a&&a<=1773?d.charAt(a-1536):1774<=a&&a<=2220?"r":8192<=a&&a<=8203?"w":8204==a?"b":"L"}function b(a,b,c){this.level=a,this.from=b,this.to=c}var c="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",d="rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm",e=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,f=/[stwN]/,g=/[LRr]/,h=/[Lb1n]/,i=/[1n]/,j="L";return function(c){if(!e.test(c))return!1;for(var d=c.length,k=[],l=0;l=this.string.length},sol:function(){return this.pos==this.lineStart},peek:function(){return this.string.charAt(this.pos)||void 0},next:function(){if(this.posb},eatSpace:function(){for(var a=this,b=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++a.pos;return this.pos>b},skipToEnd:function(){this.pos=this.string.length},skipTo:function(a){var b=this.string.indexOf(a,this.pos);if(b>-1)return this.pos=b,!0},backUp:function(a){this.pos-=a},column:function(){return this.lastColumnPos0?null:(d&&b!==!1&&(this.pos+=d[0].length),d)}var e=function(a){return c?a.toLowerCase():a},f=this.string.substr(this.pos,a.length);if(e(f)==e(a))return b!==!1&&(this.pos+=a.length),!0},current:function(){return this.string.slice(this.start,this.pos)},hideFirstChars:function(a,b){this.lineStart+=a;try{return b()}finally{this.lineStart-=a}}},Ha(hb),hb.prototype.lineNo=function(){return C(this)};var Zg,$g={},_g={},ah=null,bh=null,ch={left:0,right:0,top:0,bottom:0},dh=0,eh=null;fg?eh=-.53:cg?eh=15:jg?eh=-.7:lg&&(eh=-1/3),Rc.prototype=i({update:function(a){var b=a.scrollWidth>a.clientWidth+1,c=a.scrollHeight>a.clientHeight+1,d=a.nativeBarWidth;if(c){this.vert.style.display="block",this.vert.style.bottom=b?d+"px":"0";var e=a.viewHeight-(b?d:0);this.vert.firstChild.style.height=Math.max(0,a.scrollHeight-a.clientHeight+e)+"px"}else this.vert.style.display="",this.vert.firstChild.style.height="0";if(b){this.horiz.style.display="block",this.horiz.style.right=c?d+"px":"0",this.horiz.style.left=a.barLeft+"px";var f=a.viewWidth-a.barLeft-(c?d:0);this.horiz.firstChild.style.width=a.scrollWidth-a.clientWidth+f+"px"}else this.horiz.style.display="",this.horiz.firstChild.style.width="0";return!this.checkedZeroWidth&&a.clientHeight>0&&(0==d&&this.zeroWidthHack(),this.checkedZeroWidth=!0),{right:c?d:0,bottom:b?d:0}},setScrollLeft:function(a){this.horiz.scrollLeft!=a&&(this.horiz.scrollLeft=a),this.disableHoriz&&this.enableZeroWidthBar(this.horiz,this.disableHoriz)},setScrollTop:function(a){this.vert.scrollTop!=a&&(this.vert.scrollTop=a),this.disableVert&&this.enableZeroWidthBar(this.vert,this.disableVert)},zeroWidthHack:function(){var a=qg&&!mg?"12px":"18px";this.horiz.style.height=this.vert.style.width=a,this.horiz.style.pointerEvents=this.vert.style.pointerEvents="none",this.disableHoriz=new k,this.disableVert=new k},enableZeroWidthBar:function(a,b){function c(){var d=a.getBoundingClientRect(),e=document.elementFromPoint(d.left+1,d.bottom-1);e!=a?a.style.pointerEvents="none":b.set(1e3,c)}a.style.pointerEvents="auto",b.set(1e3,c)},clear:function(){var a=this.horiz.parentNode;a.removeChild(this.horiz),a.removeChild(this.vert)}},Rc.prototype),Sc.prototype=i({update:function(){return{bottom:0,right:0}},setScrollLeft:function(){},setScrollTop:function(){},clear:function(){}},Sc.prototype);var fh={native:Rc,null:Sc},gh=0;vd.prototype.signal=function(a,b){Ga(a,b)&&this.events.push(arguments)},vd.prototype.finish=function(){for(var a=this,b=0;b=0&&H(a,e.to())<=0)return d}return-1}},Gd.prototype={from:function(){return K(this.anchor,this.head)},to:function(){return J(this.anchor,this.head)},empty:function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch}},He.prototype={chunkSize:function(){return this.lines.length},removeInner:function(a,b){for(var c=this,d=a,e=a+b;d1||!(this.children[0]instanceof He))){var i=[];this.collapse(i),this.children=[new He(i)],this.children[0].parent=this}},collapse:function(a){for(var b=this,c=0;c50){for(var h=f.lines.length%25+25,i=h;i10);a.parent.maybeSpill()}},iterN:function(a,b,c){for(var d=this,e=0;eb.display.maxLineLength&&(b.display.maxLine=k,b.display.maxLineLength=l,b.display.maxLineChanged=!0)}null!=e&&b&&this.collapsed&&nd(b,e,f+1),this.lines.length=0,this.explicitlyCleared=!0,this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,b&&pe(b.doc)),b&&xb(b,"markerCleared",b,this),c&&cd(b),this.parent&&this.parent.clear()}},Me.prototype.find=function(a,b){ +var c=this;null==a&&"bookmark"==this.type&&(a=1);for(var d,e,f=0;f=0;j--)we(d,e[j]);i?le(this,i):this.cm&&_c(this.cm)})),undo:md((function(){ye(this,"undo")})),redo:md((function(){ye(this,"redo")})),undoSelection:md((function(){ye(this,"undo",!0)})),redoSelection:md((function(){ye(this,"redo",!0)})),setExtending:function(a){this.extend=a},getExtending:function(){return this.extend},historySize:function(){for(var a=this.history,b=0,c=0,d=0;d=a.ch)&&b.push(e.marker.parent||e.marker)}return b},findMarks:function(a,b,c){a=M(this,a),b=M(this,b);var d=[],e=a.line;return this.iter(a.line,b.line+1,(function(f){var g=f.markedSpans;if(g)for(var h=0;h=i.to||null==i.from&&e!=a.line||null!=i.from&&e==b.line&&i.from>=b.ch||c&&!c(i.marker)||d.push(i.marker.parent||i.marker)}++e})),d},getAllMarks:function(){var a=[];return this.iter((function(b){var c=b.markedSpans;if(c)for(var d=0;da?(b=a,!0):(a-=f,void++c)})),M(this,G(c,b))},indexFromPos:function(a){a=M(this,a);var b=a.ch;if(a.lineb&&(b=a.from),null!=a.to&&a.to0)e=new G(e.line,e.ch+1),a.replaceRange(f.charAt(e.ch-1)+f.charAt(e.ch-2),G(e.line,e.ch-2),e,"+transpose");else if(e.line>a.doc.first){var g=y(a.doc,e.line-1).text;g&&(e=new G(e.line,1),a.replaceRange(f.charAt(0)+a.doc.lineSeparator()+g.charAt(g.length-1),G(e.line-1,g.length-1),e,"+transpose"))}c.push(new Gd(e,e))}a.setSelections(c)}))},newlineAndIndent:function(a){return jd(a,(function(){for(var b=a.listSelections(),c=b.length-1;c>=0;c--)a.replaceRange(a.doc.lineSeparator(),b[c].anchor,b[c].head,"+input");b=a.listSelections();for(var d=0;d-1&&g<=e.head.ch&&(c.composing.sel=Id(G(e.head.line,g),G(e.head.line,g+b.length)))}})),Og(e,"compositionupdate",(function(a){return c.composing.data=a.data})),Og(e,"compositionend",(function(a){var b=c.composing;b&&(a.data==b.startData||/\u200b/.test(a.data)||(b.data=a.data),setTimeout((function(){b.handled||c.applyComposition(b),c.composing==b&&(c.composing=null)}),50))})),Og(e,"touchstart",(function(){return c.forceCompositionEnd()})),Og(e,"input",(function(){c.composing||!d.isReadOnly()&&c.pollContent()||jd(c.cm,(function(){return nd(d)}))})),Og(e,"copy",b),Og(e,"cut",b)},prepareSelection:function(){var a=yc(this.cm,!1);return a.focus=this.cm.state.focused,a},showSelection:function(a,b){a&&this.cm.display.view.length&&((a.focus||b)&&this.showPrimarySelection(),this.showMultipleSelections(a))},showPrimarySelection:function(){var a=window.getSelection(),b=this.cm.doc.sel.primary(),c=Xf(this.cm,a.anchorNode,a.anchorOffset),d=Xf(this.cm,a.focusNode,a.focusOffset);if(!c||c.bad||!d||d.bad||0!=H(K(c,d),b.from())||0!=H(J(c,d),b.to())){var e=Uf(this.cm,b.from()),f=Uf(this.cm,b.to());if(e||f){var g=this.cm.display.view,h=a.rangeCount&&a.getRangeAt(0);if(e){if(!f){var i=g[g.length-1].measure,j=i.maps?i.maps[i.maps.length-1]:i.map;f={node:j[j.length-1],offset:j[j.length-2]-j[j.length-3]}}}else e={node:g[0].measure.map[2],offset:0};var k;try{k=ug(e.node,e.offset,f.offset,f.node)}catch(a){}k&&(!cg&&this.cm.state.focused?(a.collapse(e.node,e.offset),k.collapsed||(a.removeAllRanges(),a.addRange(k))):(a.removeAllRanges(),a.addRange(k)),h&&null==a.anchorNode?a.addRange(h):cg&&this.startGracePeriod()),this.rememberSelection()}}},startGracePeriod:function(){var a=this;clearTimeout(this.gracePeriod),this.gracePeriod=setTimeout((function(){a.gracePeriod=!1,a.selectionChanged()&&a.cm.operation((function(){return a.cm.curOp.selectionChanged=!0}))}),20)},showMultipleSelections:function(a){c(this.cm.display.cursorDiv,a.cursors),c(this.cm.display.selectionDiv,a.selection)},rememberSelection:function(){var a=window.getSelection();this.lastAnchorNode=a.anchorNode,this.lastAnchorOffset=a.anchorOffset,this.lastFocusNode=a.focusNode,this.lastFocusOffset=a.focusOffset},selectionInEditor:function(){var a=window.getSelection();if(!a.rangeCount)return!1;var b=a.getRangeAt(0).commonAncestorContainer;return e(this.div,b)},focus:function(){"nocursor"!=this.cm.options.readOnly&&this.div.focus()},blur:function(){this.div.blur()},getField:function(){return this.div},supportsTouch:function(){return!0},receivedFocus:function(){function a(){b.cm.state.focused&&(b.pollSelection(),b.polling.set(b.cm.options.pollInterval,a))}var b=this;this.selectionInEditor()?this.pollSelection():jd(this.cm,(function(){return b.cm.curOp.selectionChanged=!0})),this.polling.set(this.cm.options.pollInterval,a)},selectionChanged:function(){var a=window.getSelection();return a.anchorNode!=this.lastAnchorNode||a.anchorOffset!=this.lastAnchorOffset||a.focusNode!=this.lastFocusNode||a.focusOffset!=this.lastFocusOffset},pollSelection:function(){if(!this.composing&&!this.gracePeriod&&this.selectionChanged()){var a=window.getSelection(),b=this.cm;this.rememberSelection();var c=Xf(b,a.anchorNode,a.anchorOffset),d=Xf(b,a.focusNode,a.focusOffset);c&&d&&jd(b,(function(){me(b.doc,Id(c,d),Eg),(c.bad||d.bad)&&(b.curOp.selectionChanged=!0)}))}},pollContent:function(){var a=this.cm,b=a.display,c=a.doc.sel.primary(),d=c.from(),e=c.to();if(d.lineb.viewTo-1)return!1;var f,g,h;d.line==b.viewFrom||0==(f=wc(a,d.line))?(g=C(b.view[0].line),h=b.view[0].node):(g=C(b.view[f].line),h=b.view[f-1].node.nextSibling);var i,j,k=wc(a,e.line);k==b.view.length-1?(i=b.viewTo-1,j=b.lineDiv.lastChild):(i=C(b.view[k+1].line)-1,j=b.view[k+1].node.previousSibling);for(var l=a.doc.splitLines(Wf(a,h,j,g,i)),m=z(a.doc,G(g,0),G(i,y(a.doc,i).text.length));l.length>1&&m.length>1;)if(o(l)==o(m))l.pop(),m.pop(),i--;else{if(l[0]!=m[0])break;l.shift(),m.shift(),g++}for(var n=0,p=0,q=l[0],r=m[0],s=Math.min(q.length,r.length);n1||l[0]||H(w,x)?(Ce(a.doc,l,w,x,"+input"),!0):void 0},ensurePolled:function(){this.forceCompositionEnd()},reset:function(){this.forceCompositionEnd()},forceCompositionEnd:function(){this.composing&&!this.composing.handled&&(this.applyComposition(this.composing),this.composing.handled=!0,this.div.blur(),this.div.focus())},applyComposition:function(a){this.cm.isReadOnly()?kd(this.cm,nd)(this.cm):a.data&&a.data!=a.startData&&kd(this.cm,Kf)(this.cm,a.data,0,a.sel)},setUneditable:function(a){a.contentEditable="false"},onKeyPress:function(a){a.preventDefault(),this.cm.isReadOnly()||kd(this.cm,Kf)(this.cm,String.fromCharCode(null==a.charCode?a.keyCode:a.charCode),0)},readOnlyChanged:function(a){this.div.contentEditable=String("nocursor"!=a)},onContextMenu:r,resetPosition:r,needsContentAttribute:!0},Tf.prototype),Zf.prototype=i({init:function(a){function b(a){if(!Ea(e,a)){if(e.somethingSelected())Jf({lineWise:!1,text:e.getSelections()}),d.inaccurateSelection&&(d.prevInput="",d.inaccurateSelection=!1,g.value=Ah.text.join("\n"),zg(g));else{if(!e.options.lineWiseCopyCut)return;var b=Nf(e);Jf({lineWise:!0,text:b.text}),"cut"==a.type?e.setSelections(b.ranges,null,Eg):(d.prevInput="",g.value=b.text.join("\n"),zg(g))}"cut"==a.type&&(e.state.cutIncoming=!0)}}var c=this,d=this,e=this.cm,f=this.wrapper=Pf(),g=this.textarea=f.firstChild;a.wrapper.insertBefore(f,a.wrapper.firstChild),og&&(g.style.width="0px"),Og(g,"input",(function(){fg&&gg>=9&&c.hasSelection&&(c.hasSelection=null),d.poll()})),Og(g,"paste",(function(a){Ea(e,a)||Lf(a,e)||(e.state.pasteIncoming=!0,d.fastPoll())})),Og(g,"cut",b),Og(g,"copy",b),Og(a.scroller,"paste",(function(b){Mb(a,b)||Ea(e,b)||(e.state.pasteIncoming=!0,d.focus())})),Og(a.lineSpace,"selectstart",(function(b){Mb(a,b)||Ia(b)})),Og(g,"compositionstart",(function(){var a=e.getCursor("from");d.composing&&d.composing.range.clear(),d.composing={start:a,range:e.markText(a,e.getCursor("to"),{className:"CodeMirror-composing"})}})),Og(g,"compositionend",(function(){d.composing&&(d.poll(),d.composing.range.clear(),d.composing=null)}))},prepareSelection:function(){var a=this.cm,b=a.display,c=a.doc,d=yc(a);if(a.options.moveInputWithCursor){var e=kc(a,c.sel.primary().head,"div"),f=b.wrapper.getBoundingClientRect(),g=b.lineDiv.getBoundingClientRect();d.teTop=Math.max(0,Math.min(b.wrapper.clientHeight-10,e.top+g.top-f.top)),d.teLeft=Math.max(0,Math.min(b.wrapper.clientWidth-10,e.left+g.left-f.left))}return d},showSelection:function(a){var b=this.cm,d=b.display;c(d.cursorDiv,a.cursors),c(d.selectionDiv,a.selection),null!=a.teTop&&(this.wrapper.style.top=a.teTop+"px",this.wrapper.style.left=a.teLeft+"px")},reset:function(a){if(!this.contextMenuPending){var b,c,d=this.cm,e=d.doc;if(d.somethingSelected()){this.prevInput="";var f=e.sel.primary();b=Tg&&(f.to().line-f.from().line>100||(c=d.getSelection()).length>1e3);var g=b?"-":c||d.getSelection();this.textarea.value=g,d.state.focused&&zg(this.textarea),fg&&gg>=9&&(this.hasSelection=g)}else a||(this.prevInput=this.textarea.value="",fg&&gg>=9&&(this.hasSelection=null));this.inaccurateSelection=b}},getField:function(){return this.textarea},supportsTouch:function(){return!1},focus:function(){if("nocursor"!=this.cm.options.readOnly&&(!pg||yg()!=this.textarea))try{this.textarea.focus()}catch(a){}},blur:function(){this.textarea.blur()},resetPosition:function(){this.wrapper.style.top=this.wrapper.style.left=0},receivedFocus:function(){this.slowPoll()},slowPoll:function(){var a=this;this.pollingFast||this.polling.set(this.cm.options.pollInterval,(function(){a.poll(),a.cm.state.focused&&a.slowPoll()}))},fastPoll:function(){function a(){var d=c.poll();d||b?(c.pollingFast=!1,c.slowPoll()):(b=!0,c.polling.set(60,a))}var b=!1,c=this;c.pollingFast=!0,c.polling.set(20,a)},poll:function(){var a=this,b=this.cm,c=this.textarea,d=this.prevInput;if(this.contextMenuPending||!b.state.focused||Sg(c)&&!d&&!this.composing||b.isReadOnly()||b.options.disableInput||b.state.keySeq)return!1;var e=c.value;if(e==d&&!b.somethingSelected())return!1;if(fg&&gg>=9&&this.hasSelection===e||qg&&/[\uf700-\uf7ff]/.test(e))return b.display.input.reset(),!1;if(b.doc.sel==b.display.selForContextMenu){var f=e.charCodeAt(0);if(8203!=f||d||(d="​"),8666==f)return this.reset(),this.cm.execCommand("undo")}for(var g=0,h=Math.min(d.length,e.length);g1e3||e.indexOf("\n")>-1?c.value=a.prevInput="":a.prevInput=e,a.composing&&(a.composing.range.clear(),a.composing.range=b.markText(a.composing.start,b.getCursor("to"),{className:"CodeMirror-composing"}))})),!0},ensurePolled:function(){this.pollingFast&&this.poll()&&(this.pollingFast=!1)},onKeyPress:function(){fg&&gg>=9&&(this.hasSelection=null),this.fastPoll()},onContextMenu:function(a){function b(){if(null!=g.selectionStart){var a=e.somethingSelected(),b="​"+(a?g.value:"");g.value="⇚",g.value=b,d.prevInput=a?"":"​",g.selectionStart=1,g.selectionEnd=b.length,f.selForContextMenu=e.doc.sel}}function c(){if(d.contextMenuPending=!1,d.wrapper.style.cssText=l,g.style.cssText=k,fg&&gg<9&&f.scrollbars.setScrollTop(f.scroller.scrollTop=i),null!=g.selectionStart){(!fg||fg&&gg<9)&&b();var a=0,c=function(){f.selForContextMenu==e.doc.sel&&0==g.selectionStart&&g.selectionEnd>0&&"​"==d.prevInput?kd(e,ue)(e):a++<10?f.detectingSelectAll=setTimeout(c,500):f.input.reset()};f.detectingSelectAll=setTimeout(c,200)}}var d=this,e=d.cm,f=e.display,g=d.textarea,h=vc(e,a),i=f.scroller.scrollTop;if(h&&!kg){var j=e.options.resetSelectionOnContextMenu;j&&e.doc.sel.contains(h)==-1&&kd(e,me)(e.doc,Id(h),Eg);var k=g.style.cssText,l=d.wrapper.style.cssText;d.wrapper.style.cssText="position: absolute";var m=d.wrapper.getBoundingClientRect();g.style.cssText="position: absolute; width: 30px; height: 30px;\n top: "+(a.clientY-m.top-5)+"px; left: "+(a.clientX-m.left-5)+"px;\n z-index: 1000; background: "+(fg?"rgba(255, 255, 255, .05)":"transparent")+";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";var n;if(hg&&(n=window.scrollY),f.input.focus(),hg&&window.scrollTo(null,n),f.input.reset(),e.somethingSelected()||(g.value=d.prevInput=" "),d.contextMenuPending=!0,f.selForContextMenu=e.doc.sel,clearTimeout(f.detectingSelectAll),fg&&gg>=9&&b(),wg){La(a);var o=function(){Ca(window,"mouseup",o),setTimeout(c,20)};Og(window,"mouseup",o)}else setTimeout(c,50)}},readOnlyChanged:function(a){a||this.reset()},setUneditable:r,needsContentAttribute:!1},Zf.prototype),Cf(Gf),Qf(Gf);var Bh="iter insert remove copy getEditor constructor".split(" ");for(var Ch in jh.prototype)jh.prototype.hasOwnProperty(Ch)&&l(Bh,Ch)<0&&(Gf.prototype[Ch]=(function(a){return function(){return a.apply(this.doc,arguments)}})(jh.prototype[Ch]));return Ha(jh),Gf.inputStyles={textarea:Zf,contenteditable:Tf},Gf.defineMode=function(a){Gf.defaults.mode||"null"==a||(Gf.defaults.mode=a),Ra.apply(this,arguments)},Gf.defineMIME=Sa,Gf.defineMode("null",(function(){return{token:function(a){return a.skipToEnd()}}})),Gf.defineMIME("text/plain","null"),Gf.defineExtension=function(a,b){Gf.prototype[a]=b},Gf.defineDocExtension=function(a,b){jh.prototype[a]=b},Gf.fromTextArea=$f,_f(Gf),Gf.version="5.20.2",Gf})); \ No newline at end of file diff --git a/media/editors/codemirror/mode/clike/clike.js b/media/editors/codemirror/mode/clike/clike.js index a37921fdae7ed..cad2d5145c5d0 100644 --- a/media/editors/codemirror/mode/clike/clike.js +++ b/media/editors/codemirror/mode/clike/clike.js @@ -21,7 +21,7 @@ function Context(indented, column, type, info, align, prev) { } function pushContext(state, col, type, info) { var indent = state.indented; - if (state.context && state.context.type != "statement" && type != "statement") + if (state.context && state.context.type == "statement" && type != "statement") indent = state.context.indented; return state.context = new Context(indent, col, type, info, null, state.context); } @@ -64,8 +64,7 @@ CodeMirror.defineMode("clike", function(config, parserConfig) { isPunctuationChar = parserConfig.isPunctuationChar || /[\[\]{}\(\),;\:\.]/, numberStart = parserConfig.numberStart || /[\d\.]/, number = parserConfig.number || /^(?:0x[a-f\d]+|0b[01]+|(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)(u|ll?|l|f)?/i, - isOperatorChar = parserConfig.isOperatorChar || /[+\-*&%=<>!?|\/]/, - endStatement = parserConfig.endStatement || /^[;:,]$/; + isOperatorChar = parserConfig.isOperatorChar || /[+\-*&%=<>!?|\/]/; var curPunc, isDefKeyword; @@ -177,7 +176,8 @@ CodeMirror.defineMode("clike", function(config, parserConfig) { if (style == "comment" || style == "meta") return style; if (ctx.align == null) ctx.align = true; - if (endStatement.test(curPunc)) while (state.context.type == "statement") popContext(state); + if (curPunc == ";" || curPunc == ":" || (curPunc == "," && stream.match(/^\s*(?:\/\/.*)?$/, false))) + while (state.context.type == "statement") popContext(state); else if (curPunc == "{") pushContext(state, stream.column(), "}"); else if (curPunc == "[") pushContext(state, stream.column(), "]"); else if (curPunc == "(") pushContext(state, stream.column(), ")"); @@ -432,7 +432,6 @@ CodeMirror.defineMode("clike", function(config, parserConfig) { defKeywords: words("class interface package enum"), typeFirstDefinitions: true, atoms: words("true false null"), - endStatement: /^[;:]$/, number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+\.?\d*|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i, hooks: { "@": function(stream) { diff --git a/media/editors/codemirror/mode/clike/clike.min.js b/media/editors/codemirror/mode/clike/clike.min.js index 302a6b57ddd41..afb83417aac4a 100644 --- a/media/editors/codemirror/mode/clike/clike.min.js +++ b/media/editors/codemirror/mode/clike/clike.min.js @@ -1 +1 @@ -!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";function b(a,b,c,d,e,f){this.indented=a,this.column=b,this.type=c,this.info=d,this.align=e,this.prev=f}function c(a,c,d,e){var f=a.indented;return a.context&&"statement"!=a.context.type&&"statement"!=d&&(f=a.context.indented),a.context=new b(f,c,d,e,null,a.context)}function d(a){var b=a.context.type;return")"!=b&&"]"!=b&&"}"!=b||(a.indented=a.context.indented),a.context=a.context.prev}function e(a,b,c){return"variable"==b.prevToken||"variable-3"==b.prevToken||(!!/\S(?:[^- ]>|[*\]])\s*$|\*$/.test(a.string.slice(0,c))||(!(!b.typeAtEndOfLine||a.column()!=a.indentation())||void 0))}function f(a){for(;;){if(!a||"top"==a.type)return!0;if("}"==a.type&&"namespace"!=a.prev.info)return!1;a=a.prev}}function g(a){for(var b={},c=a.split(" "),d=0;d!?|\/]/,H=i.endStatement||/^[;:,]$/;return{startState:function(a){return{tokenize:null,context:new b((a||0)-p,0,"top",null,!1),indented:0,startOfLine:!0,prevToken:null}},token:function(a,b){var g=b.context;if(a.sol()&&(null==g.align&&(g.align=!1),b.indented=a.indentation(),b.startOfLine=!0),a.eatSpace())return m(a,b),null;n=o=null;var h=(b.tokenize||j)(a,b);if("comment"==h||"meta"==h)return h;if(null==g.align&&(g.align=!0),H.test(n))for(;"statement"==b.context.type;)d(b);else if("{"==n)c(b,a.column(),"}");else if("["==n)c(b,a.column(),"]");else if("("==n)c(b,a.column(),")");else if("}"==n){for(;"statement"==g.type;)g=d(b);for("}"==g.type&&(g=d(b));"statement"==g.type;)g=d(b)}else n==g.type?d(b):A&&(("}"==g.type||"top"==g.type)&&";"!=n||"statement"==g.type&&"newstatement"==n)&&c(b,a.column(),"statement",a.current());if("variable"==h&&("def"==b.prevToken||i.typeFirstDefinitions&&e(a,b,a.start)&&f(b.context)&&a.match(/^\s*\(/,!1))&&(h="def"),y.token){var k=y.token(a,b,h);void 0!==k&&(h=k)}return"def"==h&&i.styleDefs===!1&&(h="variable"),b.startOfLine=!1,b.prevToken=o?"def":h||n,m(a,b),h},indent:function(b,c){if(b.tokenize!=j&&null!=b.tokenize||b.typeAtEndOfLine)return a.Pass;var d=b.context,e=c&&c.charAt(0);if("statement"==d.type&&"}"==e&&(d=d.prev),i.dontIndentStatements)for(;"statement"==d.type&&i.dontIndentStatements.test(d.info);)d=d.prev;if(y.indent){var f=y.indent(b,d,c);if("number"==typeof f)return f}var g=e==d.type,h=d.prev&&"switch"==d.prev.info;if(i.allmanIndentation&&/[{(]/.test(e)){for(;"top"!=d.type&&"}"!=d.type;)d=d.prev;return d.indented}return"statement"==d.type?d.indented+("{"==e?0:q):!d.align||r&&")"==d.type?")"!=d.type||g?d.indented+(g?0:p)+(g||!h||/^(?:case|default)\b/.test(c)?0:p):d.indented+q:d.column+(g?0:1)},electricInput:B?/^\s*(?:case .*?:|default:|\{\}?|\})$/:/^\s*[{}]$/,blockCommentStart:"/*",blockCommentEnd:"*/",lineComment:"//",fold:"brace"}}));var t="auto if break case register continue return default do sizeof static else struct switch extern typedef union for goto while enum const volatile",u="int long char short double float unsigned signed void size_t ptrdiff_t";p(["text/x-csrc","text/x-c","text/x-chdr"],{name:"clike",keywords:g(t),types:g(u+" bool _Complex _Bool float_t double_t intptr_t intmax_t int8_t int16_t int32_t int64_t uintptr_t uintmax_t uint8_t uint16_t uint32_t uint64_t"),blockKeywords:g("case do else for if switch while struct"),defKeywords:g("struct"),typeFirstDefinitions:!0,atoms:g("null true false"),hooks:{"#":i,"*":j},modeProps:{fold:["brace","include"]}}),p(["text/x-c++src","text/x-c++hdr"],{name:"clike",keywords:g(t+" asm dynamic_cast namespace reinterpret_cast try explicit new static_cast typeid catch operator template typename class friend private this using const_cast inline public throw virtual delete mutable protected alignas alignof constexpr decltype nullptr noexcept thread_local final static_assert override"),types:g(u+" bool wchar_t"),blockKeywords:g("catch class do else finally for if struct switch try while"),defKeywords:g("class namespace struct enum union"),typeFirstDefinitions:!0,atoms:g("true false null"),dontIndentStatements:/^template$/,hooks:{"#":i,"*":j,u:l,U:l,L:l,R:l,0:k,1:k,2:k,3:k,4:k,5:k,6:k,7:k,8:k,9:k,token:function(a,b,c){if("variable"==c&&"("==a.peek()&&(";"==b.prevToken||null==b.prevToken||"}"==b.prevToken)&&m(a.current()))return"def"}},namespaceSeparator:"::",modeProps:{fold:["brace","include"]}}),p("text/x-java",{name:"clike",keywords:g("abstract assert break case catch class const continue default do else enum extends final finally float for goto if implements import instanceof interface native new package private protected public return static strictfp super switch synchronized this throw throws transient try volatile while"),types:g("byte short int long float double boolean char void Boolean Byte Character Double Float Integer Long Number Object Short String StringBuffer StringBuilder Void"),blockKeywords:g("catch class do else finally for if switch try while"),defKeywords:g("class interface package enum"),typeFirstDefinitions:!0,atoms:g("true false null"),endStatement:/^[;:]$/,number:/^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+\.?\d*|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i,hooks:{"@":function(a){return a.eatWhile(/[\w\$_]/),"meta"}},modeProps:{fold:["brace","import"]}}),p("text/x-csharp",{name:"clike",keywords:g("abstract as async await base break case catch checked class const continue default delegate do else enum event explicit extern finally fixed for foreach goto if implicit in interface internal is lock namespace new operator out override params private protected public readonly ref return sealed sizeof stackalloc static struct switch this throw try typeof unchecked unsafe using virtual void volatile while add alias ascending descending dynamic from get global group into join let orderby partial remove select set value var yield"),types:g("Action Boolean Byte Char DateTime DateTimeOffset Decimal Double Func Guid Int16 Int32 Int64 Object SByte Single String Task TimeSpan UInt16 UInt32 UInt64 bool byte char decimal double short int long object sbyte float string ushort uint ulong"),blockKeywords:g("catch class do else finally for foreach if struct switch try while"),defKeywords:g("class interface namespace struct var"),typeFirstDefinitions:!0,atoms:g("true false null"),hooks:{"@":function(a,b){return a.eat('"')?(b.tokenize=n,n(a,b)):(a.eatWhile(/[\w\$_]/),"meta")}}}),p("text/x-scala",{name:"clike",keywords:g("abstract case catch class def do else extends final finally for forSome if implicit import lazy match new null object override package private protected return sealed super this throw trait try type val var while with yield _ : = => <- <: <% >: # @ assert assume require print println printf readLine readBoolean readByte readShort readChar readInt readLong readFloat readDouble :: #:: "),types:g("AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either Enumeration Equiv Error Exception Fractional Function IndexedSeq Int Integral Iterable Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable Compiler Double Exception Float Integer Long Math Number Object Package Pair Process Runtime Runnable SecurityManager Short StackTraceElement StrictMath String StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"),multiLineStrings:!0,blockKeywords:g("catch class do else finally for forSome if match switch try while"),defKeywords:g("class def object package trait type val var"),atoms:g("true false null"),indentStatements:!1,indentSwitch:!1,hooks:{"@":function(a){return a.eatWhile(/[\w\$_]/),"meta"},'"':function(a,b){return!!a.match('""')&&(b.tokenize=q,b.tokenize(a,b))},"'":function(a){return a.eatWhile(/[\w\$_\xa1-\uffff]/),"atom"},"=":function(a,c){var d=c.context;return!("}"!=d.type||!d.align||!a.eat(">"))&&(c.context=new b(d.indented,d.column,d.type,d.info,null,d.prev),"operator")}},modeProps:{closeBrackets:{triples:'"'}}}),p("text/x-kotlin",{name:"clike",keywords:g("package as typealias class interface this super val var fun for is in This throw return break continue object if else while do try when !in !is as? file import where by get set abstract enum open inner override private public internal protected catch finally out final vararg reified dynamic companion constructor init sealed field property receiver param sparam lateinit data inline noinline tailrec external annotation crossinline const operator infix"),types:g("Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable Compiler Double Exception Float Integer Long Math Number Object Package Pair Process Runtime Runnable SecurityManager Short StackTraceElement StrictMath String StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"),intendSwitch:!1,indentStatements:!1,multiLineStrings:!0,blockKeywords:g("catch class do else finally for if where try while enum"),defKeywords:g("class val var object package interface fun"),atoms:g("true false null this"),hooks:{'"':function(a,b){return b.tokenize=r(a.match('""')),b.tokenize(a,b)}},modeProps:{closeBrackets:{triples:'"'}}}),p(["x-shader/x-vertex","x-shader/x-fragment"],{name:"clike",keywords:g("sampler1D sampler2D sampler3D samplerCube sampler1DShadow sampler2DShadow const attribute uniform varying break continue discard return for while do if else struct in out inout"),types:g("float int bool void vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 mat2 mat3 mat4"),blockKeywords:g("for while do if else struct"),builtin:g("radians degrees sin cos tan asin acos atan pow exp log exp2 sqrt inversesqrt abs sign floor ceil fract mod min max clamp mix step smoothstep length distance dot cross normalize ftransform faceforward reflect refract matrixCompMult lessThan lessThanEqual greaterThan greaterThanEqual equal notEqual any all not texture1D texture1DProj texture1DLod texture1DProjLod texture2D texture2DProj texture2DLod texture2DProjLod texture3D texture3DProj texture3DLod texture3DProjLod textureCube textureCubeLod shadow1D shadow2D shadow1DProj shadow2DProj shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod dFdx dFdy fwidth noise1 noise2 noise3 noise4"),atoms:g("true false gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 gl_FogCoord gl_PointCoord gl_Position gl_PointSize gl_ClipVertex gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor gl_TexCoord gl_FogFragCoord gl_FragCoord gl_FrontFacing gl_FragData gl_FragDepth gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse gl_TexureMatrixTranspose gl_ModelViewMatrixInverseTranspose gl_ProjectionMatrixInverseTranspose gl_ModelViewProjectionMatrixInverseTranspose gl_TextureMatrixInverseTranspose gl_NormalScale gl_DepthRange gl_ClipPlane gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel gl_FrontLightModelProduct gl_BackLightModelProduct gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ gl_FogParameters gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits gl_MaxDrawBuffers"),indentSwitch:!1,hooks:{"#":i},modeProps:{fold:["brace","include"]}}),p("text/x-nesc",{name:"clike",keywords:g(t+"as atomic async call command component components configuration event generic implementation includes interface module new norace nx_struct nx_union post provides signal task uses abstract extends"),types:g(u),blockKeywords:g("case do else for if switch while struct"),atoms:g("null true false"),hooks:{"#":i},modeProps:{fold:["brace","include"]}}),p("text/x-objectivec",{name:"clike",keywords:g(t+"inline restrict _Bool _Complex _Imaginary BOOL Class bycopy byref id IMP in inout nil oneway out Protocol SEL self super atomic nonatomic retain copy readwrite readonly"),types:g(u),atoms:g("YES NO NULL NILL ON OFF true false"),hooks:{"@":function(a){return a.eatWhile(/[\w\$]/),"keyword"},"#":i,indent:function(a,b,c){if("statement"==b.type&&/^@\w/.test(c))return b.indented}},modeProps:{fold:"brace"}}),p("text/x-squirrel",{name:"clike",keywords:g("base break clone continue const default delete enum extends function in class foreach local resume return this throw typeof yield constructor instanceof static"),types:g(u),blockKeywords:g("case catch class else for foreach if switch try while"),defKeywords:g("function local class"),typeFirstDefinitions:!0,atoms:g("true false null"),hooks:{"#":i},modeProps:{fold:["brace","include"]}});var v=null;p("text/x-ceylon",{name:"clike",keywords:g("abstracts alias assembly assert assign break case catch class continue dynamic else exists extends finally for function given if import in interface is let module new nonempty object of out outer package return satisfies super switch then this throw try value void while"),types:function(a){var b=a.charAt(0);return b===b.toUpperCase()&&b!==b.toLowerCase()},blockKeywords:g("case catch class dynamic else finally for function if interface module new object switch try while"),defKeywords:g("class dynamic function interface module object package value"),builtin:g("abstract actual aliased annotation by default deprecated doc final formal late license native optional sealed see serializable shared suppressWarnings tagged throws variable"),isPunctuationChar:/[\[\]{}\(\),;\:\.`]/,isOperatorChar:/[+\-*&%=<>!?|^~:\/]/,numberStart:/[\d#$]/,number:/^(?:#[\da-fA-F_]+|\$[01_]+|[\d_]+[kMGTPmunpf]?|[\d_]+\.[\d_]+(?:[eE][-+]?\d+|[kMGTPmunpf]|)|)/i,multiLineStrings:!0,typeFirstDefinitions:!0,atoms:g("true false null larger smaller equal empty finished"),indentSwitch:!1,styleDefs:!1,hooks:{"@":function(a){return a.eatWhile(/[\w\$_]/),"meta"},'"':function(a,b){return b.tokenize=s(a.match('""')?"triple":"single"),b.tokenize(a,b)},"`":function(a,b){return!(!v||!a.match("`"))&&(b.tokenize=v,v=null,b.tokenize(a,b))},"'":function(a){return a.eatWhile(/[\w\$_\xa1-\uffff]/),"atom"},token:function(a,b,c){if(("variable"==c||"variable-3"==c)&&"."==b.prevToken)return"variable-2"}},modeProps:{fold:["brace","import"],closeBrackets:{triples:'"'}}})})); \ No newline at end of file +!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";function b(a,b,c,d,e,f){this.indented=a,this.column=b,this.type=c,this.info=d,this.align=e,this.prev=f}function c(a,c,d,e){var f=a.indented;return a.context&&"statement"==a.context.type&&"statement"!=d&&(f=a.context.indented),a.context=new b(f,c,d,e,null,a.context)}function d(a){var b=a.context.type;return")"!=b&&"]"!=b&&"}"!=b||(a.indented=a.context.indented),a.context=a.context.prev}function e(a,b,c){return"variable"==b.prevToken||"variable-3"==b.prevToken||(!!/\S(?:[^- ]>|[*\]])\s*$|\*$/.test(a.string.slice(0,c))||(!(!b.typeAtEndOfLine||a.column()!=a.indentation())||void 0))}function f(a){for(;;){if(!a||"top"==a.type)return!0;if("}"==a.type&&"namespace"!=a.prev.info)return!1;a=a.prev}}function g(a){for(var b={},c=a.split(" "),d=0;d!?|\/]/;return{startState:function(a){return{tokenize:null,context:new b((a||0)-p,0,"top",null,!1),indented:0,startOfLine:!0,prevToken:null}},token:function(a,b){var g=b.context;if(a.sol()&&(null==g.align&&(g.align=!1),b.indented=a.indentation(),b.startOfLine=!0),a.eatSpace())return m(a,b),null;n=o=null;var h=(b.tokenize||j)(a,b);if("comment"==h||"meta"==h)return h;if(null==g.align&&(g.align=!0),";"==n||":"==n||","==n&&a.match(/^\s*(?:\/\/.*)?$/,!1))for(;"statement"==b.context.type;)d(b);else if("{"==n)c(b,a.column(),"}");else if("["==n)c(b,a.column(),"]");else if("("==n)c(b,a.column(),")");else if("}"==n){for(;"statement"==g.type;)g=d(b);for("}"==g.type&&(g=d(b));"statement"==g.type;)g=d(b)}else n==g.type?d(b):A&&(("}"==g.type||"top"==g.type)&&";"!=n||"statement"==g.type&&"newstatement"==n)&&c(b,a.column(),"statement",a.current());if("variable"==h&&("def"==b.prevToken||i.typeFirstDefinitions&&e(a,b,a.start)&&f(b.context)&&a.match(/^\s*\(/,!1))&&(h="def"),y.token){var k=y.token(a,b,h);void 0!==k&&(h=k)}return"def"==h&&i.styleDefs===!1&&(h="variable"),b.startOfLine=!1,b.prevToken=o?"def":h||n,m(a,b),h},indent:function(b,c){if(b.tokenize!=j&&null!=b.tokenize||b.typeAtEndOfLine)return a.Pass;var d=b.context,e=c&&c.charAt(0);if("statement"==d.type&&"}"==e&&(d=d.prev),i.dontIndentStatements)for(;"statement"==d.type&&i.dontIndentStatements.test(d.info);)d=d.prev;if(y.indent){var f=y.indent(b,d,c);if("number"==typeof f)return f}var g=e==d.type,h=d.prev&&"switch"==d.prev.info;if(i.allmanIndentation&&/[{(]/.test(e)){for(;"top"!=d.type&&"}"!=d.type;)d=d.prev;return d.indented}return"statement"==d.type?d.indented+("{"==e?0:q):!d.align||r&&")"==d.type?")"!=d.type||g?d.indented+(g?0:p)+(g||!h||/^(?:case|default)\b/.test(c)?0:p):d.indented+q:d.column+(g?0:1)},electricInput:B?/^\s*(?:case .*?:|default:|\{\}?|\})$/:/^\s*[{}]$/,blockCommentStart:"/*",blockCommentEnd:"*/",lineComment:"//",fold:"brace"}}));var t="auto if break case register continue return default do sizeof static else struct switch extern typedef union for goto while enum const volatile",u="int long char short double float unsigned signed void size_t ptrdiff_t";p(["text/x-csrc","text/x-c","text/x-chdr"],{name:"clike",keywords:g(t),types:g(u+" bool _Complex _Bool float_t double_t intptr_t intmax_t int8_t int16_t int32_t int64_t uintptr_t uintmax_t uint8_t uint16_t uint32_t uint64_t"),blockKeywords:g("case do else for if switch while struct"),defKeywords:g("struct"),typeFirstDefinitions:!0,atoms:g("null true false"),hooks:{"#":i,"*":j},modeProps:{fold:["brace","include"]}}),p(["text/x-c++src","text/x-c++hdr"],{name:"clike",keywords:g(t+" asm dynamic_cast namespace reinterpret_cast try explicit new static_cast typeid catch operator template typename class friend private this using const_cast inline public throw virtual delete mutable protected alignas alignof constexpr decltype nullptr noexcept thread_local final static_assert override"),types:g(u+" bool wchar_t"),blockKeywords:g("catch class do else finally for if struct switch try while"),defKeywords:g("class namespace struct enum union"),typeFirstDefinitions:!0,atoms:g("true false null"),dontIndentStatements:/^template$/,hooks:{"#":i,"*":j,u:l,U:l,L:l,R:l,0:k,1:k,2:k,3:k,4:k,5:k,6:k,7:k,8:k,9:k,token:function(a,b,c){if("variable"==c&&"("==a.peek()&&(";"==b.prevToken||null==b.prevToken||"}"==b.prevToken)&&m(a.current()))return"def"}},namespaceSeparator:"::",modeProps:{fold:["brace","include"]}}),p("text/x-java",{name:"clike",keywords:g("abstract assert break case catch class const continue default do else enum extends final finally float for goto if implements import instanceof interface native new package private protected public return static strictfp super switch synchronized this throw throws transient try volatile while"),types:g("byte short int long float double boolean char void Boolean Byte Character Double Float Integer Long Number Object Short String StringBuffer StringBuilder Void"),blockKeywords:g("catch class do else finally for if switch try while"),defKeywords:g("class interface package enum"),typeFirstDefinitions:!0,atoms:g("true false null"),number:/^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+\.?\d*|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i,hooks:{"@":function(a){return a.eatWhile(/[\w\$_]/),"meta"}},modeProps:{fold:["brace","import"]}}),p("text/x-csharp",{name:"clike",keywords:g("abstract as async await base break case catch checked class const continue default delegate do else enum event explicit extern finally fixed for foreach goto if implicit in interface internal is lock namespace new operator out override params private protected public readonly ref return sealed sizeof stackalloc static struct switch this throw try typeof unchecked unsafe using virtual void volatile while add alias ascending descending dynamic from get global group into join let orderby partial remove select set value var yield"),types:g("Action Boolean Byte Char DateTime DateTimeOffset Decimal Double Func Guid Int16 Int32 Int64 Object SByte Single String Task TimeSpan UInt16 UInt32 UInt64 bool byte char decimal double short int long object sbyte float string ushort uint ulong"),blockKeywords:g("catch class do else finally for foreach if struct switch try while"),defKeywords:g("class interface namespace struct var"),typeFirstDefinitions:!0,atoms:g("true false null"),hooks:{"@":function(a,b){return a.eat('"')?(b.tokenize=n,n(a,b)):(a.eatWhile(/[\w\$_]/),"meta")}}}),p("text/x-scala",{name:"clike",keywords:g("abstract case catch class def do else extends final finally for forSome if implicit import lazy match new null object override package private protected return sealed super this throw trait try type val var while with yield _ : = => <- <: <% >: # @ assert assume require print println printf readLine readBoolean readByte readShort readChar readInt readLong readFloat readDouble :: #:: "),types:g("AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either Enumeration Equiv Error Exception Fractional Function IndexedSeq Int Integral Iterable Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable Compiler Double Exception Float Integer Long Math Number Object Package Pair Process Runtime Runnable SecurityManager Short StackTraceElement StrictMath String StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"),multiLineStrings:!0,blockKeywords:g("catch class do else finally for forSome if match switch try while"),defKeywords:g("class def object package trait type val var"),atoms:g("true false null"),indentStatements:!1,indentSwitch:!1,hooks:{"@":function(a){return a.eatWhile(/[\w\$_]/),"meta"},'"':function(a,b){return!!a.match('""')&&(b.tokenize=q,b.tokenize(a,b))},"'":function(a){return a.eatWhile(/[\w\$_\xa1-\uffff]/),"atom"},"=":function(a,c){var d=c.context;return!("}"!=d.type||!d.align||!a.eat(">"))&&(c.context=new b(d.indented,d.column,d.type,d.info,null,d.prev),"operator")}},modeProps:{closeBrackets:{triples:'"'}}}),p("text/x-kotlin",{name:"clike",keywords:g("package as typealias class interface this super val var fun for is in This throw return break continue object if else while do try when !in !is as? file import where by get set abstract enum open inner override private public internal protected catch finally out final vararg reified dynamic companion constructor init sealed field property receiver param sparam lateinit data inline noinline tailrec external annotation crossinline const operator infix"),types:g("Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable Compiler Double Exception Float Integer Long Math Number Object Package Pair Process Runtime Runnable SecurityManager Short StackTraceElement StrictMath String StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"),intendSwitch:!1,indentStatements:!1,multiLineStrings:!0,blockKeywords:g("catch class do else finally for if where try while enum"),defKeywords:g("class val var object package interface fun"),atoms:g("true false null this"),hooks:{'"':function(a,b){return b.tokenize=r(a.match('""')),b.tokenize(a,b)}},modeProps:{closeBrackets:{triples:'"'}}}),p(["x-shader/x-vertex","x-shader/x-fragment"],{name:"clike",keywords:g("sampler1D sampler2D sampler3D samplerCube sampler1DShadow sampler2DShadow const attribute uniform varying break continue discard return for while do if else struct in out inout"),types:g("float int bool void vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 mat2 mat3 mat4"),blockKeywords:g("for while do if else struct"),builtin:g("radians degrees sin cos tan asin acos atan pow exp log exp2 sqrt inversesqrt abs sign floor ceil fract mod min max clamp mix step smoothstep length distance dot cross normalize ftransform faceforward reflect refract matrixCompMult lessThan lessThanEqual greaterThan greaterThanEqual equal notEqual any all not texture1D texture1DProj texture1DLod texture1DProjLod texture2D texture2DProj texture2DLod texture2DProjLod texture3D texture3DProj texture3DLod texture3DProjLod textureCube textureCubeLod shadow1D shadow2D shadow1DProj shadow2DProj shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod dFdx dFdy fwidth noise1 noise2 noise3 noise4"),atoms:g("true false gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 gl_FogCoord gl_PointCoord gl_Position gl_PointSize gl_ClipVertex gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor gl_TexCoord gl_FogFragCoord gl_FragCoord gl_FrontFacing gl_FragData gl_FragDepth gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse gl_TexureMatrixTranspose gl_ModelViewMatrixInverseTranspose gl_ProjectionMatrixInverseTranspose gl_ModelViewProjectionMatrixInverseTranspose gl_TextureMatrixInverseTranspose gl_NormalScale gl_DepthRange gl_ClipPlane gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel gl_FrontLightModelProduct gl_BackLightModelProduct gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ gl_FogParameters gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits gl_MaxDrawBuffers"),indentSwitch:!1,hooks:{"#":i},modeProps:{fold:["brace","include"]}}),p("text/x-nesc",{name:"clike",keywords:g(t+"as atomic async call command component components configuration event generic implementation includes interface module new norace nx_struct nx_union post provides signal task uses abstract extends"),types:g(u),blockKeywords:g("case do else for if switch while struct"),atoms:g("null true false"),hooks:{"#":i},modeProps:{fold:["brace","include"]}}),p("text/x-objectivec",{name:"clike",keywords:g(t+"inline restrict _Bool _Complex _Imaginary BOOL Class bycopy byref id IMP in inout nil oneway out Protocol SEL self super atomic nonatomic retain copy readwrite readonly"),types:g(u),atoms:g("YES NO NULL NILL ON OFF true false"),hooks:{"@":function(a){return a.eatWhile(/[\w\$]/),"keyword"},"#":i,indent:function(a,b,c){if("statement"==b.type&&/^@\w/.test(c))return b.indented}},modeProps:{fold:"brace"}}),p("text/x-squirrel",{name:"clike",keywords:g("base break clone continue const default delete enum extends function in class foreach local resume return this throw typeof yield constructor instanceof static"),types:g(u),blockKeywords:g("case catch class else for foreach if switch try while"),defKeywords:g("function local class"),typeFirstDefinitions:!0,atoms:g("true false null"),hooks:{"#":i},modeProps:{fold:["brace","include"]}});var v=null;p("text/x-ceylon",{name:"clike",keywords:g("abstracts alias assembly assert assign break case catch class continue dynamic else exists extends finally for function given if import in interface is let module new nonempty object of out outer package return satisfies super switch then this throw try value void while"),types:function(a){var b=a.charAt(0);return b===b.toUpperCase()&&b!==b.toLowerCase()},blockKeywords:g("case catch class dynamic else finally for function if interface module new object switch try while"),defKeywords:g("class dynamic function interface module object package value"),builtin:g("abstract actual aliased annotation by default deprecated doc final formal late license native optional sealed see serializable shared suppressWarnings tagged throws variable"),isPunctuationChar:/[\[\]{}\(\),;\:\.`]/,isOperatorChar:/[+\-*&%=<>!?|^~:\/]/,numberStart:/[\d#$]/,number:/^(?:#[\da-fA-F_]+|\$[01_]+|[\d_]+[kMGTPmunpf]?|[\d_]+\.[\d_]+(?:[eE][-+]?\d+|[kMGTPmunpf]|)|)/i,multiLineStrings:!0,typeFirstDefinitions:!0,atoms:g("true false null larger smaller equal empty finished"),indentSwitch:!1,styleDefs:!1,hooks:{"@":function(a){return a.eatWhile(/[\w\$_]/),"meta"},'"':function(a,b){return b.tokenize=s(a.match('""')?"triple":"single"),b.tokenize(a,b)},"`":function(a,b){return!(!v||!a.match("`"))&&(b.tokenize=v,v=null,b.tokenize(a,b))},"'":function(a){return a.eatWhile(/[\w\$_\xa1-\uffff]/),"atom"},token:function(a,b,c){if(("variable"==c||"variable-3"==c)&&"."==b.prevToken)return"variable-2"}},modeProps:{fold:["brace","import"],closeBrackets:{triples:'"'}}})})); \ No newline at end of file diff --git a/media/editors/codemirror/mode/css/css.js b/media/editors/codemirror/mode/css/css.js index ea7bd01d84dce..e56e3dd8c6973 100644 --- a/media/editors/codemirror/mode/css/css.js +++ b/media/editors/codemirror/mode/css/css.js @@ -414,7 +414,7 @@ CodeMirror.defineMode("css", function(config, parserConfig) { function keySet(array) { var keys = {}; for (var i = 0; i < array.length; ++i) { - keys[array[i]] = true; + keys[array[i].toLowerCase()] = true; } return keys; } diff --git a/media/editors/codemirror/mode/css/css.min.js b/media/editors/codemirror/mode/css/css.min.js index 2a81f8f90456f..26487b2b917eb 100644 --- a/media/editors/codemirror/mode/css/css.min.js +++ b/media/editors/codemirror/mode/css/css.min.js @@ -1 +1 @@ -!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";function b(a){for(var b={},c=0;c*\/]/.test(c)?d(null,"select-op"):"."==c&&a.match(/^-?[_a-z][_a-z0-9-]*/i)?d("qualifier","qualifier"):/[:;{}\[\]\(\)]/.test(c)?d(null,c):"u"==c&&a.match(/rl(-prefix)?\(/)||"d"==c&&a.match("omain(")||"r"==c&&a.match("egexp(")?(a.backUp(1),b.tokenize=g,d("property","word")):/[\w\\\-]/.test(c)?(a.eatWhile(/[\w\\\-]/),d("property","word")):d(null,null):/[\d.]/.test(a.peek())?(a.eatWhile(/[\w.%]/),d("number","unit")):a.match(/^-[\w\\\-]+/)?(a.eatWhile(/[\w\\\-]/),a.match(/^\s*:/,!1)?d("variable-2","variable-definition"):d("variable-2","variable")):a.match(/^\w+-/)?d("meta","meta"):void 0}function f(a){return function(b,c){for(var e,f=!1;null!=(e=b.next());){if(e==a&&!f){")"==a&&b.backUp(1);break}f=!f&&"\\"==e}return(e==a||!f&&")"!=a)&&(c.tokenize=null),d("string","string")}}function g(a,b){return a.next(),a.match(/\s*[\"\')]/,!1)?b.tokenize=null:b.tokenize=f(")"),d(null,"(")}function h(a,b,c){this.type=a,this.indent=b,this.prev=c}function i(a,b,c,d){return a.context=new h(c,b.indentation()+(d===!1?0:q),a.context),c}function j(a){return a.context.prev&&(a.context=a.context.prev),a.context.type}function k(a,b,c){return E[c.context.type](a,b,c)}function l(a,b,c,d){for(var e=d||1;e>0;e--)c.context=c.context.prev;return k(a,b,c)}function m(a){var b=a.current().toLowerCase();p=B.hasOwnProperty(b)?"atom":A.hasOwnProperty(b)?"keyword":"variable"}var n=c.inline;c.propertyKeywords||(c=a.resolveMode("text/css"));var o,p,q=b.indentUnit,r=c.tokenHooks,s=c.documentTypes||{},t=c.mediaTypes||{},u=c.mediaFeatures||{},v=c.mediaValueKeywords||{},w=c.propertyKeywords||{},x=c.nonStandardPropertyKeywords||{},y=c.fontProperties||{},z=c.counterDescriptors||{},A=c.colorKeywords||{},B=c.valueKeywords||{},C=c.allowNested,D=c.supportsAtComponent===!0,E={};return E.top=function(a,b,c){if("{"==a)return i(c,b,"block");if("}"==a&&c.context.prev)return j(c);if(D&&/@component/.test(a))return i(c,b,"atComponentBlock");if(/^@(-moz-)?document$/.test(a))return i(c,b,"documentTypes");if(/^@(media|supports|(-moz-)?document|import)$/.test(a))return i(c,b,"atBlock");if(/^@(font-face|counter-style)/.test(a))return c.stateArg=a,"restricted_atBlock_before";if(/^@(-(moz|ms|o|webkit)-)?keyframes$/.test(a))return"keyframes";if(a&&"@"==a.charAt(0))return i(c,b,"at");if("hash"==a)p="builtin";else if("word"==a)p="tag";else{if("variable-definition"==a)return"maybeprop";if("interpolation"==a)return i(c,b,"interpolation");if(":"==a)return"pseudo";if(C&&"("==a)return i(c,b,"parens")}return c.context.type},E.block=function(a,b,c){if("word"==a){var d=b.current().toLowerCase();return w.hasOwnProperty(d)?(p="property","maybeprop"):x.hasOwnProperty(d)?(p="string-2","maybeprop"):C?(p=b.match(/^\s*:(?:\s|$)/,!1)?"property":"tag","block"):(p+=" error","maybeprop")}return"meta"==a?"block":C||"hash"!=a&&"qualifier"!=a?E.top(a,b,c):(p="error","block")},E.maybeprop=function(a,b,c){return":"==a?i(c,b,"prop"):k(a,b,c)},E.prop=function(a,b,c){if(";"==a)return j(c);if("{"==a&&C)return i(c,b,"propBlock");if("}"==a||"{"==a)return l(a,b,c);if("("==a)return i(c,b,"parens");if("hash"!=a||/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(b.current())){if("word"==a)m(b);else if("interpolation"==a)return i(c,b,"interpolation")}else p+=" error";return"prop"},E.propBlock=function(a,b,c){return"}"==a?j(c):"word"==a?(p="property","maybeprop"):c.context.type},E.parens=function(a,b,c){return"{"==a||"}"==a?l(a,b,c):")"==a?j(c):"("==a?i(c,b,"parens"):"interpolation"==a?i(c,b,"interpolation"):("word"==a&&m(b),"parens")},E.pseudo=function(a,b,c){return"word"==a?(p="variable-3",c.context.type):k(a,b,c)},E.documentTypes=function(a,b,c){return"word"==a&&s.hasOwnProperty(b.current())?(p="tag",c.context.type):E.atBlock(a,b,c)},E.atBlock=function(a,b,c){if("("==a)return i(c,b,"atBlock_parens");if("}"==a||";"==a)return l(a,b,c);if("{"==a)return j(c)&&i(c,b,C?"block":"top");if("interpolation"==a)return i(c,b,"interpolation");if("word"==a){var d=b.current().toLowerCase();p="only"==d||"not"==d||"and"==d||"or"==d?"keyword":t.hasOwnProperty(d)?"attribute":u.hasOwnProperty(d)?"property":v.hasOwnProperty(d)?"keyword":w.hasOwnProperty(d)?"property":x.hasOwnProperty(d)?"string-2":B.hasOwnProperty(d)?"atom":A.hasOwnProperty(d)?"keyword":"error"}return c.context.type},E.atComponentBlock=function(a,b,c){return"}"==a?l(a,b,c):"{"==a?j(c)&&i(c,b,C?"block":"top",!1):("word"==a&&(p="error"),c.context.type)},E.atBlock_parens=function(a,b,c){return")"==a?j(c):"{"==a||"}"==a?l(a,b,c,2):E.atBlock(a,b,c)},E.restricted_atBlock_before=function(a,b,c){return"{"==a?i(c,b,"restricted_atBlock"):"word"==a&&"@counter-style"==c.stateArg?(p="variable","restricted_atBlock_before"):k(a,b,c)},E.restricted_atBlock=function(a,b,c){return"}"==a?(c.stateArg=null,j(c)):"word"==a?(p="@font-face"==c.stateArg&&!y.hasOwnProperty(b.current().toLowerCase())||"@counter-style"==c.stateArg&&!z.hasOwnProperty(b.current().toLowerCase())?"error":"property","maybeprop"):"restricted_atBlock"},E.keyframes=function(a,b,c){return"word"==a?(p="variable","keyframes"):"{"==a?i(c,b,"top"):k(a,b,c)},E.at=function(a,b,c){return";"==a?j(c):"{"==a||"}"==a?l(a,b,c):("word"==a?p="tag":"hash"==a&&(p="builtin"),"at")},E.interpolation=function(a,b,c){return"}"==a?j(c):"{"==a||";"==a?l(a,b,c):("word"==a?p="variable":"variable"!=a&&"("!=a&&")"!=a&&(p="error"),"interpolation")},{startState:function(a){return{tokenize:null,state:n?"block":"top",stateArg:null,context:new h(n?"block":"top",a||0,null)}},token:function(a,b){if(!b.tokenize&&a.eatSpace())return null;var c=(b.tokenize||e)(a,b);return c&&"object"==typeof c&&(o=c[1],c=c[0]),p=c,b.state=E[b.state](o,a,b),p},indent:function(a,b){var c=a.context,d=b&&b.charAt(0),e=c.indent;return"prop"!=c.type||"}"!=d&&")"!=d||(c=c.prev),c.prev&&("}"!=d||"block"!=c.type&&"top"!=c.type&&"interpolation"!=c.type&&"restricted_atBlock"!=c.type?(")"!=d||"parens"!=c.type&&"atBlock_parens"!=c.type)&&("{"!=d||"at"!=c.type&&"atBlock"!=c.type)||(e=Math.max(0,c.indent-q),c=c.prev):(c=c.prev,e=c.indent)),e},electricChars:"}",blockCommentStart:"/*",blockCommentEnd:"*/",fold:"brace"}}));var d=["domain","regexp","url","url-prefix"],e=b(d),f=["all","aural","braille","handheld","print","projection","screen","tty","tv","embossed"],g=b(f),h=["width","min-width","max-width","height","min-height","max-height","device-width","min-device-width","max-device-width","device-height","min-device-height","max-device-height","aspect-ratio","min-aspect-ratio","max-aspect-ratio","device-aspect-ratio","min-device-aspect-ratio","max-device-aspect-ratio","color","min-color","max-color","color-index","min-color-index","max-color-index","monochrome","min-monochrome","max-monochrome","resolution","min-resolution","max-resolution","scan","grid","orientation","device-pixel-ratio","min-device-pixel-ratio","max-device-pixel-ratio","pointer","any-pointer","hover","any-hover"],i=b(h),j=["landscape","portrait","none","coarse","fine","on-demand","hover","interlace","progressive"],k=b(j),l=["align-content","align-items","align-self","alignment-adjust","alignment-baseline","anchor-point","animation","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-timing-function","appearance","azimuth","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-repeat","background-size","baseline-shift","binding","bleed","bookmark-label","bookmark-level","bookmark-state","bookmark-target","border","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-decoration-break","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","clear","clip","color","color-profile","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","content","counter-increment","counter-reset","crop","cue","cue-after","cue-before","cursor","direction","display","dominant-baseline","drop-initial-after-adjust","drop-initial-after-align","drop-initial-before-adjust","drop-initial-before-align","drop-initial-size","drop-initial-value","elevation","empty-cells","fit","fit-position","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","float-offset","flow-from","flow-into","font","font-feature-settings","font-family","font-kerning","font-language-override","font-size","font-size-adjust","font-stretch","font-style","font-synthesis","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-ligatures","font-variant-numeric","font-variant-position","font-weight","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-gap","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-gap","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphens","icon","image-orientation","image-rendering","image-resolution","inline-box-align","justify-content","left","letter-spacing","line-break","line-height","line-stacking","line-stacking-ruby","line-stacking-shift","line-stacking-strategy","list-style","list-style-image","list-style-position","list-style-type","margin","margin-bottom","margin-left","margin-right","margin-top","marker-offset","marks","marquee-direction","marquee-loop","marquee-play-count","marquee-speed","marquee-style","max-height","max-width","min-height","min-width","move-to","nav-down","nav-index","nav-left","nav-right","nav-up","object-fit","object-position","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-style","overflow-wrap","overflow-x","overflow-y","padding","padding-bottom","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","page-policy","pause","pause-after","pause-before","perspective","perspective-origin","pitch","pitch-range","play-during","position","presentation-level","punctuation-trim","quotes","region-break-after","region-break-before","region-break-inside","region-fragment","rendering-intent","resize","rest","rest-after","rest-before","richness","right","rotation","rotation-point","ruby-align","ruby-overhang","ruby-position","ruby-span","shape-image-threshold","shape-inside","shape-margin","shape-outside","size","speak","speak-as","speak-header","speak-numeral","speak-punctuation","speech-rate","stress","string-set","tab-size","table-layout","target","target-name","target-new","target-position","text-align","text-align-last","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-style","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-height","text-indent","text-justify","text-outline","text-overflow","text-shadow","text-size-adjust","text-space-collapse","text-transform","text-underline-position","text-wrap","top","transform","transform-origin","transform-style","transition","transition-delay","transition-duration","transition-property","transition-timing-function","unicode-bidi","vertical-align","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","volume","white-space","widows","width","word-break","word-spacing","word-wrap","z-index","clip-path","clip-rule","mask","enable-background","filter","flood-color","flood-opacity","lighting-color","stop-color","stop-opacity","pointer-events","color-interpolation","color-interpolation-filters","color-rendering","fill","fill-opacity","fill-rule","image-rendering","marker","marker-end","marker-mid","marker-start","shape-rendering","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","text-rendering","baseline-shift","dominant-baseline","glyph-orientation-horizontal","glyph-orientation-vertical","text-anchor","writing-mode"],m=b(l),n=["scrollbar-arrow-color","scrollbar-base-color","scrollbar-dark-shadow-color","scrollbar-face-color","scrollbar-highlight-color","scrollbar-shadow-color","scrollbar-3d-light-color","scrollbar-track-color","shape-inside","searchfield-cancel-button","searchfield-decoration","searchfield-results-button","searchfield-results-decoration","zoom"],o=b(n),p=["font-family","src","unicode-range","font-variant","font-feature-settings","font-stretch","font-weight","font-style"],q=b(p),r=["additive-symbols","fallback","negative","pad","prefix","range","speak-as","suffix","symbols","system"],s=b(r),t=["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","grey","green","greenyellow","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"],u=b(t),v=["above","absolute","activeborder","additive","activecaption","afar","after-white-space","ahead","alias","all","all-scroll","alphabetic","alternate","always","amharic","amharic-abegede","antialiased","appworkspace","arabic-indic","armenian","asterisks","attr","auto","avoid","avoid-column","avoid-page","avoid-region","background","backwards","baseline","below","bidi-override","binary","bengali","blink","block","block-axis","bold","bolder","border","border-box","both","bottom","break","break-all","break-word","bullets","button","button-bevel","buttonface","buttonhighlight","buttonshadow","buttontext","calc","cambodian","capitalize","caps-lock-indicator","caption","captiontext","caret","cell","center","checkbox","circle","cjk-decimal","cjk-earthly-branch","cjk-heavenly-stem","cjk-ideographic","clear","clip","close-quote","col-resize","collapse","color","color-burn","color-dodge","column","column-reverse","compact","condensed","contain","content","content-box","context-menu","continuous","copy","counter","counters","cover","crop","cross","crosshair","currentcolor","cursive","cyclic","darken","dashed","decimal","decimal-leading-zero","default","default-button","dense","destination-atop","destination-in","destination-out","destination-over","devanagari","difference","disc","discard","disclosure-closed","disclosure-open","document","dot-dash","dot-dot-dash","dotted","double","down","e-resize","ease","ease-in","ease-in-out","ease-out","element","ellipse","ellipsis","embed","end","ethiopic","ethiopic-abegede","ethiopic-abegede-am-et","ethiopic-abegede-gez","ethiopic-abegede-ti-er","ethiopic-abegede-ti-et","ethiopic-halehame-aa-er","ethiopic-halehame-aa-et","ethiopic-halehame-am-et","ethiopic-halehame-gez","ethiopic-halehame-om-et","ethiopic-halehame-sid-et","ethiopic-halehame-so-et","ethiopic-halehame-ti-er","ethiopic-halehame-ti-et","ethiopic-halehame-tig","ethiopic-numeric","ew-resize","exclusion","expanded","extends","extra-condensed","extra-expanded","fantasy","fast","fill","fixed","flat","flex","flex-end","flex-start","footnotes","forwards","from","geometricPrecision","georgian","graytext","grid","groove","gujarati","gurmukhi","hand","hangul","hangul-consonant","hard-light","hebrew","help","hidden","hide","higher","highlight","highlighttext","hiragana","hiragana-iroha","horizontal","hsl","hsla","hue","icon","ignore","inactiveborder","inactivecaption","inactivecaptiontext","infinite","infobackground","infotext","inherit","initial","inline","inline-axis","inline-block","inline-flex","inline-grid","inline-table","inset","inside","intrinsic","invert","italic","japanese-formal","japanese-informal","justify","kannada","katakana","katakana-iroha","keep-all","khmer","korean-hangul-formal","korean-hanja-formal","korean-hanja-informal","landscape","lao","large","larger","left","level","lighter","lighten","line-through","linear","linear-gradient","lines","list-item","listbox","listitem","local","logical","loud","lower","lower-alpha","lower-armenian","lower-greek","lower-hexadecimal","lower-latin","lower-norwegian","lower-roman","lowercase","ltr","luminosity","malayalam","match","matrix","matrix3d","media-controls-background","media-current-time-display","media-fullscreen-button","media-mute-button","media-play-button","media-return-to-realtime-button","media-rewind-button","media-seek-back-button","media-seek-forward-button","media-slider","media-sliderthumb","media-time-remaining-display","media-volume-slider","media-volume-slider-container","media-volume-sliderthumb","medium","menu","menulist","menulist-button","menulist-text","menulist-textfield","menutext","message-box","middle","min-intrinsic","mix","mongolian","monospace","move","multiple","multiply","myanmar","n-resize","narrower","ne-resize","nesw-resize","no-close-quote","no-drop","no-open-quote","no-repeat","none","normal","not-allowed","nowrap","ns-resize","numbers","numeric","nw-resize","nwse-resize","oblique","octal","open-quote","optimizeLegibility","optimizeSpeed","oriya","oromo","outset","outside","outside-shape","overlay","overline","padding","padding-box","painted","page","paused","persian","perspective","plus-darker","plus-lighter","pointer","polygon","portrait","pre","pre-line","pre-wrap","preserve-3d","progress","push-button","radial-gradient","radio","read-only","read-write","read-write-plaintext-only","rectangle","region","relative","repeat","repeating-linear-gradient","repeating-radial-gradient","repeat-x","repeat-y","reset","reverse","rgb","rgba","ridge","right","rotate","rotate3d","rotateX","rotateY","rotateZ","round","row","row-resize","row-reverse","rtl","run-in","running","s-resize","sans-serif","saturation","scale","scale3d","scaleX","scaleY","scaleZ","screen","scroll","scrollbar","se-resize","searchfield","searchfield-cancel-button","searchfield-decoration","searchfield-results-button","searchfield-results-decoration","semi-condensed","semi-expanded","separate","serif","show","sidama","simp-chinese-formal","simp-chinese-informal","single","skew","skewX","skewY","skip-white-space","slide","slider-horizontal","slider-vertical","sliderthumb-horizontal","sliderthumb-vertical","slow","small","small-caps","small-caption","smaller","soft-light","solid","somali","source-atop","source-in","source-out","source-over","space","space-around","space-between","spell-out","square","square-button","start","static","status-bar","stretch","stroke","sub","subpixel-antialiased","super","sw-resize","symbolic","symbols","table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","tamil","telugu","text","text-bottom","text-top","textarea","textfield","thai","thick","thin","threeddarkshadow","threedface","threedhighlight","threedlightshadow","threedshadow","tibetan","tigre","tigrinya-er","tigrinya-er-abegede","tigrinya-et","tigrinya-et-abegede","to","top","trad-chinese-formal","trad-chinese-informal","translate","translate3d","translateX","translateY","translateZ","transparent","ultra-condensed","ultra-expanded","underline","up","upper-alpha","upper-armenian","upper-greek","upper-hexadecimal","upper-latin","upper-norwegian","upper-roman","uppercase","urdu","url","var","vertical","vertical-text","visible","visibleFill","visiblePainted","visibleStroke","visual","w-resize","wait","wave","wider","window","windowframe","windowtext","words","wrap","wrap-reverse","x-large","x-small","xor","xx-large","xx-small"],w=b(v),x=d.concat(f).concat(h).concat(j).concat(l).concat(n).concat(t).concat(v);a.registerHelper("hintWords","css",x),a.defineMIME("text/css",{documentTypes:e,mediaTypes:g,mediaFeatures:i,mediaValueKeywords:k,propertyKeywords:m,nonStandardPropertyKeywords:o,fontProperties:q,counterDescriptors:s,colorKeywords:u,valueKeywords:w,tokenHooks:{"/":function(a,b){return!!a.eat("*")&&(b.tokenize=c,c(a,b))}},name:"css"}),a.defineMIME("text/x-scss",{mediaTypes:g,mediaFeatures:i,mediaValueKeywords:k,propertyKeywords:m,nonStandardPropertyKeywords:o,colorKeywords:u,valueKeywords:w,fontProperties:q,allowNested:!0,tokenHooks:{"/":function(a,b){return a.eat("/")?(a.skipToEnd(),["comment","comment"]):a.eat("*")?(b.tokenize=c,c(a,b)):["operator","operator"]},":":function(a){return!!a.match(/\s*\{/)&&[null,"{"]},$:function(a){return a.match(/^[\w-]+/),a.match(/^\s*:/,!1)?["variable-2","variable-definition"]:["variable-2","variable"]},"#":function(a){return!!a.eat("{")&&[null,"interpolation"]}},name:"css",helperType:"scss"}),a.defineMIME("text/x-less",{mediaTypes:g,mediaFeatures:i,mediaValueKeywords:k,propertyKeywords:m,nonStandardPropertyKeywords:o,colorKeywords:u,valueKeywords:w,fontProperties:q,allowNested:!0,tokenHooks:{"/":function(a,b){return a.eat("/")?(a.skipToEnd(),["comment","comment"]):a.eat("*")?(b.tokenize=c,c(a,b)):["operator","operator"]},"@":function(a){return a.eat("{")?[null,"interpolation"]:!a.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/,!1)&&(a.eatWhile(/[\w\\\-]/),a.match(/^\s*:/,!1)?["variable-2","variable-definition"]:["variable-2","variable"])},"&":function(){return["atom","atom"]}},name:"css",helperType:"less"}),a.defineMIME("text/x-gss",{documentTypes:e,mediaTypes:g,mediaFeatures:i,propertyKeywords:m,nonStandardPropertyKeywords:o,fontProperties:q,counterDescriptors:s,colorKeywords:u,valueKeywords:w,supportsAtComponent:!0,tokenHooks:{"/":function(a,b){return!!a.eat("*")&&(b.tokenize=c,c(a,b))}},name:"css",helperType:"gss"})})); \ No newline at end of file +!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";function b(a){for(var b={},c=0;c*\/]/.test(c)?d(null,"select-op"):"."==c&&a.match(/^-?[_a-z][_a-z0-9-]*/i)?d("qualifier","qualifier"):/[:;{}\[\]\(\)]/.test(c)?d(null,c):"u"==c&&a.match(/rl(-prefix)?\(/)||"d"==c&&a.match("omain(")||"r"==c&&a.match("egexp(")?(a.backUp(1),b.tokenize=g,d("property","word")):/[\w\\\-]/.test(c)?(a.eatWhile(/[\w\\\-]/),d("property","word")):d(null,null):/[\d.]/.test(a.peek())?(a.eatWhile(/[\w.%]/),d("number","unit")):a.match(/^-[\w\\\-]+/)?(a.eatWhile(/[\w\\\-]/),a.match(/^\s*:/,!1)?d("variable-2","variable-definition"):d("variable-2","variable")):a.match(/^\w+-/)?d("meta","meta"):void 0}function f(a){return function(b,c){for(var e,f=!1;null!=(e=b.next());){if(e==a&&!f){")"==a&&b.backUp(1);break}f=!f&&"\\"==e}return(e==a||!f&&")"!=a)&&(c.tokenize=null),d("string","string")}}function g(a,b){return a.next(),a.match(/\s*[\"\')]/,!1)?b.tokenize=null:b.tokenize=f(")"),d(null,"(")}function h(a,b,c){this.type=a,this.indent=b,this.prev=c}function i(a,b,c,d){return a.context=new h(c,b.indentation()+(d===!1?0:q),a.context),c}function j(a){return a.context.prev&&(a.context=a.context.prev),a.context.type}function k(a,b,c){return E[c.context.type](a,b,c)}function l(a,b,c,d){for(var e=d||1;e>0;e--)c.context=c.context.prev;return k(a,b,c)}function m(a){var b=a.current().toLowerCase();p=B.hasOwnProperty(b)?"atom":A.hasOwnProperty(b)?"keyword":"variable"}var n=c.inline;c.propertyKeywords||(c=a.resolveMode("text/css"));var o,p,q=b.indentUnit,r=c.tokenHooks,s=c.documentTypes||{},t=c.mediaTypes||{},u=c.mediaFeatures||{},v=c.mediaValueKeywords||{},w=c.propertyKeywords||{},x=c.nonStandardPropertyKeywords||{},y=c.fontProperties||{},z=c.counterDescriptors||{},A=c.colorKeywords||{},B=c.valueKeywords||{},C=c.allowNested,D=c.supportsAtComponent===!0,E={};return E.top=function(a,b,c){if("{"==a)return i(c,b,"block");if("}"==a&&c.context.prev)return j(c);if(D&&/@component/.test(a))return i(c,b,"atComponentBlock");if(/^@(-moz-)?document$/.test(a))return i(c,b,"documentTypes");if(/^@(media|supports|(-moz-)?document|import)$/.test(a))return i(c,b,"atBlock");if(/^@(font-face|counter-style)/.test(a))return c.stateArg=a,"restricted_atBlock_before";if(/^@(-(moz|ms|o|webkit)-)?keyframes$/.test(a))return"keyframes";if(a&&"@"==a.charAt(0))return i(c,b,"at");if("hash"==a)p="builtin";else if("word"==a)p="tag";else{if("variable-definition"==a)return"maybeprop";if("interpolation"==a)return i(c,b,"interpolation");if(":"==a)return"pseudo";if(C&&"("==a)return i(c,b,"parens")}return c.context.type},E.block=function(a,b,c){if("word"==a){var d=b.current().toLowerCase();return w.hasOwnProperty(d)?(p="property","maybeprop"):x.hasOwnProperty(d)?(p="string-2","maybeprop"):C?(p=b.match(/^\s*:(?:\s|$)/,!1)?"property":"tag","block"):(p+=" error","maybeprop")}return"meta"==a?"block":C||"hash"!=a&&"qualifier"!=a?E.top(a,b,c):(p="error","block")},E.maybeprop=function(a,b,c){return":"==a?i(c,b,"prop"):k(a,b,c)},E.prop=function(a,b,c){if(";"==a)return j(c);if("{"==a&&C)return i(c,b,"propBlock");if("}"==a||"{"==a)return l(a,b,c);if("("==a)return i(c,b,"parens");if("hash"!=a||/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(b.current())){if("word"==a)m(b);else if("interpolation"==a)return i(c,b,"interpolation")}else p+=" error";return"prop"},E.propBlock=function(a,b,c){return"}"==a?j(c):"word"==a?(p="property","maybeprop"):c.context.type},E.parens=function(a,b,c){return"{"==a||"}"==a?l(a,b,c):")"==a?j(c):"("==a?i(c,b,"parens"):"interpolation"==a?i(c,b,"interpolation"):("word"==a&&m(b),"parens")},E.pseudo=function(a,b,c){return"word"==a?(p="variable-3",c.context.type):k(a,b,c)},E.documentTypes=function(a,b,c){return"word"==a&&s.hasOwnProperty(b.current())?(p="tag",c.context.type):E.atBlock(a,b,c)},E.atBlock=function(a,b,c){if("("==a)return i(c,b,"atBlock_parens");if("}"==a||";"==a)return l(a,b,c);if("{"==a)return j(c)&&i(c,b,C?"block":"top");if("interpolation"==a)return i(c,b,"interpolation");if("word"==a){var d=b.current().toLowerCase();p="only"==d||"not"==d||"and"==d||"or"==d?"keyword":t.hasOwnProperty(d)?"attribute":u.hasOwnProperty(d)?"property":v.hasOwnProperty(d)?"keyword":w.hasOwnProperty(d)?"property":x.hasOwnProperty(d)?"string-2":B.hasOwnProperty(d)?"atom":A.hasOwnProperty(d)?"keyword":"error"}return c.context.type},E.atComponentBlock=function(a,b,c){return"}"==a?l(a,b,c):"{"==a?j(c)&&i(c,b,C?"block":"top",!1):("word"==a&&(p="error"),c.context.type)},E.atBlock_parens=function(a,b,c){return")"==a?j(c):"{"==a||"}"==a?l(a,b,c,2):E.atBlock(a,b,c)},E.restricted_atBlock_before=function(a,b,c){return"{"==a?i(c,b,"restricted_atBlock"):"word"==a&&"@counter-style"==c.stateArg?(p="variable","restricted_atBlock_before"):k(a,b,c)},E.restricted_atBlock=function(a,b,c){return"}"==a?(c.stateArg=null,j(c)):"word"==a?(p="@font-face"==c.stateArg&&!y.hasOwnProperty(b.current().toLowerCase())||"@counter-style"==c.stateArg&&!z.hasOwnProperty(b.current().toLowerCase())?"error":"property","maybeprop"):"restricted_atBlock"},E.keyframes=function(a,b,c){return"word"==a?(p="variable","keyframes"):"{"==a?i(c,b,"top"):k(a,b,c)},E.at=function(a,b,c){return";"==a?j(c):"{"==a||"}"==a?l(a,b,c):("word"==a?p="tag":"hash"==a&&(p="builtin"),"at")},E.interpolation=function(a,b,c){return"}"==a?j(c):"{"==a||";"==a?l(a,b,c):("word"==a?p="variable":"variable"!=a&&"("!=a&&")"!=a&&(p="error"),"interpolation")},{startState:function(a){return{tokenize:null,state:n?"block":"top",stateArg:null,context:new h(n?"block":"top",a||0,null)}},token:function(a,b){if(!b.tokenize&&a.eatSpace())return null;var c=(b.tokenize||e)(a,b);return c&&"object"==typeof c&&(o=c[1],c=c[0]),p=c,b.state=E[b.state](o,a,b),p},indent:function(a,b){var c=a.context,d=b&&b.charAt(0),e=c.indent;return"prop"!=c.type||"}"!=d&&")"!=d||(c=c.prev),c.prev&&("}"!=d||"block"!=c.type&&"top"!=c.type&&"interpolation"!=c.type&&"restricted_atBlock"!=c.type?(")"!=d||"parens"!=c.type&&"atBlock_parens"!=c.type)&&("{"!=d||"at"!=c.type&&"atBlock"!=c.type)||(e=Math.max(0,c.indent-q),c=c.prev):(c=c.prev,e=c.indent)),e},electricChars:"}",blockCommentStart:"/*",blockCommentEnd:"*/",fold:"brace"}}));var d=["domain","regexp","url","url-prefix"],e=b(d),f=["all","aural","braille","handheld","print","projection","screen","tty","tv","embossed"],g=b(f),h=["width","min-width","max-width","height","min-height","max-height","device-width","min-device-width","max-device-width","device-height","min-device-height","max-device-height","aspect-ratio","min-aspect-ratio","max-aspect-ratio","device-aspect-ratio","min-device-aspect-ratio","max-device-aspect-ratio","color","min-color","max-color","color-index","min-color-index","max-color-index","monochrome","min-monochrome","max-monochrome","resolution","min-resolution","max-resolution","scan","grid","orientation","device-pixel-ratio","min-device-pixel-ratio","max-device-pixel-ratio","pointer","any-pointer","hover","any-hover"],i=b(h),j=["landscape","portrait","none","coarse","fine","on-demand","hover","interlace","progressive"],k=b(j),l=["align-content","align-items","align-self","alignment-adjust","alignment-baseline","anchor-point","animation","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-timing-function","appearance","azimuth","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-repeat","background-size","baseline-shift","binding","bleed","bookmark-label","bookmark-level","bookmark-state","bookmark-target","border","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-decoration-break","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","clear","clip","color","color-profile","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","content","counter-increment","counter-reset","crop","cue","cue-after","cue-before","cursor","direction","display","dominant-baseline","drop-initial-after-adjust","drop-initial-after-align","drop-initial-before-adjust","drop-initial-before-align","drop-initial-size","drop-initial-value","elevation","empty-cells","fit","fit-position","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","float-offset","flow-from","flow-into","font","font-feature-settings","font-family","font-kerning","font-language-override","font-size","font-size-adjust","font-stretch","font-style","font-synthesis","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-ligatures","font-variant-numeric","font-variant-position","font-weight","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-gap","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-gap","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphens","icon","image-orientation","image-rendering","image-resolution","inline-box-align","justify-content","left","letter-spacing","line-break","line-height","line-stacking","line-stacking-ruby","line-stacking-shift","line-stacking-strategy","list-style","list-style-image","list-style-position","list-style-type","margin","margin-bottom","margin-left","margin-right","margin-top","marker-offset","marks","marquee-direction","marquee-loop","marquee-play-count","marquee-speed","marquee-style","max-height","max-width","min-height","min-width","move-to","nav-down","nav-index","nav-left","nav-right","nav-up","object-fit","object-position","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-style","overflow-wrap","overflow-x","overflow-y","padding","padding-bottom","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","page-policy","pause","pause-after","pause-before","perspective","perspective-origin","pitch","pitch-range","play-during","position","presentation-level","punctuation-trim","quotes","region-break-after","region-break-before","region-break-inside","region-fragment","rendering-intent","resize","rest","rest-after","rest-before","richness","right","rotation","rotation-point","ruby-align","ruby-overhang","ruby-position","ruby-span","shape-image-threshold","shape-inside","shape-margin","shape-outside","size","speak","speak-as","speak-header","speak-numeral","speak-punctuation","speech-rate","stress","string-set","tab-size","table-layout","target","target-name","target-new","target-position","text-align","text-align-last","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-style","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-height","text-indent","text-justify","text-outline","text-overflow","text-shadow","text-size-adjust","text-space-collapse","text-transform","text-underline-position","text-wrap","top","transform","transform-origin","transform-style","transition","transition-delay","transition-duration","transition-property","transition-timing-function","unicode-bidi","vertical-align","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","volume","white-space","widows","width","word-break","word-spacing","word-wrap","z-index","clip-path","clip-rule","mask","enable-background","filter","flood-color","flood-opacity","lighting-color","stop-color","stop-opacity","pointer-events","color-interpolation","color-interpolation-filters","color-rendering","fill","fill-opacity","fill-rule","image-rendering","marker","marker-end","marker-mid","marker-start","shape-rendering","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","text-rendering","baseline-shift","dominant-baseline","glyph-orientation-horizontal","glyph-orientation-vertical","text-anchor","writing-mode"],m=b(l),n=["scrollbar-arrow-color","scrollbar-base-color","scrollbar-dark-shadow-color","scrollbar-face-color","scrollbar-highlight-color","scrollbar-shadow-color","scrollbar-3d-light-color","scrollbar-track-color","shape-inside","searchfield-cancel-button","searchfield-decoration","searchfield-results-button","searchfield-results-decoration","zoom"],o=b(n),p=["font-family","src","unicode-range","font-variant","font-feature-settings","font-stretch","font-weight","font-style"],q=b(p),r=["additive-symbols","fallback","negative","pad","prefix","range","speak-as","suffix","symbols","system"],s=b(r),t=["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","grey","green","greenyellow","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"],u=b(t),v=["above","absolute","activeborder","additive","activecaption","afar","after-white-space","ahead","alias","all","all-scroll","alphabetic","alternate","always","amharic","amharic-abegede","antialiased","appworkspace","arabic-indic","armenian","asterisks","attr","auto","avoid","avoid-column","avoid-page","avoid-region","background","backwards","baseline","below","bidi-override","binary","bengali","blink","block","block-axis","bold","bolder","border","border-box","both","bottom","break","break-all","break-word","bullets","button","button-bevel","buttonface","buttonhighlight","buttonshadow","buttontext","calc","cambodian","capitalize","caps-lock-indicator","caption","captiontext","caret","cell","center","checkbox","circle","cjk-decimal","cjk-earthly-branch","cjk-heavenly-stem","cjk-ideographic","clear","clip","close-quote","col-resize","collapse","color","color-burn","color-dodge","column","column-reverse","compact","condensed","contain","content","content-box","context-menu","continuous","copy","counter","counters","cover","crop","cross","crosshair","currentcolor","cursive","cyclic","darken","dashed","decimal","decimal-leading-zero","default","default-button","dense","destination-atop","destination-in","destination-out","destination-over","devanagari","difference","disc","discard","disclosure-closed","disclosure-open","document","dot-dash","dot-dot-dash","dotted","double","down","e-resize","ease","ease-in","ease-in-out","ease-out","element","ellipse","ellipsis","embed","end","ethiopic","ethiopic-abegede","ethiopic-abegede-am-et","ethiopic-abegede-gez","ethiopic-abegede-ti-er","ethiopic-abegede-ti-et","ethiopic-halehame-aa-er","ethiopic-halehame-aa-et","ethiopic-halehame-am-et","ethiopic-halehame-gez","ethiopic-halehame-om-et","ethiopic-halehame-sid-et","ethiopic-halehame-so-et","ethiopic-halehame-ti-er","ethiopic-halehame-ti-et","ethiopic-halehame-tig","ethiopic-numeric","ew-resize","exclusion","expanded","extends","extra-condensed","extra-expanded","fantasy","fast","fill","fixed","flat","flex","flex-end","flex-start","footnotes","forwards","from","geometricPrecision","georgian","graytext","grid","groove","gujarati","gurmukhi","hand","hangul","hangul-consonant","hard-light","hebrew","help","hidden","hide","higher","highlight","highlighttext","hiragana","hiragana-iroha","horizontal","hsl","hsla","hue","icon","ignore","inactiveborder","inactivecaption","inactivecaptiontext","infinite","infobackground","infotext","inherit","initial","inline","inline-axis","inline-block","inline-flex","inline-grid","inline-table","inset","inside","intrinsic","invert","italic","japanese-formal","japanese-informal","justify","kannada","katakana","katakana-iroha","keep-all","khmer","korean-hangul-formal","korean-hanja-formal","korean-hanja-informal","landscape","lao","large","larger","left","level","lighter","lighten","line-through","linear","linear-gradient","lines","list-item","listbox","listitem","local","logical","loud","lower","lower-alpha","lower-armenian","lower-greek","lower-hexadecimal","lower-latin","lower-norwegian","lower-roman","lowercase","ltr","luminosity","malayalam","match","matrix","matrix3d","media-controls-background","media-current-time-display","media-fullscreen-button","media-mute-button","media-play-button","media-return-to-realtime-button","media-rewind-button","media-seek-back-button","media-seek-forward-button","media-slider","media-sliderthumb","media-time-remaining-display","media-volume-slider","media-volume-slider-container","media-volume-sliderthumb","medium","menu","menulist","menulist-button","menulist-text","menulist-textfield","menutext","message-box","middle","min-intrinsic","mix","mongolian","monospace","move","multiple","multiply","myanmar","n-resize","narrower","ne-resize","nesw-resize","no-close-quote","no-drop","no-open-quote","no-repeat","none","normal","not-allowed","nowrap","ns-resize","numbers","numeric","nw-resize","nwse-resize","oblique","octal","open-quote","optimizeLegibility","optimizeSpeed","oriya","oromo","outset","outside","outside-shape","overlay","overline","padding","padding-box","painted","page","paused","persian","perspective","plus-darker","plus-lighter","pointer","polygon","portrait","pre","pre-line","pre-wrap","preserve-3d","progress","push-button","radial-gradient","radio","read-only","read-write","read-write-plaintext-only","rectangle","region","relative","repeat","repeating-linear-gradient","repeating-radial-gradient","repeat-x","repeat-y","reset","reverse","rgb","rgba","ridge","right","rotate","rotate3d","rotateX","rotateY","rotateZ","round","row","row-resize","row-reverse","rtl","run-in","running","s-resize","sans-serif","saturation","scale","scale3d","scaleX","scaleY","scaleZ","screen","scroll","scrollbar","se-resize","searchfield","searchfield-cancel-button","searchfield-decoration","searchfield-results-button","searchfield-results-decoration","semi-condensed","semi-expanded","separate","serif","show","sidama","simp-chinese-formal","simp-chinese-informal","single","skew","skewX","skewY","skip-white-space","slide","slider-horizontal","slider-vertical","sliderthumb-horizontal","sliderthumb-vertical","slow","small","small-caps","small-caption","smaller","soft-light","solid","somali","source-atop","source-in","source-out","source-over","space","space-around","space-between","spell-out","square","square-button","start","static","status-bar","stretch","stroke","sub","subpixel-antialiased","super","sw-resize","symbolic","symbols","table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","tamil","telugu","text","text-bottom","text-top","textarea","textfield","thai","thick","thin","threeddarkshadow","threedface","threedhighlight","threedlightshadow","threedshadow","tibetan","tigre","tigrinya-er","tigrinya-er-abegede","tigrinya-et","tigrinya-et-abegede","to","top","trad-chinese-formal","trad-chinese-informal","translate","translate3d","translateX","translateY","translateZ","transparent","ultra-condensed","ultra-expanded","underline","up","upper-alpha","upper-armenian","upper-greek","upper-hexadecimal","upper-latin","upper-norwegian","upper-roman","uppercase","urdu","url","var","vertical","vertical-text","visible","visibleFill","visiblePainted","visibleStroke","visual","w-resize","wait","wave","wider","window","windowframe","windowtext","words","wrap","wrap-reverse","x-large","x-small","xor","xx-large","xx-small"],w=b(v),x=d.concat(f).concat(h).concat(j).concat(l).concat(n).concat(t).concat(v);a.registerHelper("hintWords","css",x),a.defineMIME("text/css",{documentTypes:e,mediaTypes:g,mediaFeatures:i,mediaValueKeywords:k,propertyKeywords:m,nonStandardPropertyKeywords:o,fontProperties:q,counterDescriptors:s,colorKeywords:u,valueKeywords:w,tokenHooks:{"/":function(a,b){return!!a.eat("*")&&(b.tokenize=c,c(a,b))}},name:"css"}),a.defineMIME("text/x-scss",{mediaTypes:g,mediaFeatures:i,mediaValueKeywords:k,propertyKeywords:m,nonStandardPropertyKeywords:o,colorKeywords:u,valueKeywords:w,fontProperties:q,allowNested:!0,tokenHooks:{"/":function(a,b){return a.eat("/")?(a.skipToEnd(),["comment","comment"]):a.eat("*")?(b.tokenize=c,c(a,b)):["operator","operator"]},":":function(a){return!!a.match(/\s*\{/)&&[null,"{"]},$:function(a){return a.match(/^[\w-]+/),a.match(/^\s*:/,!1)?["variable-2","variable-definition"]:["variable-2","variable"]},"#":function(a){return!!a.eat("{")&&[null,"interpolation"]}},name:"css",helperType:"scss"}),a.defineMIME("text/x-less",{mediaTypes:g,mediaFeatures:i,mediaValueKeywords:k,propertyKeywords:m,nonStandardPropertyKeywords:o,colorKeywords:u,valueKeywords:w,fontProperties:q,allowNested:!0,tokenHooks:{"/":function(a,b){return a.eat("/")?(a.skipToEnd(),["comment","comment"]):a.eat("*")?(b.tokenize=c,c(a,b)):["operator","operator"]},"@":function(a){return a.eat("{")?[null,"interpolation"]:!a.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/,!1)&&(a.eatWhile(/[\w\\\-]/),a.match(/^\s*:/,!1)?["variable-2","variable-definition"]:["variable-2","variable"])},"&":function(){return["atom","atom"]}},name:"css",helperType:"less"}),a.defineMIME("text/x-gss",{documentTypes:e,mediaTypes:g,mediaFeatures:i,propertyKeywords:m,nonStandardPropertyKeywords:o,fontProperties:q,counterDescriptors:s,colorKeywords:u,valueKeywords:w,supportsAtComponent:!0,tokenHooks:{"/":function(a,b){return!!a.eat("*")&&(b.tokenize=c,c(a,b))}},name:"css",helperType:"gss"})})); \ No newline at end of file diff --git a/media/editors/codemirror/mode/cypher/cypher.js b/media/editors/codemirror/mode/cypher/cypher.js index f99abe23850ac..1d9ca4334ab6f 100644 --- a/media/editors/codemirror/mode/cypher/cypher.js +++ b/media/editors/codemirror/mode/cypher/cypher.js @@ -20,8 +20,12 @@ CodeMirror.defineMode("cypher", function(config) { var tokenBase = function(stream/*, state*/) { var ch = stream.next(); - if (ch === "\"" || ch === "'") { - stream.match(/.+?["']/); + if (ch === "\"") { + stream.match(/.+?["]/); + return "string"; + } + if (ch === "'") { + stream.match(/.+?[']/); return "string"; } if (/[{}\(\),\.;\[\]]/.test(ch)) { diff --git a/media/editors/codemirror/mode/cypher/cypher.min.js b/media/editors/codemirror/mode/cypher/cypher.min.js index dd0ba00f78ab7..d00afc87d9b4a 100644 --- a/media/editors/codemirror/mode/cypher/cypher.min.js +++ b/media/editors/codemirror/mode/cypher/cypher.min.js @@ -1 +1 @@ -!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";var b=function(a){return new RegExp("^(?:"+a.join("|")+")$","i")};a.defineMode("cypher",(function(c){var d,e=function(a){var b=a.next();if('"'===b||"'"===b)return a.match(/.+?["']/),"string";if(/[{}\(\),\.;\[\]]/.test(b))return d=b,"node";if("/"===b&&a.eat("/"))return a.skipToEnd(),"comment";if(l.test(b))return a.eatWhile(l),null;if(a.eatWhile(/[_\w\d]/),a.eat(":"))return a.eatWhile(/[\w\d_\-]/),"atom";var c=a.current();return i.test(c)?"builtin":j.test(c)?"def":k.test(c)?"keyword":"variable"},f=function(a,b,c){return a.context={prev:a.context,indent:a.indent,col:c,type:b}},g=function(a){return a.indent=a.context.indent,a.context=a.context.prev},h=c.indentUnit,i=b(["abs","acos","allShortestPaths","asin","atan","atan2","avg","ceil","coalesce","collect","cos","cot","count","degrees","e","endnode","exp","extract","filter","floor","haversin","head","id","keys","labels","last","left","length","log","log10","lower","ltrim","max","min","node","nodes","percentileCont","percentileDisc","pi","radians","rand","range","reduce","rel","relationship","relationships","replace","reverse","right","round","rtrim","shortestPath","sign","sin","size","split","sqrt","startnode","stdev","stdevp","str","substring","sum","tail","tan","timestamp","toFloat","toInt","toString","trim","type","upper"]),j=b(["all","and","any","contains","exists","has","in","none","not","or","single","xor"]),k=b(["as","asc","ascending","assert","by","case","commit","constraint","create","csv","cypher","delete","desc","descending","detach","distinct","drop","else","end","ends","explain","false","fieldterminator","foreach","from","headers","in","index","is","join","limit","load","match","merge","null","on","optional","order","periodic","profile","remove","return","scan","set","skip","start","starts","then","true","union","unique","unwind","using","when","where","with","call","yield"]),l=/[*+\-<>=&|~%^]/;return{startState:function(){return{tokenize:e,context:null,indent:0,col:0}},token:function(a,b){if(a.sol()&&(b.context&&null==b.context.align&&(b.context.align=!1),b.indent=a.indentation()),a.eatSpace())return null;var c=b.tokenize(a,b);if("comment"!==c&&b.context&&null==b.context.align&&"pattern"!==b.context.type&&(b.context.align=!0),"("===d)f(b,")",a.column());else if("["===d)f(b,"]",a.column());else if("{"===d)f(b,"}",a.column());else if(/[\]\}\)]/.test(d)){for(;b.context&&"pattern"===b.context.type;)g(b);b.context&&d===b.context.type&&g(b)}else"."===d&&b.context&&"pattern"===b.context.type?g(b):/atom|string|variable/.test(c)&&b.context&&(/[\}\]]/.test(b.context.type)?f(b,"pattern",a.column()):"pattern"!==b.context.type||b.context.align||(b.context.align=!0,b.context.col=a.column()));return c},indent:function(b,c){var d=c&&c.charAt(0),e=b.context;if(/[\]\}]/.test(d))for(;e&&"pattern"===e.type;)e=e.prev;var f=e&&d===e.type;return e?"keywords"===e.type?a.commands.newlineAndIndent:e.align?e.col+(f?0:1):e.indent+(f?0:h):0}}})),a.modeExtensions.cypher={autoFormatLineBreaks:function(a){for(var b,c,d,c=a.split("\n"),d=/\s+\b(return|where|order by|match|with|skip|limit|create|delete|set)\b\s/g,b=0;b=&|~%^]/;return{startState:function(){return{tokenize:e,context:null,indent:0,col:0}},token:function(a,b){if(a.sol()&&(b.context&&null==b.context.align&&(b.context.align=!1),b.indent=a.indentation()),a.eatSpace())return null;var c=b.tokenize(a,b);if("comment"!==c&&b.context&&null==b.context.align&&"pattern"!==b.context.type&&(b.context.align=!0),"("===d)f(b,")",a.column());else if("["===d)f(b,"]",a.column());else if("{"===d)f(b,"}",a.column());else if(/[\]\}\)]/.test(d)){for(;b.context&&"pattern"===b.context.type;)g(b);b.context&&d===b.context.type&&g(b)}else"."===d&&b.context&&"pattern"===b.context.type?g(b):/atom|string|variable/.test(c)&&b.context&&(/[\}\]]/.test(b.context.type)?f(b,"pattern",a.column()):"pattern"!==b.context.type||b.context.align||(b.context.align=!0,b.context.col=a.column()));return c},indent:function(b,c){var d=c&&c.charAt(0),e=b.context;if(/[\]\}]/.test(d))for(;e&&"pattern"===e.type;)e=e.prev;var f=e&&d===e.type;return e?"keywords"===e.type?a.commands.newlineAndIndent:e.align?e.col+(f?0:1):e.indent+(f?0:h):0}}})),a.modeExtensions.cypher={autoFormatLineBreaks:function(a){for(var b,c,d,c=a.split("\n"),d=/\s+\b(return|where|order by|match|with|skip|limit|create|delete|set)\b\s/g,b=0;b!|\/]/;return{startState:function(a){return{tokenize:null,context:new e((a||0)-i,0,"top",!1),indented:0,startOfLine:!0}},token:function(a,c){var d=c.context;if(a.sol()&&(null==d.align&&(d.align=!1),c.indented=a.indentation(),c.startOfLine=!0,"case"==d.type&&(d.type="}")),a.eatSpace())return null;h=null;var e=(c.tokenize||b)(a,c);return"comment"==e?e:(null==d.align&&(d.align=!0),"{"==h?f(c,a.column(),"}"):"["==h?f(c,a.column(),"]"):"("==h?f(c,a.column(),")"):"case"==h?d.type="case":"}"==h&&"}"==d.type?d=g(c):h==d.type&&g(c),c.startOfLine=!1,e)},indent:function(a,c){if(a.tokenize!=b&&null!=a.tokenize)return 0;var d=a.context,e=c&&c.charAt(0);if("case"==d.type&&/^(?:case|default)\b/.test(c))return a.context.type="}",d.indented;var f=e==d.type;return d.align?d.column+(f?0:1):d.indented+(f?0:i)},electricChars:"{}):",fold:"brace",blockCommentStart:"/*",blockCommentEnd:"*/",lineComment:"//"}})),a.defineMIME("text/x-go","go")})); \ No newline at end of file +!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";a.defineMode("go",(function(a){function b(a,b){var e=a.next();if('"'==e||"'"==e||"`"==e)return b.tokenize=c(e),b.tokenize(a,b);if(/[\d\.]/.test(e))return"."==e?a.match(/^[0-9]+([eE][\-+]?[0-9]+)?/):"0"==e?a.match(/^[xX][0-9a-fA-F]+/)||a.match(/^0[0-7]+/):a.match(/^[0-9]*\.?[0-9]*([eE][\-+]?[0-9]+)?/),"number";if(/[\[\]{}\(\),;\:\.]/.test(e))return h=e,null;if("/"==e){if(a.eat("*"))return b.tokenize=d,d(a,b);if(a.eat("/"))return a.skipToEnd(),"comment"}if(l.test(e))return a.eatWhile(l),"operator";a.eatWhile(/[\w\$_\xa1-\uffff]/);var f=a.current();return j.propertyIsEnumerable(f)?("case"!=f&&"default"!=f||(h="case"),"keyword"):k.propertyIsEnumerable(f)?"atom":"variable"}function c(a){return function(c,d){for(var e,f=!1,g=!1;null!=(e=c.next());){if(e==a&&!f){g=!0;break}f=!f&&"`"!=a&&"\\"==e}return(g||!f&&"`"!=a)&&(d.tokenize=b),"string"}}function d(a,c){for(var d,e=!1;d=a.next();){if("/"==d&&e){c.tokenize=b;break}e="*"==d}return"comment"}function e(a,b,c,d,e){this.indented=a,this.column=b,this.type=c,this.align=d,this.prev=e}function f(a,b,c){return a.context=new e(a.indented,b,c,null,a.context)}function g(a){if(a.context.prev){var b=a.context.type;return")"!=b&&"]"!=b&&"}"!=b||(a.indented=a.context.indented),a.context=a.context.prev}}var h,i=a.indentUnit,j={break:!0,case:!0,chan:!0,const:!0,continue:!0,default:!0,defer:!0,else:!0,fallthrough:!0,for:!0,func:!0,go:!0,goto:!0,if:!0,import:!0,interface:!0,map:!0,package:!0,range:!0,return:!0,select:!0,struct:!0,switch:!0,type:!0,var:!0,bool:!0,byte:!0,complex64:!0,complex128:!0,float32:!0,float64:!0,int8:!0,int16:!0,int32:!0,int64:!0,string:!0,uint8:!0,uint16:!0,uint32:!0,uint64:!0,int:!0,uint:!0,uintptr:!0,error:!0},k={true:!0,false:!0,iota:!0,nil:!0,append:!0,cap:!0,close:!0,complex:!0,copy:!0,imag:!0,len:!0,make:!0,new:!0,panic:!0,print:!0,println:!0,real:!0,recover:!0},l=/[+\-*&^%:=<>!|\/]/;return{startState:function(a){return{tokenize:null,context:new e((a||0)-i,0,"top",!1),indented:0,startOfLine:!0}},token:function(a,c){var d=c.context;if(a.sol()&&(null==d.align&&(d.align=!1),c.indented=a.indentation(),c.startOfLine=!0,"case"==d.type&&(d.type="}")),a.eatSpace())return null;h=null;var e=(c.tokenize||b)(a,c);return"comment"==e?e:(null==d.align&&(d.align=!0),"{"==h?f(c,a.column(),"}"):"["==h?f(c,a.column(),"]"):"("==h?f(c,a.column(),")"):"case"==h?d.type="case":"}"==h&&"}"==d.type?d=g(c):h==d.type&&g(c),c.startOfLine=!1,e)},indent:function(a,c){if(a.tokenize!=b&&null!=a.tokenize)return 0;var d=a.context,e=c&&c.charAt(0);if("case"==d.type&&/^(?:case|default)\b/.test(c))return a.context.type="}",d.indented;var f=e==d.type;return d.align?d.column+(f?0:1):d.indented+(f?0:i)},electricChars:"{}):",closeBrackets:"()[]{}''\"\"``",fold:"brace",blockCommentStart:"/*",blockCommentEnd:"*/",lineComment:"//"}})),a.defineMIME("text/x-go","go")})); \ No newline at end of file diff --git a/media/editors/codemirror/mode/haskell/haskell.js b/media/editors/codemirror/mode/haskell/haskell.js index fe0bab67ed6be..4197666a44f45 100644 --- a/media/editors/codemirror/mode/haskell/haskell.js +++ b/media/editors/codemirror/mode/haskell/haskell.js @@ -56,7 +56,7 @@ CodeMirror.defineMode("haskell", function(_config, modeConfig) { if (source.eat('\'')) { return "string"; } - return "error"; + return "string error"; } if (ch == '"') { @@ -166,7 +166,7 @@ CodeMirror.defineMode("haskell", function(_config, modeConfig) { } } setState(normal); - return "error"; + return "string error"; } function stringGap(source, setState) { @@ -194,7 +194,7 @@ CodeMirror.defineMode("haskell", function(_config, modeConfig) { "module", "newtype", "of", "then", "type", "where", "_"); setType("keyword")( - "\.\.", ":", "::", "=", "\\", "\"", "<-", "->", "@", "~", "=>"); + "\.\.", ":", "::", "=", "\\", "<-", "->", "@", "~", "=>"); setType("builtin")( "!!", "$!", "$", "&&", "+", "++", "-", ".", "/", "/=", "<", "<=", "=<<", diff --git a/media/editors/codemirror/mode/haskell/haskell.min.js b/media/editors/codemirror/mode/haskell/haskell.min.js index 2284abc839f3f..438d0f04928b0 100644 --- a/media/editors/codemirror/mode/haskell/haskell.min.js +++ b/media/editors/codemirror/mode/haskell/haskell.min.js @@ -1 +1 @@ -!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";a.defineMode("haskell",(function(a,b){function c(a,b,c){return b(c),c(a,b)}function d(a,b){if(a.eatWhile(p))return null;var d=a.next();if(o.test(d)){if("{"==d&&a.eat("-")){var g="comment";return a.eat("#")&&(g="meta"),c(a,b,e(g,1))}return null}if("'"==d)return a.eat("\\")?a.next():a.next(),a.eat("'")?"string":"error";if('"'==d)return c(a,b,f);if(i.test(d))return a.eatWhile(m),a.eat(".")?"qualifier":"variable-2";if(h.test(d))return a.eatWhile(m),"variable";if(j.test(d)){if("0"==d){if(a.eat(/[xX]/))return a.eatWhile(k),"integer";if(a.eat(/[oO]/))return a.eatWhile(l),"number"}a.eatWhile(j);var g="number";return a.match(/^\.\d+/)&&(g="number"),a.eat(/[eE]/)&&(g="number",a.eat(/[-+]/),a.eatWhile(j)),g}if("."==d&&a.eat("."))return"keyword";if(n.test(d)){if("-"==d&&a.eat(/-/)&&(a.eatWhile(/-/),!a.eat(n)))return a.skipToEnd(),"comment";var g="variable";return":"==d&&(g="variable-2"),a.eatWhile(n),g}return"error"}function e(a,b){return 0==b?d:function(c,f){for(var g=b;!c.eol();){var h=c.next();if("{"==h&&c.eat("-"))++g;else if("-"==h&&c.eat("}")&&(--g,0==g))return f(d),a}return f(e(a,g)),a}}function f(a,b){for(;!a.eol();){var c=a.next();if('"'==c)return b(d),"string";if("\\"==c){if(a.eol()||a.eat(p))return b(g),"string";a.eat("&")||a.next()}}return b(d),"error"}function g(a,b){return a.eat("\\")?c(a,b,f):(a.next(),b(d),"error")}var h=/[a-z_]/,i=/[A-Z]/,j=/\d/,k=/[0-9A-Fa-f]/,l=/[0-7]/,m=/[a-z_A-Z0-9'\xa1-\uffff]/,n=/[-!#$%&*+.\/<=>?@\\^|~:]/,o=/[(),;[\]`{}]/,p=/[ \t\v\f]/,q=(function(){function a(a){return function(){for(var b=0;b","@","~","=>"),a("builtin")("!!","$!","$","&&","+","++","-",".","/","/=","<","<=","=<<","==",">",">=",">>",">>=","^","^^","||","*","**"),a("builtin")("Bool","Bounded","Char","Double","EQ","Either","Enum","Eq","False","FilePath","Float","Floating","Fractional","Functor","GT","IO","IOError","Int","Integer","Integral","Just","LT","Left","Maybe","Monad","Nothing","Num","Ord","Ordering","Rational","Read","ReadS","Real","RealFloat","RealFrac","Right","Show","ShowS","String","True"),a("builtin")("abs","acos","acosh","all","and","any","appendFile","asTypeOf","asin","asinh","atan","atan2","atanh","break","catch","ceiling","compare","concat","concatMap","const","cos","cosh","curry","cycle","decodeFloat","div","divMod","drop","dropWhile","either","elem","encodeFloat","enumFrom","enumFromThen","enumFromThenTo","enumFromTo","error","even","exp","exponent","fail","filter","flip","floatDigits","floatRadix","floatRange","floor","fmap","foldl","foldl1","foldr","foldr1","fromEnum","fromInteger","fromIntegral","fromRational","fst","gcd","getChar","getContents","getLine","head","id","init","interact","ioError","isDenormalized","isIEEE","isInfinite","isNaN","isNegativeZero","iterate","last","lcm","length","lex","lines","log","logBase","lookup","map","mapM","mapM_","max","maxBound","maximum","maybe","min","minBound","minimum","mod","negate","not","notElem","null","odd","or","otherwise","pi","pred","print","product","properFraction","putChar","putStr","putStrLn","quot","quotRem","read","readFile","readIO","readList","readLn","readParen","reads","readsPrec","realToFrac","recip","rem","repeat","replicate","return","reverse","round","scaleFloat","scanl","scanl1","scanr","scanr1","seq","sequence","sequence_","show","showChar","showList","showParen","showString","shows","showsPrec","significand","signum","sin","sinh","snd","span","splitAt","sqrt","subtract","succ","sum","tail","take","takeWhile","tan","tanh","toEnum","toInteger","toRational","truncate","uncurry","undefined","unlines","until","unwords","unzip","unzip3","userError","words","writeFile","zip","zip3","zipWith","zipWith3");var d=b.overrideKeywords;if(d)for(var e in d)d.hasOwnProperty(e)&&(c[e]=d[e]);return c})();return{startState:function(){return{f:d}},copyState:function(a){return{f:a.f}},token:function(a,b){var c=b.f(a,(function(a){b.f=a})),d=a.current();return q.hasOwnProperty(d)?q[d]:c},blockCommentStart:"{-",blockCommentEnd:"-}",lineComment:"--"}})),a.defineMIME("text/x-haskell","haskell")})); \ No newline at end of file +!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";a.defineMode("haskell",(function(a,b){function c(a,b,c){return b(c),c(a,b)}function d(a,b){if(a.eatWhile(p))return null;var d=a.next();if(o.test(d)){if("{"==d&&a.eat("-")){var g="comment";return a.eat("#")&&(g="meta"),c(a,b,e(g,1))}return null}if("'"==d)return a.eat("\\")?a.next():a.next(),a.eat("'")?"string":"string error";if('"'==d)return c(a,b,f);if(i.test(d))return a.eatWhile(m),a.eat(".")?"qualifier":"variable-2";if(h.test(d))return a.eatWhile(m),"variable";if(j.test(d)){if("0"==d){if(a.eat(/[xX]/))return a.eatWhile(k),"integer";if(a.eat(/[oO]/))return a.eatWhile(l),"number"}a.eatWhile(j);var g="number";return a.match(/^\.\d+/)&&(g="number"),a.eat(/[eE]/)&&(g="number",a.eat(/[-+]/),a.eatWhile(j)),g}if("."==d&&a.eat("."))return"keyword";if(n.test(d)){if("-"==d&&a.eat(/-/)&&(a.eatWhile(/-/),!a.eat(n)))return a.skipToEnd(),"comment";var g="variable";return":"==d&&(g="variable-2"),a.eatWhile(n),g}return"error"}function e(a,b){return 0==b?d:function(c,f){for(var g=b;!c.eol();){var h=c.next();if("{"==h&&c.eat("-"))++g;else if("-"==h&&c.eat("}")&&(--g,0==g))return f(d),a}return f(e(a,g)),a}}function f(a,b){for(;!a.eol();){var c=a.next();if('"'==c)return b(d),"string";if("\\"==c){if(a.eol()||a.eat(p))return b(g),"string";a.eat("&")||a.next()}}return b(d),"string error"}function g(a,b){return a.eat("\\")?c(a,b,f):(a.next(),b(d),"error")}var h=/[a-z_]/,i=/[A-Z]/,j=/\d/,k=/[0-9A-Fa-f]/,l=/[0-7]/,m=/[a-z_A-Z0-9'\xa1-\uffff]/,n=/[-!#$%&*+.\/<=>?@\\^|~:]/,o=/[(),;[\]`{}]/,p=/[ \t\v\f]/,q=(function(){function a(a){return function(){for(var b=0;b","@","~","=>"),a("builtin")("!!","$!","$","&&","+","++","-",".","/","/=","<","<=","=<<","==",">",">=",">>",">>=","^","^^","||","*","**"),a("builtin")("Bool","Bounded","Char","Double","EQ","Either","Enum","Eq","False","FilePath","Float","Floating","Fractional","Functor","GT","IO","IOError","Int","Integer","Integral","Just","LT","Left","Maybe","Monad","Nothing","Num","Ord","Ordering","Rational","Read","ReadS","Real","RealFloat","RealFrac","Right","Show","ShowS","String","True"),a("builtin")("abs","acos","acosh","all","and","any","appendFile","asTypeOf","asin","asinh","atan","atan2","atanh","break","catch","ceiling","compare","concat","concatMap","const","cos","cosh","curry","cycle","decodeFloat","div","divMod","drop","dropWhile","either","elem","encodeFloat","enumFrom","enumFromThen","enumFromThenTo","enumFromTo","error","even","exp","exponent","fail","filter","flip","floatDigits","floatRadix","floatRange","floor","fmap","foldl","foldl1","foldr","foldr1","fromEnum","fromInteger","fromIntegral","fromRational","fst","gcd","getChar","getContents","getLine","head","id","init","interact","ioError","isDenormalized","isIEEE","isInfinite","isNaN","isNegativeZero","iterate","last","lcm","length","lex","lines","log","logBase","lookup","map","mapM","mapM_","max","maxBound","maximum","maybe","min","minBound","minimum","mod","negate","not","notElem","null","odd","or","otherwise","pi","pred","print","product","properFraction","putChar","putStr","putStrLn","quot","quotRem","read","readFile","readIO","readList","readLn","readParen","reads","readsPrec","realToFrac","recip","rem","repeat","replicate","return","reverse","round","scaleFloat","scanl","scanl1","scanr","scanr1","seq","sequence","sequence_","show","showChar","showList","showParen","showString","shows","showsPrec","significand","signum","sin","sinh","snd","span","splitAt","sqrt","subtract","succ","sum","tail","take","takeWhile","tan","tanh","toEnum","toInteger","toRational","truncate","uncurry","undefined","unlines","until","unwords","unzip","unzip3","userError","words","writeFile","zip","zip3","zipWith","zipWith3");var d=b.overrideKeywords;if(d)for(var e in d)d.hasOwnProperty(e)&&(c[e]=d[e]);return c})();return{startState:function(){return{f:d}},copyState:function(a){return{f:a.f}},token:function(a,b){var c=b.f(a,(function(a){b.f=a})),d=a.current();return q.hasOwnProperty(d)?q[d]:c},blockCommentStart:"{-",blockCommentEnd:"-}",lineComment:"--"}})),a.defineMIME("text/x-haskell","haskell")})); \ No newline at end of file diff --git a/media/editors/codemirror/mode/javascript/javascript.js b/media/editors/codemirror/mode/javascript/javascript.js index e23560746d68d..a717745897415 100644 --- a/media/editors/codemirror/mode/javascript/javascript.js +++ b/media/editors/codemirror/mode/javascript/javascript.js @@ -209,6 +209,11 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { var arrow = stream.string.indexOf("=>", stream.start); if (arrow < 0) return; + if (isTS) { // Try to skip TypeScript return type declarations after the arguments + var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow)) + if (m) arrow = m.index + } + var depth = 0, sawSomething = false; for (var pos = arrow - 1; pos >= 0; --pos) { var ch = stream.string.charAt(pos); @@ -390,6 +395,7 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma; if (atomicTypes.hasOwnProperty(type)) return cont(maybeop); if (type == "function") return cont(functiondef, maybeop); + if (type == "class") return cont(pushlex("form"), classExpression, poplex); if (type == "keyword c" || type == "async") return cont(noComma ? maybeexpressionNoComma : maybeexpression); if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop); if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression); @@ -531,9 +537,6 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { if (value == "?") return cont(maybetype); } } - function maybedefault(_, value) { - if (value == "=") return cont(expressionNoComma); - } function typeexpr(type) { if (type == "variable") {cx.marked = "variable-3"; return cont(afterType);} if (type == "{") return cont(commasep(typeprop, "}")) @@ -615,19 +618,24 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { } function funarg(type) { if (type == "spread") return cont(funarg); - return pass(pattern, maybetype, maybedefault); + return pass(pattern, maybetype, maybeAssign); + } + function classExpression(type, value) { + // Class expressions may have an optional name. + if (type == "variable") return className(type, value); + return classNameAfter(type, value); } function className(type, value) { if (type == "variable") {register(value); return cont(classNameAfter);} } function classNameAfter(type, value) { - if (value == "extends") return cont(isTS ? typeexpr : expression, classNameAfter); + if (value == "extends" || value == "implements") return cont(isTS ? typeexpr : expression, classNameAfter); if (type == "{") return cont(pushlex("}"), classBody, poplex); } function classBody(type, value) { if (type == "variable" || cx.style == "keyword") { if ((value == "static" || value == "get" || value == "set" || - (isTS && (value == "public" || value == "private" || value == "protected"))) && + (isTS && (value == "public" || value == "private" || value == "protected" || value == "readonly" || value == "abstract"))) && cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false)) { cx.marked = "keyword"; return cont(classBody); @@ -642,8 +650,9 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) { if (type == ";") return cont(classBody); if (type == "}") return cont(); } - function classfield(type) { - if (type == ":") return cont(typeexpr) + function classfield(type, value) { + if (value == "?") return cont(classfield) + if (type == ":") return cont(typeexpr, maybeAssign) return pass(functiondef) } function afterExport(_type, value) { diff --git a/media/editors/codemirror/mode/javascript/javascript.min.js b/media/editors/codemirror/mode/javascript/javascript.min.js index 7a8a8db3fcd47..dbd3ec0768dc1 100644 --- a/media/editors/codemirror/mode/javascript/javascript.min.js +++ b/media/editors/codemirror/mode/javascript/javascript.min.js @@ -1 +1 @@ -!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";function b(a,b,c){return/^(?:operator|sof|keyword c|case|new|[\[{}\(,;:]|=>)$/.test(b.lastType)||"quasi"==b.lastType&&/\{\s*$/.test(a.string.slice(0,a.pos-(c||0)))}a.defineMode("javascript",(function(c,d){function e(a){for(var b,c=!1,d=!1;null!=(b=a.next());){if(!c){if("/"==b&&!d)return;"["==b?d=!0:d&&"]"==b&&(d=!1)}c=!c&&"\\"==b}}function f(a,b,c){return xa=a,ya=c,b}function g(a,c){var d=a.next();if('"'==d||"'"==d)return c.tokenize=h(d),c.tokenize(a,c);if("."==d&&a.match(/^\d+(?:[eE][+\-]?\d+)?/))return f("number","number");if("."==d&&a.match(".."))return f("spread","meta");if(/[\[\]{}\(\),;\:\.]/.test(d))return f(d);if("="==d&&a.eat(">"))return f("=>","operator");if("0"==d&&a.eat(/x/i))return a.eatWhile(/[\da-f]/i),f("number","number");if("0"==d&&a.eat(/o/i))return a.eatWhile(/[0-7]/i),f("number","number");if("0"==d&&a.eat(/b/i))return a.eatWhile(/[01]/i),f("number","number");if(/\d/.test(d))return a.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/),f("number","number");if("/"==d)return a.eat("*")?(c.tokenize=i,i(a,c)):a.eat("/")?(a.skipToEnd(),f("comment","comment")):b(a,c,1)?(e(a),a.match(/^\b(([gimyu])(?![gimyu]*\2))+\b/),f("regexp","string-2")):(a.eatWhile(Ga),f("operator","operator",a.current()));if("`"==d)return c.tokenize=j,j(a,c);if("#"==d)return a.skipToEnd(),f("error","error");if(Ga.test(d))return a.eatWhile(Ga),f("operator","operator",a.current());if(Ea.test(d)){a.eatWhile(Ea);var g=a.current(),k=Fa.propertyIsEnumerable(g)&&Fa[g];return k&&"."!=c.lastType?f(k.type,k.style,g):f("variable","variable",g)}}function h(a){return function(b,c){var d,e=!1;if(Ba&&"@"==b.peek()&&b.match(Ha))return c.tokenize=g,f("jsonld-keyword","meta");for(;null!=(d=b.next())&&(d!=a||e);)e=!e&&"\\"==d;return e||(c.tokenize=g),f("string","string")}}function i(a,b){for(var c,d=!1;c=a.next();){if("/"==c&&d){b.tokenize=g;break}d="*"==c}return f("comment","comment")}function j(a,b){for(var c,d=!1;null!=(c=a.next());){if(!d&&("`"==c||"$"==c&&a.eat("{"))){b.tokenize=g;break}d=!d&&"\\"==c}return f("quasi","string-2",a.current())}function k(a,b){b.fatArrowAt&&(b.fatArrowAt=null);var c=a.string.indexOf("=>",a.start);if(!(c<0)){for(var d=0,e=!1,f=c-1;f>=0;--f){var g=a.string.charAt(f),h=Ia.indexOf(g);if(h>=0&&h<3){if(!d){++f;break}if(0==--d){"("==g&&(e=!0);break}}else if(h>=3&&h<6)++d;else if(Ea.test(g))e=!0;else{if(/["'\/]/.test(g))return;if(e&&!d){++f;break}}}e&&!d&&(b.fatArrowAt=f)}}function l(a,b,c,d,e,f){this.indented=a,this.column=b,this.type=c,this.prev=e,this.info=f,null!=d&&(this.align=d)}function m(a,b){for(var c=a.localVars;c;c=c.next)if(c.name==b)return!0;for(var d=a.context;d;d=d.prev)for(var c=d.vars;c;c=c.next)if(c.name==b)return!0}function n(a,b,c,d,e){var f=a.cc;for(Ka.state=a,Ka.stream=e,Ka.marked=null,Ka.cc=f,Ka.style=b,a.lexical.hasOwnProperty("align")||(a.lexical.align=!0);;){var g=f.length?f.pop():Ca?x:w;if(g(c,d)){for(;f.length&&f[f.length-1].lex;)f.pop()();return Ka.marked?Ka.marked:"variable"==c&&m(a,d)?"variable-2":b}}}function o(){for(var a=arguments.length-1;a>=0;a--)Ka.cc.push(arguments[a])}function p(){return o.apply(null,arguments),!0}function q(a){function b(b){for(var c=b;c;c=c.next)if(c.name==a)return!0;return!1}var c=Ka.state;if(Ka.marked="def",c.context){if(b(c.localVars))return;c.localVars={name:a,next:c.localVars}}else{if(b(c.globalVars))return;d.globalVars&&(c.globalVars={name:a,next:c.globalVars})}}function r(){Ka.state.context={prev:Ka.state.context,vars:Ka.state.localVars},Ka.state.localVars=La}function s(){Ka.state.localVars=Ka.state.context.vars,Ka.state.context=Ka.state.context.prev}function t(a,b){var c=function(){var c=Ka.state,d=c.indented;if("stat"==c.lexical.type)d=c.lexical.indented;else for(var e=c.lexical;e&&")"==e.type&&e.align;e=e.prev)d=e.indented;c.lexical=new l(d,Ka.stream.column(),a,null,c.lexical,b)};return c.lex=!0,c}function u(){var a=Ka.state;a.lexical.prev&&(")"==a.lexical.type&&(a.indented=a.lexical.indented),a.lexical=a.lexical.prev)}function v(a){function b(c){return c==a?p():";"==a?o():p(b)}return b}function w(a,b){return"var"==a?p(t("vardef",b.length),_,v(";"),u):"keyword a"==a?p(t("form"),z,w,u):"keyword b"==a?p(t("form"),w,u):"{"==a?p(t("}"),T,u):";"==a?p():"if"==a?("else"==Ka.state.lexical.info&&Ka.state.cc[Ka.state.cc.length-1]==u&&Ka.state.cc.pop()(),p(t("form"),z,w,u,ea)):"function"==a?p(ka):"for"==a?p(t("form"),fa,w,u):"variable"==a?p(t("stat"),M):"switch"==a?p(t("form"),z,t("}","switch"),v("{"),T,u,u):"case"==a?p(x,v(":")):"default"==a?p(v(":")):"catch"==a?p(t("form"),r,v("("),la,v(")"),w,u,s):"class"==a?p(t("form"),ma,u):"export"==a?p(t("stat"),qa,u):"import"==a?p(t("stat"),ra,u):"module"==a?p(t("form"),aa,t("}"),v("{"),T,u,u):"type"==a?p(W,v("operator"),W,v(";")):"async"==a?p(w):o(t("stat"),x,v(";"),u)}function x(a){return A(a,!1)}function y(a){return A(a,!0)}function z(a){return"("!=a?o():p(t(")"),x,v(")"),u)}function A(a,b){if(Ka.state.fatArrowAt==Ka.stream.start){var c=b?I:H;if("("==a)return p(r,t(")"),R(aa,")"),u,v("=>"),c,s);if("variable"==a)return o(r,aa,v("=>"),c,s)}var d=b?E:D;return Ja.hasOwnProperty(a)?p(d):"function"==a?p(ka,d):"keyword c"==a||"async"==a?p(b?C:B):"("==a?p(t(")"),B,v(")"),u,d):"operator"==a||"spread"==a?p(b?y:x):"["==a?p(t("]"),va,u,d):"{"==a?S(O,"}",null,d):"quasi"==a?o(F,d):"new"==a?p(J(b)):p()}function B(a){return a.match(/[;\}\)\],]/)?o():o(x)}function C(a){return a.match(/[;\}\)\],]/)?o():o(y)}function D(a,b){return","==a?p(x):E(a,b,!1)}function E(a,b,c){var d=0==c?D:E,e=0==c?x:y;return"=>"==a?p(r,c?I:H,s):"operator"==a?/\+\+|--/.test(b)?p(d):"?"==b?p(x,v(":"),e):p(e):"quasi"==a?o(F,d):";"!=a?"("==a?S(y,")","call",d):"."==a?p(N,d):"["==a?p(t("]"),B,v("]"),u,d):void 0:void 0}function F(a,b){return"quasi"!=a?o():"${"!=b.slice(b.length-2)?p(F):p(x,G)}function G(a){if("}"==a)return Ka.marked="string-2",Ka.state.tokenize=j,p(F)}function H(a){return k(Ka.stream,Ka.state),o("{"==a?w:x)}function I(a){return k(Ka.stream,Ka.state),o("{"==a?w:y)}function J(a){return function(b){return"."==b?p(a?L:K):o(a?y:x)}}function K(a,b){if("target"==b)return Ka.marked="keyword",p(D)}function L(a,b){if("target"==b)return Ka.marked="keyword",p(E)}function M(a){return":"==a?p(u,w):o(D,v(";"),u)}function N(a){if("variable"==a)return Ka.marked="property",p()}function O(a,b){return"async"==a?(Ka.marked="property",p(O)):"variable"==a||"keyword"==Ka.style?(Ka.marked="property",p("get"==b||"set"==b?P:Q)):"number"==a||"string"==a?(Ka.marked=Ba?"property":Ka.style+" property",p(Q)):"jsonld-keyword"==a?p(Q):"modifier"==a?p(O):"["==a?p(x,v("]"),Q):"spread"==a?p(x):":"==a?o(Q):void 0}function P(a){return"variable"!=a?o(Q):(Ka.marked="property",p(ka))}function Q(a){return":"==a?p(y):"("==a?o(ka):void 0}function R(a,b){function c(d,e){if(","==d){var f=Ka.state.lexical;return"call"==f.info&&(f.pos=(f.pos||0)+1),p((function(c,d){return c==b||d==b?o():o(a)}),c)}return d==b||e==b?p():p(v(b))}return function(d,e){return d==b||e==b?p():o(a,c)}}function S(a,b,c){for(var d=3;d"==a)return p(W)}function Y(a){return"variable"==a||"keyword"==Ka.style?(Ka.marked="property",p(Y)):":"==a?p(W):void 0}function Z(a){return"variable"==a?p(Z):":"==a?p(W):void 0}function $(a,b){return"<"==b?p(R(W,">"),$):"["==a?p(v("]"),$):void 0}function _(){return o(aa,U,ca,da)}function aa(a,b){return"modifier"==a?p(aa):"variable"==a?(q(b),p()):"spread"==a?p(aa):"["==a?S(aa,"]"):"{"==a?S(ba,"}"):void 0}function ba(a,b){return"variable"!=a||Ka.stream.match(/^\s*:/,!1)?("variable"==a&&(Ka.marked="property"),"spread"==a?p(aa):"}"==a?o():p(v(":"),aa,ca)):(q(b),p(ca))}function ca(a,b){if("="==b)return p(y)}function da(a){if(","==a)return p(_)}function ea(a,b){if("keyword b"==a&&"else"==b)return p(t("form","else"),w,u)}function fa(a){if("("==a)return p(t(")"),ga,v(")"),u)}function ga(a){return"var"==a?p(_,v(";"),ia):";"==a?p(ia):"variable"==a?p(ha):o(x,v(";"),ia)}function ha(a,b){return"in"==b||"of"==b?(Ka.marked="keyword",p(x)):p(D,ia)}function ia(a,b){return";"==a?p(ja):"in"==b||"of"==b?(Ka.marked="keyword",p(x)):o(x,v(";"),ja)}function ja(a){")"!=a&&p(x)}function ka(a,b){return"*"==b?(Ka.marked="keyword",p(ka)):"variable"==a?(q(b),p(ka)):"("==a?p(r,t(")"),R(la,")"),u,U,w,s):void 0}function la(a){return"spread"==a?p(la):o(aa,U,V)}function ma(a,b){if("variable"==a)return q(b),p(na)}function na(a,b){return"extends"==b?p(Da?W:x,na):"{"==a?p(t("}"),oa,u):void 0}function oa(a,b){return"variable"==a||"keyword"==Ka.style?("static"==b||"get"==b||"set"==b||Da&&("public"==b||"private"==b||"protected"==b))&&Ka.stream.match(/^\s+[\w$\xa1-\uffff]/,!1)?(Ka.marked="keyword",p(oa)):(Ka.marked="property",p(Da?pa:ka,oa)):"*"==b?(Ka.marked="keyword",p(oa)):";"==a?p(oa):"}"==a?p():void 0}function pa(a){return":"==a?p(W):o(ka)}function qa(a,b){return"*"==b?(Ka.marked="keyword",p(ua,v(";"))):"default"==b?(Ka.marked="keyword",p(x,v(";"))):o(w)}function ra(a){return"string"==a?p():o(sa,ua)}function sa(a,b){return"{"==a?S(sa,"}"):("variable"==a&&q(b),"*"==b&&(Ka.marked="keyword"),p(ta))}function ta(a,b){if("as"==b)return Ka.marked="keyword",p(sa)}function ua(a,b){if("from"==b)return Ka.marked="keyword",p(x)}function va(a){return"]"==a?p():o(R(y,"]"))}function wa(a,b){return"operator"==a.lastType||","==a.lastType||Ga.test(b.charAt(0))||/[,.]/.test(b.charAt(0))}var xa,ya,za=c.indentUnit,Aa=d.statementIndent,Ba=d.jsonld,Ca=d.json||Ba,Da=d.typescript,Ea=d.wordCharacters||/[\w$\xa1-\uffff]/,Fa=(function(){function a(a){return{type:a,style:"keyword"}}var b=a("keyword a"),c=a("keyword b"),d=a("keyword c"),e=a("operator"),f={type:"atom",style:"atom"},g={if:a("if"),while:b,with:b,else:c,do:c,try:c,finally:c,return:d,break:d,continue:d,new:a("new"),delete:d,throw:d,debugger:d,var:a("var"),const:a("var"),let:a("var"),function:a("function"),catch:a("catch"),for:a("for"),switch:a("switch"),case:a("case"),default:a("default"),in:e,typeof:e,instanceof:e,true:f,false:f,null:f,undefined:f,NaN:f,Infinity:f,this:a("this"),class:a("class"),super:a("atom"),yield:d,export:a("export"),import:a("import"),extends:d,await:d,async:a("async")};if(Da){var h={type:"variable",style:"variable-3"},i={interface:a("class"),implements:d,namespace:d,module:a("module"),enum:a("module"),type:a("type"),public:a("modifier"),private:a("modifier"),protected:a("modifier"),abstract:a("modifier"),as:e,string:h,number:h,boolean:h,any:h};for(var j in i)g[j]=i[j]}return g})(),Ga=/[+\-*&%=<>!?|~^]/,Ha=/^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/,Ia="([{}])",Ja={atom:!0,number:!0,variable:!0,string:!0,regexp:!0,this:!0,"jsonld-keyword":!0},Ka={state:null,column:null,marked:null,cc:null},La={name:"this",next:{name:"arguments"}};return u.lex=!0,{startState:function(a){var b={tokenize:g,lastType:"sof",cc:[],lexical:new l((a||0)-za,0,"block",!1),localVars:d.localVars,context:d.localVars&&{vars:d.localVars},indented:a||0};return d.globalVars&&"object"==typeof d.globalVars&&(b.globalVars=d.globalVars),b},token:function(a,b){if(a.sol()&&(b.lexical.hasOwnProperty("align")||(b.lexical.align=!1),b.indented=a.indentation(),k(a,b)),b.tokenize!=i&&a.eatSpace())return null;var c=b.tokenize(a,b);return"comment"==xa?c:(b.lastType="operator"!=xa||"++"!=ya&&"--"!=ya?xa:"incdec",n(b,c,xa,ya,a))},indent:function(b,c){if(b.tokenize==i)return a.Pass;if(b.tokenize!=g)return 0;var e,f=c&&c.charAt(0),h=b.lexical;if(!/^\s*else\b/.test(c))for(var j=b.cc.length-1;j>=0;--j){var k=b.cc[j];if(k==u)h=h.prev;else if(k!=ea)break}for(;("stat"==h.type||"form"==h.type)&&("}"==f||(e=b.cc[b.cc.length-1])&&(e==D||e==E)&&!/^[,\.=+\-*:?[\(]/.test(c));)h=h.prev;Aa&&")"==h.type&&"stat"==h.prev.type&&(h=h.prev);var l=h.type,m=f==l;return"vardef"==l?h.indented+("operator"==b.lastType||","==b.lastType?h.info+1:0):"form"==l&&"{"==f?h.indented:"form"==l?h.indented+za:"stat"==l?h.indented+(wa(b,c)?Aa||za:0):"switch"!=h.info||m||0==d.doubleIndentSwitch?h.align?h.column+(m?0:1):h.indented+(m?0:za):h.indented+(/^(?:case|default)\b/.test(c)?za:2*za)},electricInput:/^\s*(?:case .*?:|default:|\{|\})$/,blockCommentStart:Ca?null:"/*",blockCommentEnd:Ca?null:"*/",lineComment:Ca?null:"//",fold:"brace",closeBrackets:"()[]{}''\"\"``",helperType:Ca?"json":"javascript",jsonldMode:Ba,jsonMode:Ca,expressionAllowed:b,skipExpression:function(a){var b=a.cc[a.cc.length-1];b!=x&&b!=y||a.cc.pop()}}})),a.registerHelper("wordChars","javascript",/[\w$]/),a.defineMIME("text/javascript","javascript"),a.defineMIME("text/ecmascript","javascript"),a.defineMIME("application/javascript","javascript"),a.defineMIME("application/x-javascript","javascript"),a.defineMIME("application/ecmascript","javascript"),a.defineMIME("application/json",{name:"javascript",json:!0}),a.defineMIME("application/x-json",{name:"javascript",json:!0}),a.defineMIME("application/ld+json",{name:"javascript",jsonld:!0}),a.defineMIME("text/typescript",{name:"javascript",typescript:!0}),a.defineMIME("application/typescript",{name:"javascript",typescript:!0})})); \ No newline at end of file +!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";function b(a,b,c){return/^(?:operator|sof|keyword c|case|new|[\[{}\(,;:]|=>)$/.test(b.lastType)||"quasi"==b.lastType&&/\{\s*$/.test(a.string.slice(0,a.pos-(c||0)))}a.defineMode("javascript",(function(c,d){function e(a){for(var b,c=!1,d=!1;null!=(b=a.next());){if(!c){if("/"==b&&!d)return;"["==b?d=!0:d&&"]"==b&&(d=!1)}c=!c&&"\\"==b}}function f(a,b,c){return xa=a,ya=c,b}function g(a,c){var d=a.next();if('"'==d||"'"==d)return c.tokenize=h(d),c.tokenize(a,c);if("."==d&&a.match(/^\d+(?:[eE][+\-]?\d+)?/))return f("number","number");if("."==d&&a.match(".."))return f("spread","meta");if(/[\[\]{}\(\),;\:\.]/.test(d))return f(d);if("="==d&&a.eat(">"))return f("=>","operator");if("0"==d&&a.eat(/x/i))return a.eatWhile(/[\da-f]/i),f("number","number");if("0"==d&&a.eat(/o/i))return a.eatWhile(/[0-7]/i),f("number","number");if("0"==d&&a.eat(/b/i))return a.eatWhile(/[01]/i),f("number","number");if(/\d/.test(d))return a.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/),f("number","number");if("/"==d)return a.eat("*")?(c.tokenize=i,i(a,c)):a.eat("/")?(a.skipToEnd(),f("comment","comment")):b(a,c,1)?(e(a),a.match(/^\b(([gimyu])(?![gimyu]*\2))+\b/),f("regexp","string-2")):(a.eatWhile(Ga),f("operator","operator",a.current()));if("`"==d)return c.tokenize=j,j(a,c);if("#"==d)return a.skipToEnd(),f("error","error");if(Ga.test(d))return a.eatWhile(Ga),f("operator","operator",a.current());if(Ea.test(d)){a.eatWhile(Ea);var g=a.current(),k=Fa.propertyIsEnumerable(g)&&Fa[g];return k&&"."!=c.lastType?f(k.type,k.style,g):f("variable","variable",g)}}function h(a){return function(b,c){var d,e=!1;if(Ba&&"@"==b.peek()&&b.match(Ha))return c.tokenize=g,f("jsonld-keyword","meta");for(;null!=(d=b.next())&&(d!=a||e);)e=!e&&"\\"==d;return e||(c.tokenize=g),f("string","string")}}function i(a,b){for(var c,d=!1;c=a.next();){if("/"==c&&d){b.tokenize=g;break}d="*"==c}return f("comment","comment")}function j(a,b){for(var c,d=!1;null!=(c=a.next());){if(!d&&("`"==c||"$"==c&&a.eat("{"))){b.tokenize=g;break}d=!d&&"\\"==c}return f("quasi","string-2",a.current())}function k(a,b){b.fatArrowAt&&(b.fatArrowAt=null);var c=a.string.indexOf("=>",a.start);if(!(c<0)){if(Da){var d=/:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(a.string.slice(a.start,c));d&&(c=d.index)}for(var e=0,f=!1,g=c-1;g>=0;--g){var h=a.string.charAt(g),i=Ia.indexOf(h);if(i>=0&&i<3){if(!e){++g;break}if(0==--e){"("==h&&(f=!0);break}}else if(i>=3&&i<6)++e;else if(Ea.test(h))f=!0;else{if(/["'\/]/.test(h))return;if(f&&!e){++g;break}}}f&&!e&&(b.fatArrowAt=g)}}function l(a,b,c,d,e,f){this.indented=a,this.column=b,this.type=c,this.prev=e,this.info=f,null!=d&&(this.align=d)}function m(a,b){for(var c=a.localVars;c;c=c.next)if(c.name==b)return!0;for(var d=a.context;d;d=d.prev)for(var c=d.vars;c;c=c.next)if(c.name==b)return!0}function n(a,b,c,d,e){var f=a.cc;for(Ka.state=a,Ka.stream=e,Ka.marked=null,Ka.cc=f,Ka.style=b,a.lexical.hasOwnProperty("align")||(a.lexical.align=!0);;){var g=f.length?f.pop():Ca?x:w;if(g(c,d)){for(;f.length&&f[f.length-1].lex;)f.pop()();return Ka.marked?Ka.marked:"variable"==c&&m(a,d)?"variable-2":b}}}function o(){for(var a=arguments.length-1;a>=0;a--)Ka.cc.push(arguments[a])}function p(){return o.apply(null,arguments),!0}function q(a){function b(b){for(var c=b;c;c=c.next)if(c.name==a)return!0;return!1}var c=Ka.state;if(Ka.marked="def",c.context){if(b(c.localVars))return;c.localVars={name:a,next:c.localVars}}else{if(b(c.globalVars))return;d.globalVars&&(c.globalVars={name:a,next:c.globalVars})}}function r(){Ka.state.context={prev:Ka.state.context,vars:Ka.state.localVars},Ka.state.localVars=La}function s(){Ka.state.localVars=Ka.state.context.vars,Ka.state.context=Ka.state.context.prev}function t(a,b){var c=function(){var c=Ka.state,d=c.indented;if("stat"==c.lexical.type)d=c.lexical.indented;else for(var e=c.lexical;e&&")"==e.type&&e.align;e=e.prev)d=e.indented;c.lexical=new l(d,Ka.stream.column(),a,null,c.lexical,b)};return c.lex=!0,c}function u(){var a=Ka.state;a.lexical.prev&&(")"==a.lexical.type&&(a.indented=a.lexical.indented),a.lexical=a.lexical.prev)}function v(a){function b(c){return c==a?p():";"==a?o():p(b)}return b}function w(a,b){return"var"==a?p(t("vardef",b.length),$,v(";"),u):"keyword a"==a?p(t("form"),z,w,u):"keyword b"==a?p(t("form"),w,u):"{"==a?p(t("}"),T,u):";"==a?p():"if"==a?("else"==Ka.state.lexical.info&&Ka.state.cc[Ka.state.cc.length-1]==u&&Ka.state.cc.pop()(),p(t("form"),z,w,u,da)):"function"==a?p(ja):"for"==a?p(t("form"),ea,w,u):"variable"==a?p(t("stat"),M):"switch"==a?p(t("form"),z,t("}","switch"),v("{"),T,u,u):"case"==a?p(x,v(":")):"default"==a?p(v(":")):"catch"==a?p(t("form"),r,v("("),ka,v(")"),w,u,s):"class"==a?p(t("form"),ma,u):"export"==a?p(t("stat"),qa,u):"import"==a?p(t("stat"),ra,u):"module"==a?p(t("form"),_,t("}"),v("{"),T,u,u):"type"==a?p(V,v("operator"),V,v(";")):"async"==a?p(w):o(t("stat"),x,v(";"),u)}function x(a){return A(a,!1)}function y(a){return A(a,!0)}function z(a){return"("!=a?o():p(t(")"),x,v(")"),u)}function A(a,b){if(Ka.state.fatArrowAt==Ka.stream.start){var c=b?I:H;if("("==a)return p(r,t(")"),R(_,")"),u,v("=>"),c,s);if("variable"==a)return o(r,_,v("=>"),c,s)}var d=b?E:D;return Ja.hasOwnProperty(a)?p(d):"function"==a?p(ja,d):"class"==a?p(t("form"),la,u):"keyword c"==a||"async"==a?p(b?C:B):"("==a?p(t(")"),B,v(")"),u,d):"operator"==a||"spread"==a?p(b?y:x):"["==a?p(t("]"),va,u,d):"{"==a?S(O,"}",null,d):"quasi"==a?o(F,d):"new"==a?p(J(b)):p()}function B(a){return a.match(/[;\}\)\],]/)?o():o(x)}function C(a){return a.match(/[;\}\)\],]/)?o():o(y)}function D(a,b){return","==a?p(x):E(a,b,!1)}function E(a,b,c){var d=0==c?D:E,e=0==c?x:y;return"=>"==a?p(r,c?I:H,s):"operator"==a?/\+\+|--/.test(b)?p(d):"?"==b?p(x,v(":"),e):p(e):"quasi"==a?o(F,d):";"!=a?"("==a?S(y,")","call",d):"."==a?p(N,d):"["==a?p(t("]"),B,v("]"),u,d):void 0:void 0}function F(a,b){return"quasi"!=a?o():"${"!=b.slice(b.length-2)?p(F):p(x,G)}function G(a){if("}"==a)return Ka.marked="string-2",Ka.state.tokenize=j,p(F)}function H(a){return k(Ka.stream,Ka.state),o("{"==a?w:x)}function I(a){return k(Ka.stream,Ka.state),o("{"==a?w:y)}function J(a){return function(b){return"."==b?p(a?L:K):o(a?y:x)}}function K(a,b){if("target"==b)return Ka.marked="keyword",p(D)}function L(a,b){if("target"==b)return Ka.marked="keyword",p(E)}function M(a){return":"==a?p(u,w):o(D,v(";"),u)}function N(a){if("variable"==a)return Ka.marked="property",p()}function O(a,b){return"async"==a?(Ka.marked="property",p(O)):"variable"==a||"keyword"==Ka.style?(Ka.marked="property",p("get"==b||"set"==b?P:Q)):"number"==a||"string"==a?(Ka.marked=Ba?"property":Ka.style+" property",p(Q)):"jsonld-keyword"==a?p(Q):"modifier"==a?p(O):"["==a?p(x,v("]"),Q):"spread"==a?p(x):":"==a?o(Q):void 0}function P(a){return"variable"!=a?o(Q):(Ka.marked="property",p(ja))}function Q(a){return":"==a?p(y):"("==a?o(ja):void 0}function R(a,b){function c(d,e){if(","==d){var f=Ka.state.lexical;return"call"==f.info&&(f.pos=(f.pos||0)+1),p((function(c,d){return c==b||d==b?o():o(a)}),c)}return d==b||e==b?p():p(v(b))}return function(d,e){return d==b||e==b?p():o(a,c)}}function S(a,b,c){for(var d=3;d"==a)return p(V)}function X(a){return"variable"==a||"keyword"==Ka.style?(Ka.marked="property",p(X)):":"==a?p(V):void 0}function Y(a){return"variable"==a?p(Y):":"==a?p(V):void 0}function Z(a,b){return"<"==b?p(R(V,">"),Z):"["==a?p(v("]"),Z):void 0}function $(){return o(_,U,ba,ca)}function _(a,b){return"modifier"==a?p(_):"variable"==a?(q(b),p()):"spread"==a?p(_):"["==a?S(_,"]"):"{"==a?S(aa,"}"):void 0}function aa(a,b){return"variable"!=a||Ka.stream.match(/^\s*:/,!1)?("variable"==a&&(Ka.marked="property"),"spread"==a?p(_):"}"==a?o():p(v(":"),_,ba)):(q(b),p(ba))}function ba(a,b){if("="==b)return p(y)}function ca(a){if(","==a)return p($)}function da(a,b){if("keyword b"==a&&"else"==b)return p(t("form","else"),w,u)}function ea(a){if("("==a)return p(t(")"),fa,v(")"),u)}function fa(a){return"var"==a?p($,v(";"),ha):";"==a?p(ha):"variable"==a?p(ga):o(x,v(";"),ha)}function ga(a,b){return"in"==b||"of"==b?(Ka.marked="keyword",p(x)):p(D,ha)}function ha(a,b){return";"==a?p(ia):"in"==b||"of"==b?(Ka.marked="keyword",p(x)):o(x,v(";"),ia)}function ia(a){")"!=a&&p(x)}function ja(a,b){return"*"==b?(Ka.marked="keyword",p(ja)):"variable"==a?(q(b),p(ja)):"("==a?p(r,t(")"),R(ka,")"),u,U,w,s):void 0}function ka(a){return"spread"==a?p(ka):o(_,U,ba)}function la(a,b){return"variable"==a?ma(a,b):na(a,b)}function ma(a,b){if("variable"==a)return q(b),p(na)}function na(a,b){return"extends"==b||"implements"==b?p(Da?V:x,na):"{"==a?p(t("}"),oa,u):void 0}function oa(a,b){return"variable"==a||"keyword"==Ka.style?("static"==b||"get"==b||"set"==b||Da&&("public"==b||"private"==b||"protected"==b||"readonly"==b||"abstract"==b))&&Ka.stream.match(/^\s+[\w$\xa1-\uffff]/,!1)?(Ka.marked="keyword",p(oa)):(Ka.marked="property",p(Da?pa:ja,oa)):"*"==b?(Ka.marked="keyword",p(oa)):";"==a?p(oa):"}"==a?p():void 0}function pa(a,b){return"?"==b?p(pa):":"==a?p(V,ba):o(ja)}function qa(a,b){return"*"==b?(Ka.marked="keyword",p(ua,v(";"))):"default"==b?(Ka.marked="keyword",p(x,v(";"))):o(w)}function ra(a){return"string"==a?p():o(sa,ua)}function sa(a,b){return"{"==a?S(sa,"}"):("variable"==a&&q(b),"*"==b&&(Ka.marked="keyword"),p(ta))}function ta(a,b){if("as"==b)return Ka.marked="keyword",p(sa)}function ua(a,b){if("from"==b)return Ka.marked="keyword",p(x)}function va(a){return"]"==a?p():o(R(y,"]"))}function wa(a,b){return"operator"==a.lastType||","==a.lastType||Ga.test(b.charAt(0))||/[,.]/.test(b.charAt(0))}var xa,ya,za=c.indentUnit,Aa=d.statementIndent,Ba=d.jsonld,Ca=d.json||Ba,Da=d.typescript,Ea=d.wordCharacters||/[\w$\xa1-\uffff]/,Fa=(function(){function a(a){return{type:a,style:"keyword"}}var b=a("keyword a"),c=a("keyword b"),d=a("keyword c"),e=a("operator"),f={type:"atom",style:"atom"},g={if:a("if"),while:b,with:b,else:c,do:c,try:c,finally:c,return:d,break:d,continue:d,new:a("new"),delete:d,throw:d,debugger:d,var:a("var"),const:a("var"),let:a("var"),function:a("function"),catch:a("catch"),for:a("for"),switch:a("switch"),case:a("case"),default:a("default"),in:e,typeof:e,instanceof:e,true:f,false:f,null:f,undefined:f,NaN:f,Infinity:f,this:a("this"),class:a("class"),super:a("atom"),yield:d,export:a("export"),import:a("import"),extends:d,await:d,async:a("async")};if(Da){var h={type:"variable",style:"variable-3"},i={interface:a("class"),implements:d,namespace:d,module:a("module"),enum:a("module"),type:a("type"),public:a("modifier"),private:a("modifier"),protected:a("modifier"),abstract:a("modifier"),as:e,string:h,number:h,boolean:h,any:h};for(var j in i)g[j]=i[j]}return g})(),Ga=/[+\-*&%=<>!?|~^]/,Ha=/^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/,Ia="([{}])",Ja={atom:!0,number:!0,variable:!0,string:!0,regexp:!0,this:!0,"jsonld-keyword":!0},Ka={state:null,column:null,marked:null,cc:null},La={name:"this",next:{name:"arguments"}};return u.lex=!0,{startState:function(a){var b={tokenize:g,lastType:"sof",cc:[],lexical:new l((a||0)-za,0,"block",!1),localVars:d.localVars,context:d.localVars&&{vars:d.localVars},indented:a||0};return d.globalVars&&"object"==typeof d.globalVars&&(b.globalVars=d.globalVars),b},token:function(a,b){if(a.sol()&&(b.lexical.hasOwnProperty("align")||(b.lexical.align=!1),b.indented=a.indentation(),k(a,b)),b.tokenize!=i&&a.eatSpace())return null;var c=b.tokenize(a,b);return"comment"==xa?c:(b.lastType="operator"!=xa||"++"!=ya&&"--"!=ya?xa:"incdec",n(b,c,xa,ya,a))},indent:function(b,c){if(b.tokenize==i)return a.Pass;if(b.tokenize!=g)return 0;var e,f=c&&c.charAt(0),h=b.lexical;if(!/^\s*else\b/.test(c))for(var j=b.cc.length-1;j>=0;--j){var k=b.cc[j];if(k==u)h=h.prev;else if(k!=da)break}for(;("stat"==h.type||"form"==h.type)&&("}"==f||(e=b.cc[b.cc.length-1])&&(e==D||e==E)&&!/^[,\.=+\-*:?[\(]/.test(c));)h=h.prev;Aa&&")"==h.type&&"stat"==h.prev.type&&(h=h.prev);var l=h.type,m=f==l;return"vardef"==l?h.indented+("operator"==b.lastType||","==b.lastType?h.info+1:0):"form"==l&&"{"==f?h.indented:"form"==l?h.indented+za:"stat"==l?h.indented+(wa(b,c)?Aa||za:0):"switch"!=h.info||m||0==d.doubleIndentSwitch?h.align?h.column+(m?0:1):h.indented+(m?0:za):h.indented+(/^(?:case|default)\b/.test(c)?za:2*za)},electricInput:/^\s*(?:case .*?:|default:|\{|\})$/,blockCommentStart:Ca?null:"/*",blockCommentEnd:Ca?null:"*/",lineComment:Ca?null:"//",fold:"brace",closeBrackets:"()[]{}''\"\"``",helperType:Ca?"json":"javascript",jsonldMode:Ba,jsonMode:Ca,expressionAllowed:b,skipExpression:function(a){var b=a.cc[a.cc.length-1];b!=x&&b!=y||a.cc.pop()}}})),a.registerHelper("wordChars","javascript",/[\w$]/),a.defineMIME("text/javascript","javascript"),a.defineMIME("text/ecmascript","javascript"),a.defineMIME("application/javascript","javascript"),a.defineMIME("application/x-javascript","javascript"),a.defineMIME("application/ecmascript","javascript"),a.defineMIME("application/json",{name:"javascript",json:!0}),a.defineMIME("application/x-json",{name:"javascript",json:!0}),a.defineMIME("application/ld+json",{name:"javascript",jsonld:!0}),a.defineMIME("text/typescript",{name:"javascript",typescript:!0}),a.defineMIME("application/typescript",{name:"javascript",typescript:!0})})); \ No newline at end of file diff --git a/media/editors/codemirror/mode/markdown/markdown.js b/media/editors/codemirror/mode/markdown/markdown.js index 9dd44574fc33d..3dcce8d3b1e66 100644 --- a/media/editors/codemirror/mode/markdown/markdown.js +++ b/media/editors/codemirror/mode/markdown/markdown.js @@ -809,6 +809,7 @@ CodeMirror.defineMode("markdown", function(cmCfg, modeCfg) { getType: getType, + closeBrackets: "()[]{}''\"\"``", fold: "markdown" }; return mode; diff --git a/media/editors/codemirror/mode/markdown/markdown.min.js b/media/editors/codemirror/mode/markdown/markdown.min.js index 1b2df6f1c4394..3e962f615953c 100644 --- a/media/editors/codemirror/mode/markdown/markdown.min.js +++ b/media/editors/codemirror/mode/markdown/markdown.min.js @@ -1 +1 @@ -!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror"),require("../xml/xml"),require("../meta")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","../xml/xml","../meta"],a):a(CodeMirror)})((function(a){"use strict";a.defineMode("markdown",(function(b,c){function d(c){if(a.findModeByName){var d=a.findModeByName(c);d&&(c=d.mime||d.mimes[0])}var e=a.getMode(b,c);return"null"==e.name?null:e}function e(a,b,c){return b.f=b.inline=c,c(a,b)}function f(a,b,c){return b.f=b.block=c,c(a,b)}function g(a){return!a||!/\S/.test(a.string)}function h(a){return a.linkTitle=!1,a.em=!1,a.strong=!1,a.strikethrough=!1,a.quote=0,a.indentedCode=!1,w&&a.f==j&&(a.f=o,a.block=i),a.trailingSpace=0,a.trailingSpaceNewLine=!1,a.prevLine=a.thisLine,a.thisLine=null,null}function i(b,f){var h=b.sol(),i=f.list!==!1,j=f.indentedCode;f.indentedCode=!1,i&&(f.indentationDiff>=0?(f.indentationDiff<4&&(f.indentation-=f.indentationDiff),f.list=null):f.indentation>0?f.list=null:f.list=!1);var l=null;if(f.indentationDiff>=4)return b.skipToEnd(),j||g(f.prevLine)?(f.indentation-=4,f.indentedCode=!0,x.code):null;if(b.eatSpace())return null;if((l=b.match(D))&&l[1].length<=6)return f.header=l[1].length,c.highlightFormatting&&(f.formatting="header"),f.f=f.inline,m(f);if(!(g(f.prevLine)||f.quote||i||j)&&(l=b.match(E)))return f.header="="==l[0].charAt(0)?1:2,c.highlightFormatting&&(f.formatting="header"),f.f=f.inline,m(f);if(b.eat(">"))return f.quote=h?1:f.quote+1,c.highlightFormatting&&(f.formatting="quote"),b.eatSpace(),m(f);if("["===b.peek())return e(b,f,s);if(b.match(z,!0))return f.hr=!0,x.hr;if((g(f.prevLine)||i)&&(b.match(A,!1)||b.match(B,!1))){var n=null;for(b.match(A,!0)?n="ul":(b.match(B,!0),n="ol"),f.indentation=b.column()+b.current().length,f.list=!0;f.listStack&&b.column()")>-1)&&(c.f=o,c.block=i,c.htmlState=null)}return d}function k(a,b){return b.fencedChars&&a.match(b.fencedChars,!1)?(b.localMode=b.localState=null,b.f=b.block=l,null):b.localMode?b.localMode.token(a,b.localState):(a.skipToEnd(),x.code)}function l(a,b){a.match(b.fencedChars),b.block=i,b.f=o,b.fencedChars=null,c.highlightFormatting&&(b.formatting="code-block"),b.code=1;var d=m(b);return b.code=0,d}function m(a){var b=[];if(a.formatting){b.push(x.formatting),"string"==typeof a.formatting&&(a.formatting=[a.formatting]);for(var d=0;d=a.quote?b.push(x.formatting+"-"+a.formatting[d]+"-"+a.quote):b.push("error"))}if(a.taskOpen)return b.push("meta"),b.length?b.join(" "):null;if(a.taskClosed)return b.push("property"),b.length?b.join(" "):null;if(a.linkHref?b.push(x.linkHref,"url"):(a.strong&&b.push(x.strong),a.em&&b.push(x.em),a.strikethrough&&b.push(x.strikethrough),a.linkText&&b.push(x.linkText),a.code&&b.push(x.code),a.image&&b.push(x.image),a.imageAltText&&b.push(x.imageAltText,"link"),a.imageMarker&&b.push(x.imageMarker)),a.header&&b.push(x.header,x.header+"-"+a.header),a.quote&&(b.push(x.quote),!c.maxBlockquoteDepth||c.maxBlockquoteDepth>=a.quote?b.push(x.quote+"-"+a.quote):b.push(x.quote+"-"+c.maxBlockquoteDepth)),a.list!==!1){var e=(a.listStack.length-1)%3;e?1===e?b.push(x.list2):b.push(x.list3):b.push(x.list1)}return a.trailingSpaceNewLine?b.push("trailing-space-new-line"):a.trailingSpace&&b.push("trailing-space-"+(a.trailingSpace%2?"a":"b")),b.length?b.join(" "):null}function n(a,b){if(a.match(F,!0))return m(b)}function o(b,d){var e=d.text(b,d);if("undefined"!=typeof e)return e;if(d.list)return d.list=null,m(d);if(d.taskList){var g="x"!==b.match(C,!0)[1];return g?d.taskOpen=!0:d.taskClosed=!0,c.highlightFormatting&&(d.formatting="task"),d.taskList=!1,m(d)}if(d.taskOpen=!1,d.taskClosed=!1,d.header&&b.match(/^#+$/,!0))return c.highlightFormatting&&(d.formatting="header"),m(d);var h=b.sol(),i=b.next();if(d.linkTitle){d.linkTitle=!1;var k=i;"("===i&&(k=")"),k=(k+"").replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1");var l="^\\s*(?:[^"+k+"\\\\]+|\\\\\\\\|\\\\.)"+k;if(b.match(new RegExp(l),!0))return x.linkHref}if("`"===i){var n=d.formatting;c.highlightFormatting&&(d.formatting="code"),b.eatWhile("`");var o=b.current().length;if(0==d.code)return d.code=o,m(d);if(o==d.code){var r=m(d);return d.code=0,r}return d.formatting=n,m(d)}if(d.code)return m(d);if("\\"===i&&(b.next(),c.highlightFormatting)){var s=m(d),t=x.formatting+"-escape";return s?s+" "+t:t}if("!"===i&&b.match(/\[[^\]]*\] ?(?:\(|\[)/,!1))return d.imageMarker=!0,d.image=!0,c.highlightFormatting&&(d.formatting="image"),m(d);if("["===i&&d.imageMarker)return d.imageMarker=!1,d.imageAltText=!0,c.highlightFormatting&&(d.formatting="image"),m(d);if("]"===i&&d.imageAltText){c.highlightFormatting&&(d.formatting="image");var s=m(d);return d.imageAltText=!1,d.image=!1,d.inline=d.f=q,s}if("["===i&&b.match(/[^\]]*\](\(.*\)| ?\[.*?\])/,!1)&&!d.image)return d.linkText=!0,c.highlightFormatting&&(d.formatting="link"),m(d);if("]"===i&&d.linkText&&b.match(/\(.*?\)| ?\[.*?\]/,!1)){c.highlightFormatting&&(d.formatting="link");var s=m(d);return d.linkText=!1,d.inline=d.f=q,s}if("<"===i&&b.match(/^(https?|ftps?):\/\/(?:[^\\>]|\\.)+>/,!1)){d.f=d.inline=p,c.highlightFormatting&&(d.formatting="link");var s=m(d);return s?s+=" ":s="",s+x.linkInline}if("<"===i&&b.match(/^[^> \\]+@(?:[^\\>]|\\.)+>/,!1)){d.f=d.inline=p,c.highlightFormatting&&(d.formatting="link");var s=m(d);return s?s+=" ":s="",s+x.linkEmail}if("<"===i&&b.match(/^(!--|\w)/,!1)){var u=b.string.indexOf(">",b.pos);if(u!=-1){var w=b.string.substring(b.start,u);/markdown\s*=\s*('|"){0,1}1('|"){0,1}/.test(w)&&(d.md_inside=!0)}return b.backUp(1),d.htmlState=a.startState(v),f(b,d,j)}if("<"===i&&b.match(/^\/\w*?>/))return d.md_inside=!1,"tag";var y=!1;if(!c.underscoresBreakWords&&"_"===i&&"_"!==b.peek()&&b.match(/(\w)/,!1)){var z=b.pos-2;if(z>=0){var A=b.string.charAt(z);"_"!==A&&A.match(/(\w)/,!1)&&(y=!0)}}if("*"===i||"_"===i&&!y)if(h&&" "===b.peek());else{if(d.strong===i&&b.eat(i)){c.highlightFormatting&&(d.formatting="strong");var r=m(d);return d.strong=!1,r}if(!d.strong&&b.eat(i))return d.strong=i,c.highlightFormatting&&(d.formatting="strong"),m(d);if(d.em===i){c.highlightFormatting&&(d.formatting="em");var r=m(d);return d.em=!1,r}if(!d.em)return d.em=i,c.highlightFormatting&&(d.formatting="em"),m(d)}else if(" "===i&&(b.eat("*")||b.eat("_"))){if(" "===b.peek())return m(d);b.backUp(1)}if(c.strikethrough)if("~"===i&&b.eatWhile(i)){if(d.strikethrough){c.highlightFormatting&&(d.formatting="strikethrough");var r=m(d);return d.strikethrough=!1,r}if(b.match(/^[^\s]/,!1))return d.strikethrough=!0,c.highlightFormatting&&(d.formatting="strikethrough"),m(d)}else if(" "===i&&b.match(/^~~/,!0)){if(" "===b.peek())return m(d);b.backUp(2)}return" "===i&&(b.match(/ +$/,!1)?d.trailingSpace++:d.trailingSpace&&(d.trailingSpaceNewLine=!0)),m(d)}function p(a,b){var d=a.next();if(">"===d){b.f=b.inline=o,c.highlightFormatting&&(b.formatting="link");var e=m(b);return e?e+=" ":e="",e+x.linkInline}return a.match(/^[^>]+/,!0),x.linkInline}function q(a,b){if(a.eatSpace())return null;var d=a.next();return"("===d||"["===d?(b.f=b.inline=r("("===d?")":"]",0),c.highlightFormatting&&(b.formatting="link-string"),b.linkHref=!0,m(b)):"error"}function r(a){return function(b,d){var e=b.next();if(e===a){d.f=d.inline=o,c.highlightFormatting&&(d.formatting="link-string");var f=m(d);return d.linkHref=!1,f}return b.match(H[a]),d.linkHref=!0,m(d)}}function s(a,b){return a.match(/^([^\]\\]|\\.)*\]:/,!1)?(b.f=t,a.next(),c.highlightFormatting&&(b.formatting="link"),b.linkText=!0,m(b)):e(a,b,o)}function t(a,b){if(a.match(/^\]:/,!0)){b.f=b.inline=u,c.highlightFormatting&&(b.formatting="link");var d=m(b);return b.linkText=!1,d}return a.match(/^([^\]\\]|\\.)+/,!0),x.linkText}function u(a,b){return a.eatSpace()?null:(a.match(/^[^\s]+/,!0),void 0===a.peek()?b.linkTitle=!0:a.match(/^(?:\s+(?:"(?:[^"\\]|\\\\|\\.)+"|'(?:[^'\\]|\\\\|\\.)+'|\((?:[^)\\]|\\\\|\\.)+\)))?/,!0),b.f=b.inline=o,x.linkHref+" url")}var v=a.getMode(b,"text/html"),w="null"==v.name;void 0===c.highlightFormatting&&(c.highlightFormatting=!1),void 0===c.maxBlockquoteDepth&&(c.maxBlockquoteDepth=0),void 0===c.underscoresBreakWords&&(c.underscoresBreakWords=!0),void 0===c.taskLists&&(c.taskLists=!1),void 0===c.strikethrough&&(c.strikethrough=!1),void 0===c.tokenTypeOverrides&&(c.tokenTypeOverrides={});var x={header:"header",code:"comment",quote:"quote",list1:"variable-2",list2:"variable-3",list3:"keyword",hr:"hr",image:"image",imageAltText:"image-alt-text",imageMarker:"image-marker",formatting:"formatting",linkInline:"link",linkEmail:"link",linkText:"link",linkHref:"string",em:"em",strong:"strong",strikethrough:"strikethrough"};for(var y in x)x.hasOwnProperty(y)&&c.tokenTypeOverrides[y]&&(x[y]=c.tokenTypeOverrides[y]);var z=/^([*\-_])(?:\s*\1){2,}\s*$/,A=/^[*\-+]\s+/,B=/^[0-9]+([.)])\s+/,C=/^\[(x| )\](?=\s)/,D=c.allowAtxHeaderWithoutSpace?/^(#+)/:/^(#+)(?: |$)/,E=/^ *(?:\={1,}|-{1,})\s*$/,F=/^[^#!\[\]*_\\<>` "'(~]+/,G=new RegExp("^("+(c.fencedCodeBlocks===!0?"~~~+|```+":c.fencedCodeBlocks)+")[ \\t]*([\\w+#-]*)"),H={")":/^(?:[^\\\(\)]|\\.|\((?:[^\\\(\)]|\\.)*\))*?(?=\))/,"]":/^(?:[^\\\[\]]|\\.|\[(?:[^\\\[\\]]|\\.)*\])*?(?=\])/},I={startState:function(){return{f:i,prevLine:null,thisLine:null,block:i,htmlState:null,indentation:0,inline:o,text:n,formatting:!1,linkText:!1,linkHref:!1,linkTitle:!1,code:0,em:!1,strong:!1,header:0,hr:!1,taskList:!1,list:!1,listStack:[],quote:0,trailingSpace:0,trailingSpaceNewLine:!1,strikethrough:!1,fencedChars:null}},copyState:function(b){return{f:b.f,prevLine:b.prevLine,thisLine:b.thisLine,block:b.block,htmlState:b.htmlState&&a.copyState(v,b.htmlState),indentation:b.indentation,localMode:b.localMode,localState:b.localMode?a.copyState(b.localMode,b.localState):null,inline:b.inline,text:b.text,formatting:!1,linkTitle:b.linkTitle,code:b.code,em:b.em,strong:b.strong,strikethrough:b.strikethrough,header:b.header,hr:b.hr,taskList:b.taskList,list:b.list,listStack:b.listStack.slice(0),quote:b.quote,indentedCode:b.indentedCode,trailingSpace:b.trailingSpace,trailingSpaceNewLine:b.trailingSpaceNewLine,md_inside:b.md_inside,fencedChars:b.fencedChars}},token:function(a,b){if(b.formatting=!1,a!=b.thisLine){var c=b.header||b.hr;if(b.header=0,b.hr=!1,a.match(/^\s*$/,!0)||c){if(h(b),!c)return null;b.prevLine=null}b.prevLine=b.thisLine,b.thisLine=a,b.taskList=!1,b.trailingSpace=0,b.trailingSpaceNewLine=!1,b.f=b.block;var d=a.match(/^\s*/,!0)[0].replace(/\t/g," ").length;if(b.indentationDiff=Math.min(d-b.indentation,4),b.indentation=b.indentation+b.indentationDiff,d>0)return null}return b.f(a,b)},innerMode:function(a){return a.block==j?{state:a.htmlState,mode:v}:a.localState?{state:a.localState,mode:a.localMode}:{state:a,mode:I}},blankLine:h,getType:m,fold:"markdown"};return I}),"xml"),a.defineMIME("text/x-markdown","markdown")})); \ No newline at end of file +!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror"),require("../xml/xml"),require("../meta")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","../xml/xml","../meta"],a):a(CodeMirror)})((function(a){"use strict";a.defineMode("markdown",(function(b,c){function d(c){if(a.findModeByName){var d=a.findModeByName(c);d&&(c=d.mime||d.mimes[0])}var e=a.getMode(b,c);return"null"==e.name?null:e}function e(a,b,c){return b.f=b.inline=c,c(a,b)}function f(a,b,c){return b.f=b.block=c,c(a,b)}function g(a){return!a||!/\S/.test(a.string)}function h(a){return a.linkTitle=!1,a.em=!1,a.strong=!1,a.strikethrough=!1,a.quote=0,a.indentedCode=!1,w&&a.f==j&&(a.f=o,a.block=i),a.trailingSpace=0,a.trailingSpaceNewLine=!1,a.prevLine=a.thisLine,a.thisLine=null,null}function i(b,f){var h=b.sol(),i=f.list!==!1,j=f.indentedCode;f.indentedCode=!1,i&&(f.indentationDiff>=0?(f.indentationDiff<4&&(f.indentation-=f.indentationDiff),f.list=null):f.indentation>0?f.list=null:f.list=!1);var l=null;if(f.indentationDiff>=4)return b.skipToEnd(),j||g(f.prevLine)?(f.indentation-=4,f.indentedCode=!0,x.code):null;if(b.eatSpace())return null;if((l=b.match(D))&&l[1].length<=6)return f.header=l[1].length,c.highlightFormatting&&(f.formatting="header"),f.f=f.inline,m(f);if(!(g(f.prevLine)||f.quote||i||j)&&(l=b.match(E)))return f.header="="==l[0].charAt(0)?1:2,c.highlightFormatting&&(f.formatting="header"),f.f=f.inline,m(f);if(b.eat(">"))return f.quote=h?1:f.quote+1,c.highlightFormatting&&(f.formatting="quote"),b.eatSpace(),m(f);if("["===b.peek())return e(b,f,s);if(b.match(z,!0))return f.hr=!0,x.hr;if((g(f.prevLine)||i)&&(b.match(A,!1)||b.match(B,!1))){var n=null;for(b.match(A,!0)?n="ul":(b.match(B,!0),n="ol"),f.indentation=b.column()+b.current().length,f.list=!0;f.listStack&&b.column()")>-1)&&(c.f=o,c.block=i,c.htmlState=null)}return d}function k(a,b){return b.fencedChars&&a.match(b.fencedChars,!1)?(b.localMode=b.localState=null,b.f=b.block=l,null):b.localMode?b.localMode.token(a,b.localState):(a.skipToEnd(),x.code)}function l(a,b){a.match(b.fencedChars),b.block=i,b.f=o,b.fencedChars=null,c.highlightFormatting&&(b.formatting="code-block"),b.code=1;var d=m(b);return b.code=0,d}function m(a){var b=[];if(a.formatting){b.push(x.formatting),"string"==typeof a.formatting&&(a.formatting=[a.formatting]);for(var d=0;d=a.quote?b.push(x.formatting+"-"+a.formatting[d]+"-"+a.quote):b.push("error"))}if(a.taskOpen)return b.push("meta"),b.length?b.join(" "):null;if(a.taskClosed)return b.push("property"),b.length?b.join(" "):null;if(a.linkHref?b.push(x.linkHref,"url"):(a.strong&&b.push(x.strong),a.em&&b.push(x.em),a.strikethrough&&b.push(x.strikethrough),a.linkText&&b.push(x.linkText),a.code&&b.push(x.code),a.image&&b.push(x.image),a.imageAltText&&b.push(x.imageAltText,"link"),a.imageMarker&&b.push(x.imageMarker)),a.header&&b.push(x.header,x.header+"-"+a.header),a.quote&&(b.push(x.quote),!c.maxBlockquoteDepth||c.maxBlockquoteDepth>=a.quote?b.push(x.quote+"-"+a.quote):b.push(x.quote+"-"+c.maxBlockquoteDepth)),a.list!==!1){var e=(a.listStack.length-1)%3;e?1===e?b.push(x.list2):b.push(x.list3):b.push(x.list1)}return a.trailingSpaceNewLine?b.push("trailing-space-new-line"):a.trailingSpace&&b.push("trailing-space-"+(a.trailingSpace%2?"a":"b")),b.length?b.join(" "):null}function n(a,b){if(a.match(F,!0))return m(b)}function o(b,d){var e=d.text(b,d);if("undefined"!=typeof e)return e;if(d.list)return d.list=null,m(d);if(d.taskList){var g="x"!==b.match(C,!0)[1];return g?d.taskOpen=!0:d.taskClosed=!0,c.highlightFormatting&&(d.formatting="task"),d.taskList=!1,m(d)}if(d.taskOpen=!1,d.taskClosed=!1,d.header&&b.match(/^#+$/,!0))return c.highlightFormatting&&(d.formatting="header"),m(d);var h=b.sol(),i=b.next();if(d.linkTitle){d.linkTitle=!1;var k=i;"("===i&&(k=")"),k=(k+"").replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1");var l="^\\s*(?:[^"+k+"\\\\]+|\\\\\\\\|\\\\.)"+k;if(b.match(new RegExp(l),!0))return x.linkHref}if("`"===i){var n=d.formatting;c.highlightFormatting&&(d.formatting="code"),b.eatWhile("`");var o=b.current().length;if(0==d.code)return d.code=o,m(d);if(o==d.code){var r=m(d);return d.code=0,r}return d.formatting=n,m(d)}if(d.code)return m(d);if("\\"===i&&(b.next(),c.highlightFormatting)){var s=m(d),t=x.formatting+"-escape";return s?s+" "+t:t}if("!"===i&&b.match(/\[[^\]]*\] ?(?:\(|\[)/,!1))return d.imageMarker=!0,d.image=!0,c.highlightFormatting&&(d.formatting="image"),m(d);if("["===i&&d.imageMarker)return d.imageMarker=!1,d.imageAltText=!0,c.highlightFormatting&&(d.formatting="image"),m(d);if("]"===i&&d.imageAltText){c.highlightFormatting&&(d.formatting="image");var s=m(d);return d.imageAltText=!1,d.image=!1,d.inline=d.f=q,s}if("["===i&&b.match(/[^\]]*\](\(.*\)| ?\[.*?\])/,!1)&&!d.image)return d.linkText=!0,c.highlightFormatting&&(d.formatting="link"),m(d);if("]"===i&&d.linkText&&b.match(/\(.*?\)| ?\[.*?\]/,!1)){c.highlightFormatting&&(d.formatting="link");var s=m(d);return d.linkText=!1,d.inline=d.f=q,s}if("<"===i&&b.match(/^(https?|ftps?):\/\/(?:[^\\>]|\\.)+>/,!1)){d.f=d.inline=p,c.highlightFormatting&&(d.formatting="link");var s=m(d);return s?s+=" ":s="",s+x.linkInline}if("<"===i&&b.match(/^[^> \\]+@(?:[^\\>]|\\.)+>/,!1)){d.f=d.inline=p,c.highlightFormatting&&(d.formatting="link");var s=m(d);return s?s+=" ":s="",s+x.linkEmail}if("<"===i&&b.match(/^(!--|\w)/,!1)){var u=b.string.indexOf(">",b.pos);if(u!=-1){var w=b.string.substring(b.start,u);/markdown\s*=\s*('|"){0,1}1('|"){0,1}/.test(w)&&(d.md_inside=!0)}return b.backUp(1),d.htmlState=a.startState(v),f(b,d,j)}if("<"===i&&b.match(/^\/\w*?>/))return d.md_inside=!1,"tag";var y=!1;if(!c.underscoresBreakWords&&"_"===i&&"_"!==b.peek()&&b.match(/(\w)/,!1)){var z=b.pos-2;if(z>=0){var A=b.string.charAt(z);"_"!==A&&A.match(/(\w)/,!1)&&(y=!0)}}if("*"===i||"_"===i&&!y)if(h&&" "===b.peek());else{if(d.strong===i&&b.eat(i)){c.highlightFormatting&&(d.formatting="strong");var r=m(d);return d.strong=!1,r}if(!d.strong&&b.eat(i))return d.strong=i,c.highlightFormatting&&(d.formatting="strong"),m(d);if(d.em===i){c.highlightFormatting&&(d.formatting="em");var r=m(d);return d.em=!1,r}if(!d.em)return d.em=i,c.highlightFormatting&&(d.formatting="em"),m(d)}else if(" "===i&&(b.eat("*")||b.eat("_"))){if(" "===b.peek())return m(d);b.backUp(1)}if(c.strikethrough)if("~"===i&&b.eatWhile(i)){if(d.strikethrough){c.highlightFormatting&&(d.formatting="strikethrough");var r=m(d);return d.strikethrough=!1,r}if(b.match(/^[^\s]/,!1))return d.strikethrough=!0,c.highlightFormatting&&(d.formatting="strikethrough"),m(d)}else if(" "===i&&b.match(/^~~/,!0)){if(" "===b.peek())return m(d);b.backUp(2)}return" "===i&&(b.match(/ +$/,!1)?d.trailingSpace++:d.trailingSpace&&(d.trailingSpaceNewLine=!0)),m(d)}function p(a,b){var d=a.next();if(">"===d){b.f=b.inline=o,c.highlightFormatting&&(b.formatting="link");var e=m(b);return e?e+=" ":e="",e+x.linkInline}return a.match(/^[^>]+/,!0),x.linkInline}function q(a,b){if(a.eatSpace())return null;var d=a.next();return"("===d||"["===d?(b.f=b.inline=r("("===d?")":"]",0),c.highlightFormatting&&(b.formatting="link-string"),b.linkHref=!0,m(b)):"error"}function r(a){return function(b,d){var e=b.next();if(e===a){d.f=d.inline=o,c.highlightFormatting&&(d.formatting="link-string");var f=m(d);return d.linkHref=!1,f}return b.match(H[a]),d.linkHref=!0,m(d)}}function s(a,b){return a.match(/^([^\]\\]|\\.)*\]:/,!1)?(b.f=t,a.next(),c.highlightFormatting&&(b.formatting="link"),b.linkText=!0,m(b)):e(a,b,o)}function t(a,b){if(a.match(/^\]:/,!0)){b.f=b.inline=u,c.highlightFormatting&&(b.formatting="link");var d=m(b);return b.linkText=!1,d}return a.match(/^([^\]\\]|\\.)+/,!0),x.linkText}function u(a,b){return a.eatSpace()?null:(a.match(/^[^\s]+/,!0),void 0===a.peek()?b.linkTitle=!0:a.match(/^(?:\s+(?:"(?:[^"\\]|\\\\|\\.)+"|'(?:[^'\\]|\\\\|\\.)+'|\((?:[^)\\]|\\\\|\\.)+\)))?/,!0),b.f=b.inline=o,x.linkHref+" url")}var v=a.getMode(b,"text/html"),w="null"==v.name;void 0===c.highlightFormatting&&(c.highlightFormatting=!1),void 0===c.maxBlockquoteDepth&&(c.maxBlockquoteDepth=0),void 0===c.underscoresBreakWords&&(c.underscoresBreakWords=!0),void 0===c.taskLists&&(c.taskLists=!1),void 0===c.strikethrough&&(c.strikethrough=!1),void 0===c.tokenTypeOverrides&&(c.tokenTypeOverrides={});var x={header:"header",code:"comment",quote:"quote",list1:"variable-2",list2:"variable-3",list3:"keyword",hr:"hr",image:"image",imageAltText:"image-alt-text",imageMarker:"image-marker",formatting:"formatting",linkInline:"link",linkEmail:"link",linkText:"link",linkHref:"string",em:"em",strong:"strong",strikethrough:"strikethrough"};for(var y in x)x.hasOwnProperty(y)&&c.tokenTypeOverrides[y]&&(x[y]=c.tokenTypeOverrides[y]);var z=/^([*\-_])(?:\s*\1){2,}\s*$/,A=/^[*\-+]\s+/,B=/^[0-9]+([.)])\s+/,C=/^\[(x| )\](?=\s)/,D=c.allowAtxHeaderWithoutSpace?/^(#+)/:/^(#+)(?: |$)/,E=/^ *(?:\={1,}|-{1,})\s*$/,F=/^[^#!\[\]*_\\<>` "'(~]+/,G=new RegExp("^("+(c.fencedCodeBlocks===!0?"~~~+|```+":c.fencedCodeBlocks)+")[ \\t]*([\\w+#-]*)"),H={")":/^(?:[^\\\(\)]|\\.|\((?:[^\\\(\)]|\\.)*\))*?(?=\))/,"]":/^(?:[^\\\[\]]|\\.|\[(?:[^\\\[\\]]|\\.)*\])*?(?=\])/},I={startState:function(){return{f:i,prevLine:null,thisLine:null,block:i,htmlState:null,indentation:0,inline:o,text:n,formatting:!1,linkText:!1,linkHref:!1,linkTitle:!1,code:0,em:!1,strong:!1,header:0,hr:!1,taskList:!1,list:!1,listStack:[],quote:0,trailingSpace:0,trailingSpaceNewLine:!1,strikethrough:!1,fencedChars:null}},copyState:function(b){return{f:b.f,prevLine:b.prevLine,thisLine:b.thisLine,block:b.block,htmlState:b.htmlState&&a.copyState(v,b.htmlState),indentation:b.indentation,localMode:b.localMode,localState:b.localMode?a.copyState(b.localMode,b.localState):null,inline:b.inline,text:b.text,formatting:!1,linkTitle:b.linkTitle,code:b.code,em:b.em,strong:b.strong,strikethrough:b.strikethrough,header:b.header,hr:b.hr,taskList:b.taskList,list:b.list,listStack:b.listStack.slice(0),quote:b.quote,indentedCode:b.indentedCode,trailingSpace:b.trailingSpace,trailingSpaceNewLine:b.trailingSpaceNewLine,md_inside:b.md_inside,fencedChars:b.fencedChars}},token:function(a,b){if(b.formatting=!1,a!=b.thisLine){var c=b.header||b.hr;if(b.header=0,b.hr=!1,a.match(/^\s*$/,!0)||c){if(h(b),!c)return null;b.prevLine=null}b.prevLine=b.thisLine,b.thisLine=a,b.taskList=!1,b.trailingSpace=0,b.trailingSpaceNewLine=!1,b.f=b.block;var d=a.match(/^\s*/,!0)[0].replace(/\t/g," ").length;if(b.indentationDiff=Math.min(d-b.indentation,4),b.indentation=b.indentation+b.indentationDiff,d>0)return null}return b.f(a,b)},innerMode:function(a){return a.block==j?{state:a.htmlState,mode:v}:a.localState?{state:a.localState,mode:a.localMode}:{state:a,mode:I}},blankLine:h,getType:m,closeBrackets:"()[]{}''\"\"``",fold:"markdown"};return I}),"xml"),a.defineMIME("text/x-markdown","markdown")})); \ No newline at end of file diff --git a/media/editors/codemirror/mode/meta.js b/media/editors/codemirror/mode/meta.js index 1e078eedee0b5..47e9a31ce88ee 100644 --- a/media/editors/codemirror/mode/meta.js +++ b/media/editors/codemirror/mode/meta.js @@ -131,6 +131,7 @@ {name: "Spreadsheet", mime: "text/x-spreadsheet", mode: "spreadsheet", alias: ["excel", "formula"]}, {name: "SQL", mime: "text/x-sql", mode: "sql", ext: ["sql"]}, {name: "Squirrel", mime: "text/x-squirrel", mode: "clike", ext: ["nut"]}, + {name: "Stylus", mime: "text/x-styl", mode: "stylus", ext: ["styl"]}, {name: "Swift", mime: "text/x-swift", mode: "swift", ext: ["swift"]}, {name: "sTeX", mime: "text/x-stex", mode: "stex"}, {name: "LaTeX", mime: "text/x-latex", mode: "stex", ext: ["text", "ltx"], alias: ["tex"]}, diff --git a/media/editors/codemirror/mode/meta.min.js b/media/editors/codemirror/mode/meta.min.js index cd880788490c9..74d0d083fc075 100644 --- a/media/editors/codemirror/mode/meta.min.js +++ b/media/editors/codemirror/mode/meta.min.js @@ -1 +1 @@ -!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../lib/codemirror")):"function"==typeof define&&define.amd?define(["../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";a.modeInfo=[{name:"APL",mime:"text/apl",mode:"apl",ext:["dyalog","apl"]},{name:"PGP",mimes:["application/pgp","application/pgp-keys","application/pgp-signature"],mode:"asciiarmor",ext:["pgp"]},{name:"ASN.1",mime:"text/x-ttcn-asn",mode:"asn.1",ext:["asn","asn1"]},{name:"Asterisk",mime:"text/x-asterisk",mode:"asterisk",file:/^extensions\.conf$/i},{name:"Brainfuck",mime:"text/x-brainfuck",mode:"brainfuck",ext:["b","bf"]},{name:"C",mime:"text/x-csrc",mode:"clike",ext:["c","h"]},{name:"C++",mime:"text/x-c++src",mode:"clike",ext:["cpp","c++","cc","cxx","hpp","h++","hh","hxx"],alias:["cpp"]},{name:"Cobol",mime:"text/x-cobol",mode:"cobol",ext:["cob","cpy"]},{name:"C#",mime:"text/x-csharp",mode:"clike",ext:["cs"],alias:["csharp"]},{name:"Clojure",mime:"text/x-clojure",mode:"clojure",ext:["clj","cljc","cljx"]},{name:"ClojureScript",mime:"text/x-clojurescript",mode:"clojure",ext:["cljs"]},{name:"Closure Stylesheets (GSS)",mime:"text/x-gss",mode:"css",ext:["gss"]},{name:"CMake",mime:"text/x-cmake",mode:"cmake",ext:["cmake","cmake.in"],file:/^CMakeLists.txt$/},{name:"CoffeeScript",mime:"text/x-coffeescript",mode:"coffeescript",ext:["coffee"],alias:["coffee","coffee-script"]},{name:"Common Lisp",mime:"text/x-common-lisp",mode:"commonlisp",ext:["cl","lisp","el"],alias:["lisp"]},{name:"Cypher",mime:"application/x-cypher-query",mode:"cypher",ext:["cyp","cypher"]},{name:"Cython",mime:"text/x-cython",mode:"python",ext:["pyx","pxd","pxi"]},{name:"Crystal",mime:"text/x-crystal",mode:"crystal",ext:["cr"]},{name:"CSS",mime:"text/css",mode:"css",ext:["css"]},{name:"CQL",mime:"text/x-cassandra",mode:"sql",ext:["cql"]},{name:"D",mime:"text/x-d",mode:"d",ext:["d"]},{name:"Dart",mimes:["application/dart","text/x-dart"],mode:"dart",ext:["dart"]},{name:"diff",mime:"text/x-diff",mode:"diff",ext:["diff","patch"]},{name:"Django",mime:"text/x-django",mode:"django"},{name:"Dockerfile",mime:"text/x-dockerfile",mode:"dockerfile",file:/^Dockerfile$/},{name:"DTD",mime:"application/xml-dtd",mode:"dtd",ext:["dtd"]},{name:"Dylan",mime:"text/x-dylan",mode:"dylan",ext:["dylan","dyl","intr"]},{name:"EBNF",mime:"text/x-ebnf",mode:"ebnf"},{name:"ECL",mime:"text/x-ecl",mode:"ecl",ext:["ecl"]},{name:"edn",mime:"application/edn",mode:"clojure",ext:["edn"]},{name:"Eiffel",mime:"text/x-eiffel",mode:"eiffel",ext:["e"]},{name:"Elm",mime:"text/x-elm",mode:"elm",ext:["elm"]},{name:"Embedded Javascript",mime:"application/x-ejs",mode:"htmlembedded",ext:["ejs"]},{name:"Embedded Ruby",mime:"application/x-erb",mode:"htmlembedded",ext:["erb"]},{name:"Erlang",mime:"text/x-erlang",mode:"erlang",ext:["erl"]},{name:"Factor",mime:"text/x-factor",mode:"factor",ext:["factor"]},{name:"FCL",mime:"text/x-fcl",mode:"fcl"},{name:"Forth",mime:"text/x-forth",mode:"forth",ext:["forth","fth","4th"]},{name:"Fortran",mime:"text/x-fortran",mode:"fortran",ext:["f","for","f77","f90"]},{name:"F#",mime:"text/x-fsharp",mode:"mllike",ext:["fs"],alias:["fsharp"]},{name:"Gas",mime:"text/x-gas",mode:"gas",ext:["s"]},{name:"Gherkin",mime:"text/x-feature",mode:"gherkin",ext:["feature"]},{name:"GitHub Flavored Markdown",mime:"text/x-gfm",mode:"gfm",file:/^(readme|contributing|history).md$/i},{name:"Go",mime:"text/x-go",mode:"go",ext:["go"]},{name:"Groovy",mime:"text/x-groovy",mode:"groovy",ext:["groovy","gradle"],file:/^Jenkinsfile$/},{name:"HAML",mime:"text/x-haml",mode:"haml",ext:["haml"]},{name:"Haskell",mime:"text/x-haskell",mode:"haskell",ext:["hs"]},{name:"Haskell (Literate)",mime:"text/x-literate-haskell",mode:"haskell-literate",ext:["lhs"]},{name:"Haxe",mime:"text/x-haxe",mode:"haxe",ext:["hx"]},{name:"HXML",mime:"text/x-hxml",mode:"haxe",ext:["hxml"]},{name:"ASP.NET",mime:"application/x-aspx",mode:"htmlembedded",ext:["aspx"],alias:["asp","aspx"]},{name:"HTML",mime:"text/html",mode:"htmlmixed",ext:["html","htm"],alias:["xhtml"]},{name:"HTTP",mime:"message/http",mode:"http"},{name:"IDL",mime:"text/x-idl",mode:"idl",ext:["pro"]},{name:"Pug",mime:"text/x-pug",mode:"pug",ext:["jade","pug"],alias:["jade"]},{name:"Java",mime:"text/x-java",mode:"clike",ext:["java"]},{name:"Java Server Pages",mime:"application/x-jsp",mode:"htmlembedded",ext:["jsp"],alias:["jsp"]},{name:"JavaScript",mimes:["text/javascript","text/ecmascript","application/javascript","application/x-javascript","application/ecmascript"],mode:"javascript",ext:["js"],alias:["ecmascript","js","node"]},{name:"JSON",mimes:["application/json","application/x-json"],mode:"javascript",ext:["json","map"],alias:["json5"]},{name:"JSON-LD",mime:"application/ld+json",mode:"javascript",ext:["jsonld"],alias:["jsonld"]},{name:"JSX",mime:"text/jsx",mode:"jsx",ext:["jsx"]},{name:"Jinja2",mime:"null",mode:"jinja2"},{name:"Julia",mime:"text/x-julia",mode:"julia",ext:["jl"]},{name:"Kotlin",mime:"text/x-kotlin",mode:"clike",ext:["kt"]},{name:"LESS",mime:"text/x-less",mode:"css",ext:["less"]},{name:"LiveScript",mime:"text/x-livescript",mode:"livescript",ext:["ls"],alias:["ls"]},{name:"Lua",mime:"text/x-lua",mode:"lua",ext:["lua"]},{name:"Markdown",mime:"text/x-markdown",mode:"markdown",ext:["markdown","md","mkd"]},{name:"mIRC",mime:"text/mirc",mode:"mirc"},{name:"MariaDB SQL",mime:"text/x-mariadb",mode:"sql"},{name:"Mathematica",mime:"text/x-mathematica",mode:"mathematica",ext:["m","nb"]},{name:"Modelica",mime:"text/x-modelica",mode:"modelica",ext:["mo"]},{name:"MUMPS",mime:"text/x-mumps",mode:"mumps",ext:["mps"]},{name:"MS SQL",mime:"text/x-mssql",mode:"sql"},{name:"mbox",mime:"application/mbox",mode:"mbox",ext:["mbox"]},{name:"MySQL",mime:"text/x-mysql",mode:"sql"},{name:"Nginx",mime:"text/x-nginx-conf",mode:"nginx",file:/nginx.*\.conf$/i},{name:"NSIS",mime:"text/x-nsis",mode:"nsis",ext:["nsh","nsi"]},{name:"NTriples",mime:"text/n-triples",mode:"ntriples",ext:["nt"]},{name:"Objective C",mime:"text/x-objectivec",mode:"clike",ext:["m","mm"],alias:["objective-c","objc"]},{name:"OCaml",mime:"text/x-ocaml",mode:"mllike",ext:["ml","mli","mll","mly"]},{name:"Octave",mime:"text/x-octave",mode:"octave",ext:["m"]},{name:"Oz",mime:"text/x-oz",mode:"oz",ext:["oz"]},{name:"Pascal",mime:"text/x-pascal",mode:"pascal",ext:["p","pas"]},{name:"PEG.js",mime:"null",mode:"pegjs",ext:["jsonld"]},{name:"Perl",mime:"text/x-perl",mode:"perl",ext:["pl","pm"]},{name:"PHP",mime:"application/x-httpd-php",mode:"php",ext:["php","php3","php4","php5","phtml"]},{name:"Pig",mime:"text/x-pig",mode:"pig",ext:["pig"]},{name:"Plain Text",mime:"text/plain",mode:"null",ext:["txt","text","conf","def","list","log"]},{name:"PLSQL",mime:"text/x-plsql",mode:"sql",ext:["pls"]},{name:"PowerShell",mime:"application/x-powershell",mode:"powershell",ext:["ps1","psd1","psm1"]},{name:"Properties files",mime:"text/x-properties",mode:"properties",ext:["properties","ini","in"],alias:["ini","properties"]},{name:"ProtoBuf",mime:"text/x-protobuf",mode:"protobuf",ext:["proto"]},{name:"Python",mime:"text/x-python",mode:"python",ext:["BUILD","bzl","py","pyw"],file:/^(BUCK|BUILD)$/},{name:"Puppet",mime:"text/x-puppet",mode:"puppet",ext:["pp"]},{name:"Q",mime:"text/x-q",mode:"q",ext:["q"]},{name:"R",mime:"text/x-rsrc",mode:"r",ext:["r"],alias:["rscript"]},{name:"reStructuredText",mime:"text/x-rst",mode:"rst",ext:["rst"],alias:["rst"]},{name:"RPM Changes",mime:"text/x-rpm-changes",mode:"rpm"},{name:"RPM Spec",mime:"text/x-rpm-spec",mode:"rpm",ext:["spec"]},{name:"Ruby",mime:"text/x-ruby",mode:"ruby",ext:["rb"],alias:["jruby","macruby","rake","rb","rbx"]},{name:"Rust",mime:"text/x-rustsrc",mode:"rust",ext:["rs"]},{name:"SAS",mime:"text/x-sas",mode:"sas",ext:["sas"]},{name:"Sass",mime:"text/x-sass",mode:"sass",ext:["sass"]},{name:"Scala",mime:"text/x-scala",mode:"clike",ext:["scala"]},{name:"Scheme",mime:"text/x-scheme",mode:"scheme",ext:["scm","ss"]},{name:"SCSS",mime:"text/x-scss",mode:"css",ext:["scss"]},{name:"Shell",mime:"text/x-sh",mode:"shell",ext:["sh","ksh","bash"],alias:["bash","sh","zsh"],file:/^PKGBUILD$/},{name:"Sieve",mime:"application/sieve",mode:"sieve",ext:["siv","sieve"]},{name:"Slim",mimes:["text/x-slim","application/x-slim"],mode:"slim",ext:["slim"]},{name:"Smalltalk",mime:"text/x-stsrc",mode:"smalltalk",ext:["st"]},{name:"Smarty",mime:"text/x-smarty",mode:"smarty",ext:["tpl"]},{name:"Solr",mime:"text/x-solr",mode:"solr"},{name:"Soy",mime:"text/x-soy",mode:"soy",ext:["soy"],alias:["closure template"]},{name:"SPARQL",mime:"application/sparql-query",mode:"sparql",ext:["rq","sparql"],alias:["sparul"]},{name:"Spreadsheet",mime:"text/x-spreadsheet",mode:"spreadsheet",alias:["excel","formula"]},{name:"SQL",mime:"text/x-sql",mode:"sql",ext:["sql"]},{name:"Squirrel",mime:"text/x-squirrel",mode:"clike",ext:["nut"]},{name:"Swift",mime:"text/x-swift",mode:"swift",ext:["swift"]},{name:"sTeX",mime:"text/x-stex",mode:"stex"},{name:"LaTeX",mime:"text/x-latex",mode:"stex",ext:["text","ltx"],alias:["tex"]},{name:"SystemVerilog",mime:"text/x-systemverilog",mode:"verilog",ext:["v"]},{name:"Tcl",mime:"text/x-tcl",mode:"tcl",ext:["tcl"]},{name:"Textile",mime:"text/x-textile",mode:"textile",ext:["textile"]},{name:"TiddlyWiki ",mime:"text/x-tiddlywiki",mode:"tiddlywiki"},{name:"Tiki wiki",mime:"text/tiki",mode:"tiki"},{name:"TOML",mime:"text/x-toml",mode:"toml",ext:["toml"]},{name:"Tornado",mime:"text/x-tornado",mode:"tornado"},{name:"troff",mime:"text/troff",mode:"troff",ext:["1","2","3","4","5","6","7","8","9"]},{name:"TTCN",mime:"text/x-ttcn",mode:"ttcn",ext:["ttcn","ttcn3","ttcnpp"]},{name:"TTCN_CFG",mime:"text/x-ttcn-cfg",mode:"ttcn-cfg",ext:["cfg"]},{name:"Turtle",mime:"text/turtle",mode:"turtle",ext:["ttl"]},{name:"TypeScript",mime:"application/typescript",mode:"javascript",ext:["ts"],alias:["ts"]},{name:"Twig",mime:"text/x-twig",mode:"twig"},{name:"Web IDL",mime:"text/x-webidl",mode:"webidl",ext:["webidl"]},{name:"VB.NET",mime:"text/x-vb",mode:"vb",ext:["vb"]},{name:"VBScript",mime:"text/vbscript",mode:"vbscript",ext:["vbs"]},{name:"Velocity",mime:"text/velocity",mode:"velocity",ext:["vtl"]},{name:"Verilog",mime:"text/x-verilog",mode:"verilog",ext:["v"]},{name:"VHDL",mime:"text/x-vhdl",mode:"vhdl",ext:["vhd","vhdl"]},{name:"XML",mimes:["application/xml","text/xml"],mode:"xml",ext:["xml","xsl","xsd"],alias:["rss","wsdl","xsd"]},{name:"XQuery",mime:"application/xquery",mode:"xquery",ext:["xy","xquery"]},{name:"Yacas",mime:"text/x-yacas",mode:"yacas",ext:["ys"]},{name:"YAML",mime:"text/x-yaml",mode:"yaml",ext:["yaml","yml"],alias:["yml"]},{name:"Z80",mime:"text/x-z80",mode:"z80",ext:["z80"]},{name:"mscgen",mime:"text/x-mscgen",mode:"mscgen",ext:["mscgen","mscin","msc"]},{name:"xu",mime:"text/x-xu",mode:"mscgen",ext:["xu"]},{name:"msgenny",mime:"text/x-msgenny",mode:"mscgen",ext:["msgenny"]}];for(var b=0;b-1&&b.substring(e+1,b.length);if(f)return a.findModeByExtension(f)},a.findModeByName=function(b){b=b.toLowerCase();for(var c=0;c-1&&b.substring(e+1,b.length);if(f)return a.findModeByExtension(f)},a.findModeByName=function(b){b=b.toLowerCase();for(var c=0;c!]+/, token: "operator"}, // Variable - {regex: /\$[\w]+/, token: "variable"}, + {regex: /\$\w+/, token: "variable"}, // Constant - {regex: /\${[\w]+}/,token: "variable-2"}, + {regex: /\${[\w\.:-]+}/, token: "variable-2"}, // Language String - {regex: /\$\([\w]+\)/,token: "variable-3"} + {regex: /\$\([\w\.:-]+\)/, token: "variable-3"} ], comment: [ {regex: /.*?\*\//, token: "comment", next: "start"}, diff --git a/media/editors/codemirror/mode/nsis/nsis.min.js b/media/editors/codemirror/mode/nsis/nsis.min.js index 8b6a3c164afc2..1105da25bb093 100644 --- a/media/editors/codemirror/mode/nsis/nsis.min.js +++ b/media/editors/codemirror/mode/nsis/nsis.min.js @@ -1 +1 @@ -!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror"),require("../../addon/mode/simple")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","../../addon/mode/simple"],a):a(CodeMirror)})((function(a){"use strict";a.defineSimpleMode("nsis",{start:[{regex:/(?:[+-]?)(?:0x[\d,a-f]+)|(?:0o[0-7]+)|(?:0b[0,1]+)|(?:\d+.?\d*)/,token:"number"},{regex:/"(?:[^\\"]|\\.)*"?/,token:"string"},{regex:/'(?:[^\\']|\\.)*'?/,token:"string"},{regex:/`(?:[^\\`]|\\.)*`?/,token:"string"},{regex:/(?:\!(include|addincludedir|addplugindir|appendfile|cd|delfile|echo|error|execute|packhdr|finalize|getdllversion|system|tempfile|warning|verbose|define|undef|insertmacro|makensis|searchparse|searchreplace))\b/,token:"keyword"},{regex:/(?:\!(if(?:n?def)?|ifmacron?def|macro))\b/,token:"keyword",indent:!0},{regex:/(?:\!(else|endif|macroend))\b/,token:"keyword",dedent:!0},{regex:/\b(?:Abort|AddBrandingImage|AddSize|AllowRootDirInstall|AllowSkipFiles|AutoCloseWindow|BGFont|BGGradient|BrandingText|BringToFront|Call|CallInstDLL|Caption|ChangeUI|CheckBitmap|ClearErrors|CompletedText|ComponentText|CopyFiles|CRCCheck|CreateDirectory|CreateFont|CreateShortCut|Delete|DeleteINISec|DeleteINIStr|DeleteRegKey|DeleteRegValue|DetailPrint|DetailsButtonText|DirText|DirVar|DirVerify|EnableWindow|EnumRegKey|EnumRegValue|Exch|Exec|ExecShell|ExecWait|ExpandEnvStrings|File|FileBufSize|FileClose|FileErrorText|FileOpen|FileRead|FileReadByte|FileReadUTF16LE|FileReadWord|FileWriteUTF16LE|FileSeek|FileWrite|FileWriteByte|FileWriteWord|FindClose|FindFirst|FindNext|FindWindow|FlushINI|GetCurInstType|GetCurrentAddress|GetDlgItem|GetDLLVersion|GetDLLVersionLocal|GetErrorLevel|GetFileTime|GetFileTimeLocal|GetFullPathName|GetFunctionAddress|GetInstDirError|GetLabelAddress|GetTempFileName|Goto|HideWindow|Icon|IfAbort|IfErrors|IfFileExists|IfRebootFlag|IfSilent|InitPluginsDir|InstallButtonText|InstallColors|InstallDir|InstallDirRegKey|InstProgressFlags|InstType|InstTypeGetText|InstTypeSetText|IntCmp|IntCmpU|IntFmt|IntOp|IsWindow|LangString|LicenseBkColor|LicenseData|LicenseForceSelection|LicenseLangString|LicenseText|LoadLanguageFile|LockWindow|LogSet|LogText|ManifestDPIAware|ManifestSupportedOS|MessageBox|MiscButtonText|Name|Nop|OutFile|Page|PageCallbacks|Pop|Push|Quit|ReadEnvStr|ReadINIStr|ReadRegDWORD|ReadRegStr|Reboot|RegDLL|Rename|RequestExecutionLevel|ReserveFile|Return|RMDir|SearchPath|SectionGetFlags|SectionGetInstTypes|SectionGetSize|SectionGetText|SectionIn|SectionSetFlags|SectionSetInstTypes|SectionSetSize|SectionSetText|SendMessage|SetAutoClose|SetBrandingImage|SetCompress|SetCompressor|SetCompressorDictSize|SetCtlColors|SetCurInstType|SetDatablockOptimize|SetDateSave|SetDetailsPrint|SetDetailsView|SetErrorLevel|SetErrors|SetFileAttributes|SetFont|SetOutPath|SetOverwrite|SetPluginUnload|SetRebootFlag|SetRegView|SetShellVarContext|SetSilent|ShowInstDetails|ShowUninstDetails|ShowWindow|SilentInstall|SilentUnInstall|Sleep|SpaceTexts|StrCmp|StrCmpS|StrCpy|StrLen|SubCaption|Unicode|UninstallButtonText|UninstallCaption|UninstallIcon|UninstallSubCaption|UninstallText|UninstPage|UnRegDLL|Var|VIAddVersionKey|VIFileVersion|VIProductVersion|WindowIcon|WriteINIStr|WriteRegBin|WriteRegDWORD|WriteRegExpandStr|WriteRegStr|WriteUninstaller|XPStyle)\b/,token:"keyword"},{regex:/\b(?:Function|PageEx|Section(?:Group)?)\b/,token:"keyword",indent:!0},{regex:/\b(?:(Function|PageEx|Section(?:Group)?)End)\b/,token:"keyword",dedent:!0},{regex:/\b(?:ARCHIVE|FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_NORMAL|FILE_ATTRIBUTE_OFFLINE|FILE_ATTRIBUTE_READONLY|FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_TEMPORARY|HIDDEN|HKCC|HKCR|HKCU|HKDD|HKEY_CLASSES_ROOT|HKEY_CURRENT_CONFIG|HKEY_CURRENT_USER|HKEY_DYN_DATA|HKEY_LOCAL_MACHINE|HKEY_PERFORMANCE_DATA|HKEY_USERS|HKLM|HKPD|HKU|IDABORT|IDCANCEL|IDD_DIR|IDD_INST|IDD_INSTFILES|IDD_LICENSE|IDD_SELCOM|IDD_UNINST|IDD_VERIFY|IDIGNORE|IDNO|IDOK|IDRETRY|IDYES|MB_ABORTRETRYIGNORE|MB_DEFBUTTON1|MB_DEFBUTTON2|MB_DEFBUTTON3|MB_DEFBUTTON4|MB_ICONEXCLAMATION|MB_ICONINFORMATION|MB_ICONQUESTION|MB_ICONSTOP|MB_OK|MB_OKCANCEL|MB_RETRYCANCEL|MB_RIGHT|MB_RTLREADING|MB_SETFOREGROUND|MB_TOPMOST|MB_USERICON|MB_YESNO|MB_YESNOCANCEL|NORMAL|OFFLINE|READONLY|SHCTX|SHELL_CONTEXT|SW_HIDE|SW_SHOWDEFAULT|SW_SHOWMAXIMIZED|SW_SHOWMINIMIZED|SW_SHOWNORMAL|SYSTEM|TEMPORARY)\b/,token:"atom"},{regex:/\b(?:admin|all|auto|both|bottom|bzip2|components|current|custom|directory|force|hide|highest|ifdiff|ifnewer|instfiles|lastused|leave|left|license|listonly|lzma|nevershow|none|normal|notset|right|show|silent|silentlog|textonly|top|try|un\.components|un\.custom|un\.directory|un\.instfiles|un\.license|uninstConfirm|user|Win10|Win7|Win8|WinVista|zlib)\b/,token:"builtin"},{regex:/\$\{(?:And(?:If(?:Not)?|Unless)|Break|Case(?:Else)?|Continue|Default|Do(?:Until|While)?|Else(?:If(?:Not)?|Unless)?|End(?:If|Select|Switch)|Exit(?:Do|For|While)|For(?:Each)?|If(?:Cmd|Not(?:Then)?|Then)?|Loop(?:Until|While)?|Or(?:If(?:Not)?|Unless)|Select|Switch|Unless|While)\}/,token:"variable-2",indent:!0},{regex:/\$\{(?:BannerTrimPath|DirState|DriveSpace|Get(BaseName|Drives|ExeName|ExePath|FileAttributes|FileExt|FileName|FileVersion|Options|OptionsS|Parameters|Parent|Root|Size|Time)|Locate|RefreshShellIcons)\}/,token:"variable-2",dedent:!0},{regex:/\$\{(?:Memento(?:Section(?:Done|End|Restore|Save)?|UnselectedSection))\}/,token:"variable-2",dedent:!0},{regex:/\$\{(?:Config(?:Read|ReadS|Write|WriteS)|File(?:Join|ReadFromEnd|Recode)|Line(?:Find|Read|Sum)|Text(?:Compare|CompareS)|TrimNewLines)\}/,token:"variable-2",dedent:!0},{regex:/\$\{(?:(?:At(?:Least|Most)|Is)(?:ServicePack|Win(?:7|8|10|95|98|200(?:0|3|8(?:R2)?)|ME|NT4|Vista|XP))|Is(?:NT|Server))\}/,token:"variable",dedent:!0},{regex:/\$\{(?:StrFilterS?|Version(?:Compare|Convert)|Word(?:AddS?|Find(?:(?:2|3)X)?S?|InsertS?|ReplaceS?))\}/,token:"variable-2",dedent:!0},{regex:/\$\{(?:RunningX64)\}/,token:"variable",dedent:!0},{regex:/\$\{(?:Disable|Enable)X64FSRedirection\}/,token:"variable-2",dedent:!0},{regex:/(#|;).*/,token:"comment"},{regex:/\/\*/,token:"comment",next:"comment"},{regex:/[-+\/*=<>!]+/,token:"operator"},{regex:/\$[\w]+/,token:"variable"},{regex:/\${[\w]+}/,token:"variable-2"},{regex:/\$\([\w]+\)/,token:"variable-3"}],comment:[{regex:/.*?\*\//,token:"comment",next:"start"},{regex:/.*/,token:"comment"}],meta:{electricInput:/^\s*((Function|PageEx|Section|Section(Group)?)End|(\!(endif|macroend))|\$\{(End(If|Unless|While)|Loop(Until)|Next)\})$/,blockCommentStart:"/*",blockCommentEnd:"*/",lineComment:["#",";"]}}),a.defineMIME("text/x-nsis","nsis")})); \ No newline at end of file +!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror"),require("../../addon/mode/simple")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","../../addon/mode/simple"],a):a(CodeMirror)})((function(a){"use strict";a.defineSimpleMode("nsis",{start:[{regex:/(?:[+-]?)(?:0x[\d,a-f]+)|(?:0o[0-7]+)|(?:0b[0,1]+)|(?:\d+.?\d*)/,token:"number"},{regex:/"(?:[^\\"]|\\.)*"?/,token:"string"},{regex:/'(?:[^\\']|\\.)*'?/,token:"string"},{regex:/`(?:[^\\`]|\\.)*`?/,token:"string"},{regex:/^\s*(?:\!(include|addincludedir|addplugindir|appendfile|cd|delfile|echo|error|execute|packhdr|finalize|getdllversion|system|tempfile|warning|verbose|define|undef|insertmacro|makensis|searchparse|searchreplace))\b/,token:"keyword"},{regex:/^\s*(?:\!(if(?:n?def)?|ifmacron?def|macro))\b/,token:"keyword",indent:!0},{regex:/^\s*(?:\!(else|endif|macroend))\b/,token:"keyword",dedent:!0},{regex:/^\s*(?:Abort|AddBrandingImage|AddSize|AllowRootDirInstall|AllowSkipFiles|AutoCloseWindow|BGFont|BGGradient|BrandingText|BringToFront|Call|CallInstDLL|Caption|ChangeUI|CheckBitmap|ClearErrors|CompletedText|ComponentText|CopyFiles|CRCCheck|CreateDirectory|CreateFont|CreateShortCut|Delete|DeleteINISec|DeleteINIStr|DeleteRegKey|DeleteRegValue|DetailPrint|DetailsButtonText|DirText|DirVar|DirVerify|EnableWindow|EnumRegKey|EnumRegValue|Exch|Exec|ExecShell|ExecWait|ExpandEnvStrings|File|FileBufSize|FileClose|FileErrorText|FileOpen|FileRead|FileReadByte|FileReadUTF16LE|FileReadWord|FileWriteUTF16LE|FileSeek|FileWrite|FileWriteByte|FileWriteWord|FindClose|FindFirst|FindNext|FindWindow|FlushINI|GetCurInstType|GetCurrentAddress|GetDlgItem|GetDLLVersion|GetDLLVersionLocal|GetErrorLevel|GetFileTime|GetFileTimeLocal|GetFullPathName|GetFunctionAddress|GetInstDirError|GetLabelAddress|GetTempFileName|Goto|HideWindow|Icon|IfAbort|IfErrors|IfFileExists|IfRebootFlag|IfSilent|InitPluginsDir|InstallButtonText|InstallColors|InstallDir|InstallDirRegKey|InstProgressFlags|InstType|InstTypeGetText|InstTypeSetText|IntCmp|IntCmpU|IntFmt|IntOp|IsWindow|LangString|LicenseBkColor|LicenseData|LicenseForceSelection|LicenseLangString|LicenseText|LoadLanguageFile|LockWindow|LogSet|LogText|ManifestDPIAware|ManifestSupportedOS|MessageBox|MiscButtonText|Name|Nop|OutFile|Page|PageCallbacks|Pop|Push|Quit|ReadEnvStr|ReadINIStr|ReadRegDWORD|ReadRegStr|Reboot|RegDLL|Rename|RequestExecutionLevel|ReserveFile|Return|RMDir|SearchPath|SectionGetFlags|SectionGetInstTypes|SectionGetSize|SectionGetText|SectionIn|SectionSetFlags|SectionSetInstTypes|SectionSetSize|SectionSetText|SendMessage|SetAutoClose|SetBrandingImage|SetCompress|SetCompressor|SetCompressorDictSize|SetCtlColors|SetCurInstType|SetDatablockOptimize|SetDateSave|SetDetailsPrint|SetDetailsView|SetErrorLevel|SetErrors|SetFileAttributes|SetFont|SetOutPath|SetOverwrite|SetRebootFlag|SetRegView|SetShellVarContext|SetSilent|ShowInstDetails|ShowUninstDetails|ShowWindow|SilentInstall|SilentUnInstall|Sleep|SpaceTexts|StrCmp|StrCmpS|StrCpy|StrLen|SubCaption|Unicode|UninstallButtonText|UninstallCaption|UninstallIcon|UninstallSubCaption|UninstallText|UninstPage|UnRegDLL|Var|VIAddVersionKey|VIFileVersion|VIProductVersion|WindowIcon|WriteINIStr|WriteRegBin|WriteRegDWORD|WriteRegExpandStr|WriteRegStr|WriteUninstaller|XPStyle)\b/,token:"keyword"},{regex:/^\s*(?:Function|PageEx|Section(?:Group)?)\b/,token:"keyword",indent:!0},{regex:/^\s*(?:(Function|PageEx|Section(?:Group)?)End)\b/,token:"keyword",dedent:!0},{regex:/\b(?:ARCHIVE|FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_NORMAL|FILE_ATTRIBUTE_OFFLINE|FILE_ATTRIBUTE_READONLY|FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_TEMPORARY|HIDDEN|HKCC|HKCR|HKCU|HKDD|HKEY_CLASSES_ROOT|HKEY_CURRENT_CONFIG|HKEY_CURRENT_USER|HKEY_DYN_DATA|HKEY_LOCAL_MACHINE|HKEY_PERFORMANCE_DATA|HKEY_USERS|HKLM|HKPD|HKU|IDABORT|IDCANCEL|IDD_DIR|IDD_INST|IDD_INSTFILES|IDD_LICENSE|IDD_SELCOM|IDD_UNINST|IDD_VERIFY|IDIGNORE|IDNO|IDOK|IDRETRY|IDYES|MB_ABORTRETRYIGNORE|MB_DEFBUTTON1|MB_DEFBUTTON2|MB_DEFBUTTON3|MB_DEFBUTTON4|MB_ICONEXCLAMATION|MB_ICONINFORMATION|MB_ICONQUESTION|MB_ICONSTOP|MB_OK|MB_OKCANCEL|MB_RETRYCANCEL|MB_RIGHT|MB_RTLREADING|MB_SETFOREGROUND|MB_TOPMOST|MB_USERICON|MB_YESNO|MB_YESNOCANCEL|NORMAL|OFFLINE|READONLY|SHCTX|SHELL_CONTEXT|SW_HIDE|SW_SHOWDEFAULT|SW_SHOWMAXIMIZED|SW_SHOWMINIMIZED|SW_SHOWNORMAL|SYSTEM|TEMPORARY)\b/,token:"atom"},{regex:/\b(?:admin|all|auto|both|bottom|bzip2|components|current|custom|directory|force|hide|highest|ifdiff|ifnewer|instfiles|lastused|leave|left|license|listonly|lzma|nevershow|none|normal|notset|right|show|silent|silentlog|textonly|top|try|un\.components|un\.custom|un\.directory|un\.instfiles|un\.license|uninstConfirm|user|Win10|Win7|Win8|WinVista|zlib)\b/,token:"builtin"},{regex:/\$\{(?:And(?:If(?:Not)?|Unless)|Break|Case(?:Else)?|Continue|Default|Do(?:Until|While)?|Else(?:If(?:Not)?|Unless)?|End(?:If|Select|Switch)|Exit(?:Do|For|While)|For(?:Each)?|If(?:Cmd|Not(?:Then)?|Then)?|Loop(?:Until|While)?|Or(?:If(?:Not)?|Unless)|Select|Switch|Unless|While)\}/,token:"variable-2",indent:!0},{regex:/\$\{(?:BannerTrimPath|DirState|DriveSpace|Get(BaseName|Drives|ExeName|ExePath|FileAttributes|FileExt|FileName|FileVersion|Options|OptionsS|Parameters|Parent|Root|Size|Time)|Locate|RefreshShellIcons)\}/,token:"variable-2",dedent:!0},{regex:/\$\{(?:Memento(?:Section(?:Done|End|Restore|Save)?|UnselectedSection))\}/,token:"variable-2",dedent:!0},{regex:/\$\{(?:Config(?:Read|ReadS|Write|WriteS)|File(?:Join|ReadFromEnd|Recode)|Line(?:Find|Read|Sum)|Text(?:Compare|CompareS)|TrimNewLines)\}/,token:"variable-2",dedent:!0},{regex:/\$\{(?:(?:At(?:Least|Most)|Is)(?:ServicePack|Win(?:7|8|10|95|98|200(?:0|3|8(?:R2)?)|ME|NT4|Vista|XP))|Is(?:NT|Server))\}/,token:"variable",dedent:!0},{regex:/\$\{(?:StrFilterS?|Version(?:Compare|Convert)|Word(?:AddS?|Find(?:(?:2|3)X)?S?|InsertS?|ReplaceS?))\}/,token:"variable-2",dedent:!0},{regex:/\$\{(?:RunningX64)\}/,token:"variable",dedent:!0},{regex:/\$\{(?:Disable|Enable)X64FSRedirection\}/,token:"variable-2",dedent:!0},{regex:/(#|;).*/,token:"comment"},{regex:/\/\*/,token:"comment",next:"comment"},{regex:/[-+\/*=<>!]+/,token:"operator"},{regex:/\$\w+/,token:"variable"},{regex:/\${[\w\.:-]+}/,token:"variable-2"},{regex:/\$\([\w\.:-]+\)/,token:"variable-3"}],comment:[{regex:/.*?\*\//,token:"comment",next:"start"},{regex:/.*/,token:"comment"}],meta:{electricInput:/^\s*((Function|PageEx|Section|Section(Group)?)End|(\!(endif|macroend))|\$\{(End(If|Unless|While)|Loop(Until)|Next)\})$/,blockCommentStart:"/*",blockCommentEnd:"*/",lineComment:["#",";"]}}),a.defineMIME("text/x-nsis","nsis")})); \ No newline at end of file diff --git a/media/editors/codemirror/mode/python/python.js b/media/editors/codemirror/mode/python/python.js index efeed7f15434c..30f1428e3aa48 100644 --- a/media/editors/codemirror/mode/python/python.js +++ b/media/editors/codemirror/mode/python/python.js @@ -85,7 +85,7 @@ var lineOffset = stream.indentation(); if (lineOffset > scopeOffset) pushPyScope(state); - else if (lineOffset < scopeOffset && dedent(stream, state)) + else if (lineOffset < scopeOffset && dedent(stream, state) && stream.peek() != "#") state.errorToken = true; return null; } else { diff --git a/media/editors/codemirror/mode/python/python.min.js b/media/editors/codemirror/mode/python/python.min.js index 960d451e01fbd..582dca9cb546a 100644 --- a/media/editors/codemirror/mode/python/python.min.js +++ b/media/editors/codemirror/mode/python/python.min.js @@ -1 +1 @@ -!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";function b(a){return new RegExp("^(("+a.join(")|(")+"))\\b")}function c(a){return a.scopes[a.scopes.length-1]}var d=b(["and","or","not","is"]),e=["as","assert","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","lambda","pass","raise","return","try","while","with","yield","in"],f=["abs","all","any","bin","bool","bytearray","callable","chr","classmethod","compile","complex","delattr","dict","dir","divmod","enumerate","eval","filter","float","format","frozenset","getattr","globals","hasattr","hash","help","hex","id","input","int","isinstance","issubclass","iter","len","list","locals","map","max","memoryview","min","next","object","oct","open","ord","pow","property","range","repr","reversed","round","set","setattr","slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip","__import__","NotImplemented","Ellipsis","__debug__"];a.registerHelper("hintWords","python",e.concat(f)),a.defineMode("python",(function(g,h){function i(a,b){if(a.sol()&&(b.indent=a.indentation()),a.sol()&&"py"==c(b).type){var d=c(b).offset;if(a.eatSpace()){var e=a.indentation();return e>d?l(b):e0&&n(a,b)&&(f+=" "+p),f}return j(a,b)}function j(a,b){if(a.eatSpace())return null;var c=a.peek();if("#"==c)return a.skipToEnd(),"comment";if(a.match(/^[0-9\.]/,!1)){var e=!1;if(a.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)&&(e=!0),a.match(/^\d+\.\d*/)&&(e=!0),a.match(/^\.\d+/)&&(e=!0),e)return a.eat(/J/i),"number";var f=!1;if(a.match(/^0x[0-9a-f]+/i)&&(f=!0),a.match(/^0b[01]+/i)&&(f=!0),a.match(/^0o[0-7]+/i)&&(f=!0),a.match(/^[1-9]\d*(e[\+\-]?\d+)?/)&&(a.eat(/J/i),f=!0),a.match(/^0(?![\dx])/i)&&(f=!0),f)return a.eat(/L/i),"number"}return a.match(A)?(b.tokenize=k(a.current()),b.tokenize(a,b)):a.match(t)||a.match(s)?"punctuation":a.match(r)||a.match(y)?"operator":a.match(q)?"punctuation":"."==b.lastToken&&a.match(z)?"property":a.match(B)||a.match(d)?"keyword":a.match(C)?"builtin":a.match(/^(self|cls)\b/)?"variable-2":a.match(z)?"def"==b.lastToken||"class"==b.lastToken?"def":"variable":(a.next(),p)}function k(a){function b(b,e){for(;!b.eol();)if(b.eatWhile(/[^'"\\]/),b.eat("\\")){if(b.next(),c&&b.eol())return d}else{if(b.match(a))return e.tokenize=i,d;b.eat(/['"]/)}if(c){if(h.singleLineStringErrors)return p;e.tokenize=i}return d}for(;"rubf".indexOf(a.charAt(0).toLowerCase())>=0;)a=a.substr(1);var c=1==a.length,d="string";return b.isString=!0,b}function l(a){for(;"py"!=c(a).type;)a.scopes.pop();a.scopes.push({offset:c(a).offset+g.indentUnit,type:"py",align:null})}function m(a,b,c){var d=a.match(/^([\s\[\{\(]|#.*)*$/,!1)?null:a.column()+1;b.scopes.push({offset:b.indent+u,type:c,align:d})}function n(a,b){for(var d=a.indentation();b.scopes.length>1&&c(b).offset>d;){if("py"!=c(b).type)return!0;b.scopes.pop()}return c(b).offset!=d}function o(a,b){a.sol()&&(b.beginningOfLine=!0);var d=b.tokenize(a,b),e=a.current();if(b.beginningOfLine&&"@"==e)return a.match(z,!1)?"meta":x?"operator":p;/\S/.test(e)&&(b.beginningOfLine=!1),"variable"!=d&&"builtin"!=d||"meta"!=b.lastToken||(d="meta"),"pass"!=e&&"return"!=e||(b.dedent+=1),"lambda"==e&&(b.lambda=!0),":"!=e||b.lambda||"py"!=c(b).type||l(b);var f=1==e.length?"[({".indexOf(e):-1;if(f!=-1&&m(a,b,"])}".slice(f,f+1)),f="])}".indexOf(e),f!=-1){if(c(b).type!=e)return p;b.indent=b.scopes.pop().offset-u}return b.dedent>0&&a.eol()&&"py"==c(b).type&&(b.scopes.length>1&&b.scopes.pop(),b.dedent-=1),d}var p="error",q=h.singleDelimiters||/^[\(\)\[\]\{\}@,:`=;\.]/,r=h.doubleOperators||/^([!<>]==|<>|<<|>>|\/\/|\*\*)/,s=h.doubleDelimiters||/^(\+=|\-=|\*=|%=|\/=|&=|\|=|\^=)/,t=h.tripleDelimiters||/^(\/\/=|>>=|<<=|\*\*=)/,u=h.hangingIndent||g.indentUnit,v=e,w=f;void 0!=h.extra_keywords&&(v=v.concat(h.extra_keywords)),void 0!=h.extra_builtins&&(w=w.concat(h.extra_builtins));var x=!(h.version&&Number(h.version)<3);if(x){var y=h.singleOperators||/^[\+\-\*\/%&|\^~<>!@]/,z=h.identifiers||/^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*/;v=v.concat(["nonlocal","False","True","None","async","await"]),w=w.concat(["ascii","bytes","exec","print"]);var A=new RegExp("^(([rbuf]|(br))?('{3}|\"{3}|['\"]))","i")}else{var y=h.singleOperators||/^[\+\-\*\/%&|\^~<>!]/,z=h.identifiers||/^[_A-Za-z][_A-Za-z0-9]*/;v=v.concat(["exec","print"]),w=w.concat(["apply","basestring","buffer","cmp","coerce","execfile","file","intern","long","raw_input","reduce","reload","unichr","unicode","xrange","False","True","None"]);var A=new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))","i")}var B=b(v),C=b(w),D={startState:function(a){return{tokenize:i,scopes:[{offset:a||0,type:"py",align:null}],indent:a||0,lastToken:null,lambda:!1,dedent:0}},token:function(a,b){var c=b.errorToken;c&&(b.errorToken=!1);var d=o(a,b);return d&&"comment"!=d&&(b.lastToken="keyword"==d||"punctuation"==d?a.current():d),"punctuation"==d&&(d=null),a.eol()&&b.lambda&&(b.lambda=!1),c?d+" "+p:d},indent:function(b,d){if(b.tokenize!=i)return b.tokenize.isString?a.Pass:0;var e=c(b),f=e.type==d.charAt(0);return null!=e.align?e.align-(f?1:0):e.offset-(f?u:0)},electricInput:/^\s*[\}\]\)]$/,closeBrackets:{triples:"'\""},lineComment:"#",fold:"indent"};return D})),a.defineMIME("text/x-python","python");var g=function(a){return a.split(" ")};a.defineMIME("text/x-cython",{name:"python",extra_keywords:g("by cdef cimport cpdef ctypedef enum exceptextern gil include nogil property publicreadonly struct union DEF IF ELIF ELSE")})})); \ No newline at end of file +!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";function b(a){return new RegExp("^(("+a.join(")|(")+"))\\b")}function c(a){return a.scopes[a.scopes.length-1]}var d=b(["and","or","not","is"]),e=["as","assert","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","lambda","pass","raise","return","try","while","with","yield","in"],f=["abs","all","any","bin","bool","bytearray","callable","chr","classmethod","compile","complex","delattr","dict","dir","divmod","enumerate","eval","filter","float","format","frozenset","getattr","globals","hasattr","hash","help","hex","id","input","int","isinstance","issubclass","iter","len","list","locals","map","max","memoryview","min","next","object","oct","open","ord","pow","property","range","repr","reversed","round","set","setattr","slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip","__import__","NotImplemented","Ellipsis","__debug__"];a.registerHelper("hintWords","python",e.concat(f)),a.defineMode("python",(function(g,h){function i(a,b){if(a.sol()&&(b.indent=a.indentation()),a.sol()&&"py"==c(b).type){var d=c(b).offset;if(a.eatSpace()){var e=a.indentation();return e>d?l(b):e0&&n(a,b)&&(f+=" "+p),f}return j(a,b)}function j(a,b){if(a.eatSpace())return null;var c=a.peek();if("#"==c)return a.skipToEnd(),"comment";if(a.match(/^[0-9\.]/,!1)){var e=!1;if(a.match(/^\d*\.\d+(e[\+\-]?\d+)?/i)&&(e=!0),a.match(/^\d+\.\d*/)&&(e=!0),a.match(/^\.\d+/)&&(e=!0),e)return a.eat(/J/i),"number";var f=!1;if(a.match(/^0x[0-9a-f]+/i)&&(f=!0),a.match(/^0b[01]+/i)&&(f=!0),a.match(/^0o[0-7]+/i)&&(f=!0),a.match(/^[1-9]\d*(e[\+\-]?\d+)?/)&&(a.eat(/J/i),f=!0),a.match(/^0(?![\dx])/i)&&(f=!0),f)return a.eat(/L/i),"number"}return a.match(A)?(b.tokenize=k(a.current()),b.tokenize(a,b)):a.match(t)||a.match(s)?"punctuation":a.match(r)||a.match(y)?"operator":a.match(q)?"punctuation":"."==b.lastToken&&a.match(z)?"property":a.match(B)||a.match(d)?"keyword":a.match(C)?"builtin":a.match(/^(self|cls)\b/)?"variable-2":a.match(z)?"def"==b.lastToken||"class"==b.lastToken?"def":"variable":(a.next(),p)}function k(a){function b(b,e){for(;!b.eol();)if(b.eatWhile(/[^'"\\]/),b.eat("\\")){if(b.next(),c&&b.eol())return d}else{if(b.match(a))return e.tokenize=i,d;b.eat(/['"]/)}if(c){if(h.singleLineStringErrors)return p;e.tokenize=i}return d}for(;"rubf".indexOf(a.charAt(0).toLowerCase())>=0;)a=a.substr(1);var c=1==a.length,d="string";return b.isString=!0,b}function l(a){for(;"py"!=c(a).type;)a.scopes.pop();a.scopes.push({offset:c(a).offset+g.indentUnit,type:"py",align:null})}function m(a,b,c){var d=a.match(/^([\s\[\{\(]|#.*)*$/,!1)?null:a.column()+1;b.scopes.push({offset:b.indent+u,type:c,align:d})}function n(a,b){for(var d=a.indentation();b.scopes.length>1&&c(b).offset>d;){if("py"!=c(b).type)return!0;b.scopes.pop()}return c(b).offset!=d}function o(a,b){a.sol()&&(b.beginningOfLine=!0);var d=b.tokenize(a,b),e=a.current();if(b.beginningOfLine&&"@"==e)return a.match(z,!1)?"meta":x?"operator":p;/\S/.test(e)&&(b.beginningOfLine=!1),"variable"!=d&&"builtin"!=d||"meta"!=b.lastToken||(d="meta"),"pass"!=e&&"return"!=e||(b.dedent+=1),"lambda"==e&&(b.lambda=!0),":"!=e||b.lambda||"py"!=c(b).type||l(b);var f=1==e.length?"[({".indexOf(e):-1;if(f!=-1&&m(a,b,"])}".slice(f,f+1)),f="])}".indexOf(e),f!=-1){if(c(b).type!=e)return p;b.indent=b.scopes.pop().offset-u}return b.dedent>0&&a.eol()&&"py"==c(b).type&&(b.scopes.length>1&&b.scopes.pop(),b.dedent-=1),d}var p="error",q=h.singleDelimiters||/^[\(\)\[\]\{\}@,:`=;\.]/,r=h.doubleOperators||/^([!<>]==|<>|<<|>>|\/\/|\*\*)/,s=h.doubleDelimiters||/^(\+=|\-=|\*=|%=|\/=|&=|\|=|\^=)/,t=h.tripleDelimiters||/^(\/\/=|>>=|<<=|\*\*=)/,u=h.hangingIndent||g.indentUnit,v=e,w=f;void 0!=h.extra_keywords&&(v=v.concat(h.extra_keywords)),void 0!=h.extra_builtins&&(w=w.concat(h.extra_builtins));var x=!(h.version&&Number(h.version)<3);if(x){var y=h.singleOperators||/^[\+\-\*\/%&|\^~<>!@]/,z=h.identifiers||/^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*/;v=v.concat(["nonlocal","False","True","None","async","await"]),w=w.concat(["ascii","bytes","exec","print"]);var A=new RegExp("^(([rbuf]|(br))?('{3}|\"{3}|['\"]))","i")}else{var y=h.singleOperators||/^[\+\-\*\/%&|\^~<>!]/,z=h.identifiers||/^[_A-Za-z][_A-Za-z0-9]*/;v=v.concat(["exec","print"]),w=w.concat(["apply","basestring","buffer","cmp","coerce","execfile","file","intern","long","raw_input","reduce","reload","unichr","unicode","xrange","False","True","None"]);var A=new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))","i")}var B=b(v),C=b(w),D={startState:function(a){return{tokenize:i,scopes:[{offset:a||0,type:"py",align:null}],indent:a||0,lastToken:null,lambda:!1,dedent:0}},token:function(a,b){var c=b.errorToken;c&&(b.errorToken=!1);var d=o(a,b);return d&&"comment"!=d&&(b.lastToken="keyword"==d||"punctuation"==d?a.current():d),"punctuation"==d&&(d=null),a.eol()&&b.lambda&&(b.lambda=!1),c?d+" "+p:d},indent:function(b,d){if(b.tokenize!=i)return b.tokenize.isString?a.Pass:0;var e=c(b),f=e.type==d.charAt(0);return null!=e.align?e.align-(f?1:0):e.offset-(f?u:0)},electricInput:/^\s*[\}\]\)]$/,closeBrackets:{triples:"'\""},lineComment:"#",fold:"indent"};return D})),a.defineMIME("text/x-python","python");var g=function(a){return a.split(" ")};a.defineMIME("text/x-cython",{name:"python",extra_keywords:g("by cdef cimport cpdef ctypedef enum exceptextern gil include nogil property publicreadonly struct union DEF IF ELIF ELSE")})})); \ No newline at end of file diff --git a/media/editors/codemirror/mode/r/r.js b/media/editors/codemirror/mode/r/r.js index d41d1c54c1335..7e15beac629f7 100644 --- a/media/editors/codemirror/mode/r/r.js +++ b/media/editors/codemirror/mode/r/r.js @@ -44,6 +44,9 @@ CodeMirror.defineMode("r", function(config) { } else if (ch == "'" || ch == '"') { state.tokenize = tokenString(ch); return "string"; + } else if (ch == "`") { + stream.match(/[^`]+`/); + return "variable-3"; } else if (ch == "." && stream.match(/.[.\d]+/)) { return "keyword"; } else if (/[\w\.]/.test(ch) && ch != "_") { @@ -62,13 +65,17 @@ CodeMirror.defineMode("r", function(config) { return "variable"; } else if (ch == "%") { if (stream.skipTo("%")) stream.next(); - return "variable-2"; - } else if (ch == "<" && stream.eat("-")) { - return "arrow"; + return "operator variable-2"; + } else if ( + (ch == "<" && stream.eat("-")) || + (ch == "<" && stream.match("<-")) || + (ch == "-" && stream.match(/>>?/)) + ) { + return "operator arrow"; } else if (ch == "=" && state.ctx.argList) { return "arg-is"; } else if (opChars.test(ch)) { - if (ch == "$") return "dollar"; + if (ch == "$") return "operator dollar"; stream.eatWhile(opChars); return "operator"; } else if (/[\(\){}\[\];]/.test(ch)) { diff --git a/media/editors/codemirror/mode/r/r.min.js b/media/editors/codemirror/mode/r/r.min.js index 57df35d0a6fe0..26a5df58165ea 100644 --- a/media/editors/codemirror/mode/r/r.min.js +++ b/media/editors/codemirror/mode/r/r.min.js @@ -1 +1 @@ -!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";a.registerHelper("wordChars","r",/[\w.]/),a.defineMode("r",(function(a){function b(a){for(var b=a.split(" "),c={},d=0;d=!&|~$:]/;return{startState:function(){return{tokenize:c,ctx:{type:"top",indent:-a.indentUnit,align:!1},indent:0,afterIdent:!1}},token:function(a,b){if(a.sol()&&(null==b.ctx.align&&(b.ctx.align=!1),b.indent=a.indentation()),a.eatSpace())return null;var c=b.tokenize(a,b);"comment"!=c&&null==b.ctx.align&&(b.ctx.align=!0);var d=b.ctx.type;return";"!=g&&"{"!=g&&"}"!=g||"block"!=d||f(b),"{"==g?e(b,"}",a):"("==g?(e(b,")",a),b.afterIdent&&(b.ctx.argList=!0)):"["==g?e(b,"]",a):"block"==g?e(b,"block",a):g==d&&f(b),b.afterIdent="variable"==c||"keyword"==c,c},indent:function(b,d){if(b.tokenize!=c)return 0;var e=d&&d.charAt(0),f=b.ctx,g=e==f.type;return"block"==f.type?f.indent+("{"==e?0:a.indentUnit):f.align?f.column+(g?0:1):f.indent+(g?0:a.indentUnit)},lineComment:"#"}})),a.defineMIME("text/x-rsrc","r")})); \ No newline at end of file +!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";a.registerHelper("wordChars","r",/[\w.]/),a.defineMode("r",(function(a){function b(a){for(var b=a.split(" "),c={},d=0;d>?/)?"operator arrow":"="==c&&b.ctx.argList?"arg-is":l.test(c)?"$"==c?"operator dollar":(a.eatWhile(l),"operator"):/[\(\){}\[\];]/.test(c)?(g=c,";"==c?"semi":null):null}function d(a){return function(b,d){if(b.eat("\\")){var e=b.next();return"x"==e?b.match(/^[a-f0-9]{2}/i):("u"==e||"U"==e)&&b.eat("{")&&b.skipTo("}")?b.next():"u"==e?b.match(/^[a-f0-9]{4}/i):"U"==e?b.match(/^[a-f0-9]{8}/i):/[0-7]/.test(e)&&b.match(/^[0-7]{1,2}/),"string-2"}for(var f;null!=(f=b.next());){if(f==a){d.tokenize=c;break}if("\\"==f){b.backUp(1);break}}return"string"}}function e(a,b,c){a.ctx={type:b,indent:a.indent,align:null,column:c.column(),prev:a.ctx}}function f(a){a.indent=a.ctx.indent,a.ctx=a.ctx.prev}var g,h=b("NULL NA Inf NaN NA_integer_ NA_real_ NA_complex_ NA_character_"),i=b("list quote bquote eval return call parse deparse"),j=b("if else repeat while function for in next break"),k=b("if else repeat while function for"),l=/[+\-*\/^<>=!&|~$:]/;return{startState:function(){return{tokenize:c,ctx:{type:"top",indent:-a.indentUnit,align:!1},indent:0,afterIdent:!1}},token:function(a,b){if(a.sol()&&(null==b.ctx.align&&(b.ctx.align=!1),b.indent=a.indentation()),a.eatSpace())return null;var c=b.tokenize(a,b);"comment"!=c&&null==b.ctx.align&&(b.ctx.align=!0);var d=b.ctx.type;return";"!=g&&"{"!=g&&"}"!=g||"block"!=d||f(b),"{"==g?e(b,"}",a):"("==g?(e(b,")",a),b.afterIdent&&(b.ctx.argList=!0)):"["==g?e(b,"]",a):"block"==g?e(b,"block",a):g==d&&f(b),b.afterIdent="variable"==c||"keyword"==c,c},indent:function(b,d){if(b.tokenize!=c)return 0;var e=d&&d.charAt(0),f=b.ctx,g=e==f.type;return"block"==f.type?f.indent+("{"==e?0:a.indentUnit):f.align?f.column+(g?0:1):f.indent+(g?0:a.indentUnit)},lineComment:"#"}})),a.defineMIME("text/x-rsrc","r")})); \ No newline at end of file diff --git a/media/editors/codemirror/mode/rpm/changes/index.html b/media/editors/codemirror/mode/rpm/changes/index.html new file mode 100644 index 0000000000000..6e5031bd1f55f --- /dev/null +++ b/media/editors/codemirror/mode/rpm/changes/index.html @@ -0,0 +1,66 @@ + + +CodeMirror: RPM changes mode + + + + + + + + + + + +
+

RPM changes mode

+ +
+ + +

MIME types defined: text/x-rpm-changes.

+
diff --git a/media/editors/codemirror/mode/shell/shell.js b/media/editors/codemirror/mode/shell/shell.js index a684e8c233ad2..570b4e2419bdb 100644 --- a/media/editors/codemirror/mode/shell/shell.js +++ b/media/editors/codemirror/mode/shell/shell.js @@ -129,6 +129,7 @@ CodeMirror.defineMode('shell', function() { token: function(stream, state) { return tokenize(stream, state); }, + closeBrackets: "()[]{}''\"\"``", lineComment: '#', fold: "brace" }; diff --git a/media/editors/codemirror/mode/shell/shell.min.js b/media/editors/codemirror/mode/shell/shell.min.js index e88fb2142fda3..0632b2f3fa7d7 100644 --- a/media/editors/codemirror/mode/shell/shell.min.js +++ b/media/editors/codemirror/mode/shell/shell.min.js @@ -1 +1 @@ -!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";a.defineMode("shell",(function(){function a(a,b){for(var c=b.split(" "),d=0;d1&&a.eat("$");var e=a.next(),f=/\w/;return"{"===e&&(f=/[^}]/),"("===e?(b.tokens[0]=c(")"),d(a,b)):(/\d/.test(e)||(a.eatWhile(f),a.eat("}")),b.tokens.shift(),"def")};return{startState:function(){return{tokens:[]}},token:function(a,b){return d(a,b)},lineComment:"#",fold:"brace"}})),a.defineMIME("text/x-sh","shell")})); \ No newline at end of file +!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";a.defineMode("shell",(function(){function a(a,b){for(var c=b.split(" "),d=0;d1&&a.eat("$");var e=a.next(),f=/\w/;return"{"===e&&(f=/[^}]/),"("===e?(b.tokens[0]=c(")"),d(a,b)):(/\d/.test(e)||(a.eatWhile(f),a.eat("}")),b.tokens.shift(),"def")};return{startState:function(){return{tokens:[]}},token:function(a,b){return d(a,b)},closeBrackets:"()[]{}''\"\"``",lineComment:"#",fold:"brace"}})),a.defineMIME("text/x-sh","shell")})); \ No newline at end of file diff --git a/media/editors/codemirror/mode/sql/sql.js b/media/editors/codemirror/mode/sql/sql.js index 01ebd80ae1a28..e3cbae54cffa5 100644 --- a/media/editors/codemirror/mode/sql/sql.js +++ b/media/editors/codemirror/mode/sql/sql.js @@ -280,7 +280,7 @@ CodeMirror.defineMode("sql", function(config, parserConfig) { CodeMirror.defineMIME("text/x-mssql", { name: "sql", client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"), - keywords: set(sqlKeywords + "begin trigger proc view index for add constraint key primary foreign collate clustered nonclustered declare"), + keywords: set(sqlKeywords + "begin trigger proc view index for add constraint key primary foreign collate clustered nonclustered declare exec"), builtin: set("bigint numeric bit smallint decimal smallmoney int tinyint money float real char varchar text nchar nvarchar ntext binary varbinary image cursor timestamp hierarchyid uniqueidentifier sql_variant xml table "), atoms: set("false true null unknown"), operatorChars: /^[*+\-%<>!=]/, diff --git a/media/editors/codemirror/mode/sql/sql.min.js b/media/editors/codemirror/mode/sql/sql.min.js index 2803cba049d13..702058eeb7982 100644 --- a/media/editors/codemirror/mode/sql/sql.min.js +++ b/media/editors/codemirror/mode/sql/sql.min.js @@ -1 +1 @@ -!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";a.defineMode("sql",(function(b,c){function d(a,b){var c=a.next();if(o[c]){var d=o[c](a,b);if(d!==!1)return d}if(1==n.hexNumber&&("0"==c&&a.match(/^[xX][0-9a-fA-F]+/)||("x"==c||"X"==c)&&a.match(/^'[0-9a-fA-F]+'/)))return"number";if(1==n.binaryNumber&&(("b"==c||"B"==c)&&a.match(/^'[01]+'/)||"0"==c&&a.match(/^b[01]+/)))return"number";if(c.charCodeAt(0)>47&&c.charCodeAt(0)<58)return a.match(/^[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?/),1==n.decimallessFloat&&a.eat("."),"number";if("?"==c&&(a.eatSpace()||a.eol()||a.eat(";")))return"variable-3";if("'"==c||'"'==c&&n.doubleQuote)return b.tokenize=e(c),b.tokenize(a,b);if((1==n.nCharCast&&("n"==c||"N"==c)||1==n.charsetCast&&"_"==c&&a.match(/[a-z][a-z0-9]*/i))&&("'"==a.peek()||'"'==a.peek()))return"keyword";if(/^[\(\),\;\[\]]/.test(c))return null;if(n.commentSlashSlash&&"/"==c&&a.eat("/"))return a.skipToEnd(),"comment";if(n.commentHash&&"#"==c||"-"==c&&a.eat("-")&&(!n.commentSpaceRequired||a.eat(" ")))return a.skipToEnd(),"comment";if("/"==c&&a.eat("*"))return b.tokenize=f,b.tokenize(a,b);if("."!=c){if(m.test(c))return a.eatWhile(m),null;if("{"==c&&(a.match(/^( )*(d|D|t|T|ts|TS)( )*'[^']*'( )*}/)||a.match(/^( )*(d|D|t|T|ts|TS)( )*"[^"]*"( )*}/)))return"number";a.eatWhile(/^[_\w\d]/);var g=a.current().toLowerCase();return p.hasOwnProperty(g)&&(a.match(/^( )+'[^']*'/)||a.match(/^( )+"[^"]*"/))?"number":j.hasOwnProperty(g)?"atom":k.hasOwnProperty(g)?"builtin":l.hasOwnProperty(g)?"keyword":i.hasOwnProperty(g)?"string-2":null}return 1==n.zerolessFloat&&a.match(/^(?:\d+(?:e[+-]?\d+)?)/i)?"number":1==n.ODBCdotTable&&a.match(/^[a-zA-Z_]+/)?"variable-2":void 0}function e(a){return function(b,c){for(var e,f=!1;null!=(e=b.next());){if(e==a&&!f){c.tokenize=d;break}f=!f&&"\\"==e}return"string"}}function f(a,b){for(;;){if(!a.skipTo("*")){a.skipToEnd();break}if(a.next(),a.eat("/")){b.tokenize=d;break}}return"comment"}function g(a,b,c){b.context={prev:b.context,indent:a.indentation(),col:a.column(),type:c}}function h(a){a.indent=a.context.indent,a.context=a.context.prev}var i=c.client||{},j=c.atoms||{false:!0,true:!0,null:!0},k=c.builtin||{},l=c.keywords||{},m=c.operatorChars||/^[*+\-%<>!=&|~^]/,n=c.support||{},o=c.hooks||{},p=c.dateSQL||{date:!0,time:!0,timestamp:!0};return{startState:function(){return{tokenize:d,context:null}},token:function(a,b){if(a.sol()&&b.context&&null==b.context.align&&(b.context.align=!1),a.eatSpace())return null;var c=b.tokenize(a,b);if("comment"==c)return c;b.context&&null==b.context.align&&(b.context.align=!0);var d=a.current();return"("==d?g(a,b,")"):"["==d?g(a,b,"]"):b.context&&b.context.type==d&&h(b),c},indent:function(c,d){var e=c.context;if(!e)return a.Pass;var f=d.charAt(0)==e.type;return e.align?e.col+(f?0:1):e.indent+(f?0:b.indentUnit)},blockCommentStart:"/*",blockCommentEnd:"*/",lineComment:n.commentSlashSlash?"//":n.commentHash?"#":null}})),(function(){function b(a){for(var b;null!=(b=a.next());)if("`"==b&&!a.eat("`"))return"variable-2";return a.backUp(a.current().length-1),a.eatWhile(/\w/)?"variable-2":null}function c(a){return a.eat("@")&&(a.match(/^session\./),a.match(/^local\./),a.match(/^global\./)),a.eat("'")?(a.match(/^.*'/),"variable-2"):a.eat('"')?(a.match(/^.*"/),"variable-2"):a.eat("`")?(a.match(/^.*`/),"variable-2"):a.match(/^[0-9a-zA-Z$\.\_]+/)?"variable-2":null}function d(a){return a.eat("N")?"atom":a.match(/^[a-zA-Z.#!?]/)?"variable-2":null}function e(a){for(var b={},c=a.split(" "),d=0;d!=]/,dateSQL:e("date time timestamp"),support:e("ODBCdotTable doubleQuote binaryNumber hexNumber")}),a.defineMIME("text/x-mssql",{name:"sql",client:e("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),keywords:e(f+"begin trigger proc view index for add constraint key primary foreign collate clustered nonclustered declare"),builtin:e("bigint numeric bit smallint decimal smallmoney int tinyint money float real char varchar text nchar nvarchar ntext binary varbinary image cursor timestamp hierarchyid uniqueidentifier sql_variant xml table "),atoms:e("false true null unknown"),operatorChars:/^[*+\-%<>!=]/,dateSQL:e("date datetimeoffset datetime2 smalldatetime datetime time"),hooks:{"@":c}}),a.defineMIME("text/x-mysql",{name:"sql",client:e("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),keywords:e(f+"accessible action add after algorithm all analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance diagnostics directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general get global grant grants group group_concat handler hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show signal slave slow smallint snapshot soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"),builtin:e("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric"),atoms:e("false true null unknown"),operatorChars:/^[*+\-%<>!=&|^]/,dateSQL:e("date time timestamp"),support:e("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"),hooks:{"@":c,"`":b,"\\":d}}),a.defineMIME("text/x-mariadb",{name:"sql",client:e("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),keywords:e(f+"accessible action add after algorithm all always analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance diagnostics directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general generated get global grant grants group groupby_concat handler hard hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password persistent phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show shutdown signal slave slow smallint snapshot soft soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views virtual warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"),builtin:e("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric"),atoms:e("false true null unknown"),operatorChars:/^[*+\-%<>!=&|^]/,dateSQL:e("date time timestamp"),support:e("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"),hooks:{"@":c,"`":b,"\\":d}}),a.defineMIME("text/x-cassandra",{name:"sql",client:{},keywords:e("add all allow alter and any apply as asc authorize batch begin by clustering columnfamily compact consistency count create custom delete desc distinct drop each_quorum exists filtering from grant if in index insert into key keyspace keyspaces level limit local_one local_quorum modify nan norecursive nosuperuser not of on one order password permission permissions primary quorum rename revoke schema select set storage superuser table three to token truncate ttl two type unlogged update use user users using values where with writetime"),builtin:e("ascii bigint blob boolean counter decimal double float frozen inet int list map static text timestamp timeuuid tuple uuid varchar varint"),atoms:e("false true infinity NaN"),operatorChars:/^[<>=]/,dateSQL:{},support:e("commentSlashSlash decimallessFloat"),hooks:{}}),a.defineMIME("text/x-plsql",{name:"sql",client:e("appinfo arraysize autocommit autoprint autorecovery autotrace blockterminator break btitle cmdsep colsep compatibility compute concat copycommit copytypecheck define describe echo editfile embedded escape exec execute feedback flagger flush heading headsep instance linesize lno loboffset logsource long longchunksize markup native newpage numformat numwidth pagesize pause pno recsep recsepchar release repfooter repheader serveroutput shiftinout show showmode size spool sqlblanklines sqlcase sqlcode sqlcontinue sqlnumber sqlpluscompatibility sqlprefix sqlprompt sqlterminator suffix tab term termout time timing trimout trimspool ttitle underline verify version wrap"),keywords:e("abort accept access add all alter and any array arraylen as asc assert assign at attributes audit authorization avg base_table begin between binary_integer body boolean by case cast char char_base check close cluster clusters colauth column comment commit compress connect connected constant constraint crash create current currval cursor data_base database date dba deallocate debugoff debugon decimal declare default definition delay delete desc digits dispose distinct do drop else elseif elsif enable end entry escape exception exception_init exchange exclusive exists exit external fast fetch file for force form from function generic goto grant group having identified if immediate in increment index indexes indicator initial initrans insert interface intersect into is key level library like limited local lock log logging long loop master maxextents maxtrans member minextents minus mislabel mode modify multiset new next no noaudit nocompress nologging noparallel not nowait number_base object of off offline on online only open option or order out package parallel partition pctfree pctincrease pctused pls_integer positive positiven pragma primary prior private privileges procedure public raise range raw read rebuild record ref references refresh release rename replace resource restrict return returning returns reverse revoke rollback row rowid rowlabel rownum rows run savepoint schema segment select separate session set share snapshot some space split sql start statement storage subtype successful synonym tabauth table tables tablespace task terminate then to trigger truncate type union unique unlimited unrecoverable unusable update use using validate value values variable view views when whenever where while with work"),builtin:e("abs acos add_months ascii asin atan atan2 average bfile bfilename bigserial bit blob ceil character chartorowid chr clob concat convert cos cosh count dec decode deref dual dump dup_val_on_index empty error exp false float floor found glb greatest hextoraw initcap instr instrb int integer isopen last_day least length lengthb ln lower lpad ltrim lub make_ref max min mlslabel mod months_between natural naturaln nchar nclob new_time next_day nextval nls_charset_decl_len nls_charset_id nls_charset_name nls_initcap nls_lower nls_sort nls_upper nlssort no_data_found notfound null number numeric nvarchar2 nvl others power rawtohex real reftohex round rowcount rowidtochar rowtype rpad rtrim serial sign signtype sin sinh smallint soundex sqlcode sqlerrm sqrt stddev string substr substrb sum sysdate tan tanh to_char text to_date to_label to_multi_byte to_number to_single_byte translate true trunc uid unlogged upper user userenv varchar varchar2 variance varying vsize xml"),operatorChars:/^[*+\-%<>!=~]/,dateSQL:e("date time timestamp"),support:e("doubleQuote nCharCast zerolessFloat binaryNumber hexNumber")}),a.defineMIME("text/x-hive",{name:"sql",keywords:e("select alter $elem$ $key$ $value$ add after all analyze and archive as asc before between binary both bucket buckets by cascade case cast change cluster clustered clusterstatus collection column columns comment compute concatenate continue create cross cursor data database databases dbproperties deferred delete delimited desc describe directory disable distinct distribute drop else enable end escaped exclusive exists explain export extended external false fetch fields fileformat first format formatted from full function functions grant group having hold_ddltime idxproperties if import in index indexes inpath inputdriver inputformat insert intersect into is items join keys lateral left like limit lines load local location lock locks mapjoin materialized minus msck no_drop nocompress not of offline on option or order out outer outputdriver outputformat overwrite partition partitioned partitions percent plus preserve procedure purge range rcfile read readonly reads rebuild recordreader recordwriter recover reduce regexp rename repair replace restrict revoke right rlike row schema schemas semi sequencefile serde serdeproperties set shared show show_database sort sorted ssl statistics stored streamtable table tables tablesample tblproperties temporary terminated textfile then tmp to touch transform trigger true unarchive undo union uniquejoin unlock update use using utc utc_tmestamp view when where while with"),builtin:e("bool boolean long timestamp tinyint smallint bigint int float double date datetime unsigned string array struct map uniontype"),atoms:e("false true null unknown"),operatorChars:/^[*+\-%<>!=]/,dateSQL:e("date timestamp"),support:e("ODBCdotTable doubleQuote binaryNumber hexNumber")}),a.defineMIME("text/x-pgsql",{name:"sql",client:e("source"),keywords:e(f+"a abort abs absent absolute access according action ada add admin after aggregate all allocate also always analyse analyze any are array array_agg array_max_cardinality asensitive assertion assignment asymmetric at atomic attribute attributes authorization avg backward base64 before begin begin_frame begin_partition bernoulli binary bit_length blob blocked bom both breadth c cache call called cardinality cascade cascaded case cast catalog catalog_name ceil ceiling chain characteristics characters character_length character_set_catalog character_set_name character_set_schema char_length check checkpoint class class_origin clob close cluster coalesce cobol collate collation collation_catalog collation_name collation_schema collect column columns column_name command_function command_function_code comment comments commit committed concurrently condition condition_number configuration conflict connect connection connection_name constraint constraints constraint_catalog constraint_name constraint_schema constructor contains content continue control conversion convert copy corr corresponding cost covar_pop covar_samp cross csv cube cume_dist current current_catalog current_date current_default_transform_group current_path current_role current_row current_schema current_time current_timestamp current_transform_group_for_type current_user cursor cursor_name cycle data database datalink datetime_interval_code datetime_interval_precision day db deallocate dec declare default defaults deferrable deferred defined definer degree delimiter delimiters dense_rank depth deref derived describe descriptor deterministic diagnostics dictionary disable discard disconnect dispatch dlnewcopy dlpreviouscopy dlurlcomplete dlurlcompleteonly dlurlcompletewrite dlurlpath dlurlpathonly dlurlpathwrite dlurlscheme dlurlserver dlvalue do document domain dynamic dynamic_function dynamic_function_code each element else empty enable encoding encrypted end end-exec end_frame end_partition enforced enum equals escape event every except exception exclude excluding exclusive exec execute exists exp explain expression extension external extract false family fetch file filter final first first_value flag float floor following for force foreign fortran forward found frame_row free freeze fs full function functions fusion g general generated get global go goto grant granted greatest grouping groups handler header hex hierarchy hold hour id identity if ignore ilike immediate immediately immutable implementation implicit import including increment indent index indexes indicator inherit inherits initially inline inner inout input insensitive instance instantiable instead integrity intersect intersection invoker isnull isolation k key key_member key_type label lag language large last last_value lateral lead leading leakproof least left length level library like_regex link listen ln load local localtime localtimestamp location locator lock locked logged lower m map mapping match matched materialized max maxvalue max_cardinality member merge message_length message_octet_length message_text method min minute minvalue mod mode modifies module month more move multiset mumps name names namespace national natural nchar nclob nesting new next nfc nfd nfkc nfkd nil no none normalize normalized nothing notify notnull nowait nth_value ntile null nullable nullif nulls number object occurrences_regex octets octet_length of off offset oids old only open operator option options ordering ordinality others out outer output over overlaps overlay overriding owned owner p pad parameter parameter_mode parameter_name parameter_ordinal_position parameter_specific_catalog parameter_specific_name parameter_specific_schema parser partial partition pascal passing passthrough password percent percentile_cont percentile_disc percent_rank period permission placing plans pli policy portion position position_regex power precedes preceding prepare prepared preserve primary prior privileges procedural procedure program public quote range rank read reads reassign recheck recovery recursive ref references referencing refresh regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy regr_syy reindex relative release rename repeatable replace replica requiring reset respect restart restore restrict result return returned_cardinality returned_length returned_octet_length returned_sqlstate returning returns revoke right role rollback rollup routine routine_catalog routine_name routine_schema row rows row_count row_number rule savepoint scale schema schema_name scope scope_catalog scope_name scope_schema scroll search second section security selective self sensitive sequence sequences serializable server server_name session session_user setof sets share show similar simple size skip snapshot some source space specific specifictype specific_name sql sqlcode sqlerror sqlexception sqlstate sqlwarning sqrt stable standalone start state statement static statistics stddev_pop stddev_samp stdin stdout storage strict strip structure style subclass_origin submultiset substring substring_regex succeeds sum symmetric sysid system system_time system_user t tables tablesample tablespace table_name temp template temporary then ties timezone_hour timezone_minute to token top_level_count trailing transaction transactions_committed transactions_rolled_back transaction_active transform transforms translate translate_regex translation treat trigger trigger_catalog trigger_name trigger_schema trim trim_array true truncate trusted type types uescape unbounded uncommitted under unencrypted unique unknown unlink unlisten unlogged unnamed unnest until untyped upper uri usage user user_defined_type_catalog user_defined_type_code user_defined_type_name user_defined_type_schema using vacuum valid validate validator value value_of varbinary variadic var_pop var_samp verbose version versioning view views volatile when whenever whitespace width_bucket window within work wrapper write xmlagg xmlattributes xmlbinary xmlcast xmlcomment xmlconcat xmldeclaration xmldocument xmlelement xmlexists xmlforest xmliterate xmlnamespaces xmlparse xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltext xmlvalidate year yes loop repeat"),builtin:e("bigint int8 bigserial serial8 bit varying varbit boolean bool box bytea character char varchar cidr circle date double precision float8 inet integer int int4 interval json jsonb line lseg macaddr money numeric decimal path pg_lsn point polygon real float4 smallint int2 smallserial serial2 serial serial4 text time without zone with timetz timestamp timestamptz tsquery tsvector txid_snapshot uuid xml"),atoms:e("false true null unknown"),operatorChars:/^[*+\-%<>!=&|^\/#@?~]/,dateSQL:e("date time timestamp"),support:e("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber nCharCast charsetCast")}),a.defineMIME("text/x-gql",{name:"sql",keywords:e("ancestor and asc by contains desc descendant distinct from group has in is limit offset on order select superset where"),atoms:e("false true"),builtin:e("blob datetime first key __key__ string integer double boolean null"),operatorChars:/^[*+\-%<>!=]/})})()})); \ No newline at end of file +!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";a.defineMode("sql",(function(b,c){function d(a,b){var c=a.next();if(o[c]){var d=o[c](a,b);if(d!==!1)return d}if(1==n.hexNumber&&("0"==c&&a.match(/^[xX][0-9a-fA-F]+/)||("x"==c||"X"==c)&&a.match(/^'[0-9a-fA-F]+'/)))return"number";if(1==n.binaryNumber&&(("b"==c||"B"==c)&&a.match(/^'[01]+'/)||"0"==c&&a.match(/^b[01]+/)))return"number";if(c.charCodeAt(0)>47&&c.charCodeAt(0)<58)return a.match(/^[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?/),1==n.decimallessFloat&&a.eat("."),"number";if("?"==c&&(a.eatSpace()||a.eol()||a.eat(";")))return"variable-3";if("'"==c||'"'==c&&n.doubleQuote)return b.tokenize=e(c),b.tokenize(a,b);if((1==n.nCharCast&&("n"==c||"N"==c)||1==n.charsetCast&&"_"==c&&a.match(/[a-z][a-z0-9]*/i))&&("'"==a.peek()||'"'==a.peek()))return"keyword";if(/^[\(\),\;\[\]]/.test(c))return null;if(n.commentSlashSlash&&"/"==c&&a.eat("/"))return a.skipToEnd(),"comment";if(n.commentHash&&"#"==c||"-"==c&&a.eat("-")&&(!n.commentSpaceRequired||a.eat(" ")))return a.skipToEnd(),"comment";if("/"==c&&a.eat("*"))return b.tokenize=f,b.tokenize(a,b);if("."!=c){if(m.test(c))return a.eatWhile(m),null;if("{"==c&&(a.match(/^( )*(d|D|t|T|ts|TS)( )*'[^']*'( )*}/)||a.match(/^( )*(d|D|t|T|ts|TS)( )*"[^"]*"( )*}/)))return"number";a.eatWhile(/^[_\w\d]/);var g=a.current().toLowerCase();return p.hasOwnProperty(g)&&(a.match(/^( )+'[^']*'/)||a.match(/^( )+"[^"]*"/))?"number":j.hasOwnProperty(g)?"atom":k.hasOwnProperty(g)?"builtin":l.hasOwnProperty(g)?"keyword":i.hasOwnProperty(g)?"string-2":null}return 1==n.zerolessFloat&&a.match(/^(?:\d+(?:e[+-]?\d+)?)/i)?"number":1==n.ODBCdotTable&&a.match(/^[a-zA-Z_]+/)?"variable-2":void 0}function e(a){return function(b,c){for(var e,f=!1;null!=(e=b.next());){if(e==a&&!f){c.tokenize=d;break}f=!f&&"\\"==e}return"string"}}function f(a,b){for(;;){if(!a.skipTo("*")){a.skipToEnd();break}if(a.next(),a.eat("/")){b.tokenize=d;break}}return"comment"}function g(a,b,c){b.context={prev:b.context,indent:a.indentation(),col:a.column(),type:c}}function h(a){a.indent=a.context.indent,a.context=a.context.prev}var i=c.client||{},j=c.atoms||{false:!0,true:!0,null:!0},k=c.builtin||{},l=c.keywords||{},m=c.operatorChars||/^[*+\-%<>!=&|~^]/,n=c.support||{},o=c.hooks||{},p=c.dateSQL||{date:!0,time:!0,timestamp:!0};return{startState:function(){return{tokenize:d,context:null}},token:function(a,b){if(a.sol()&&b.context&&null==b.context.align&&(b.context.align=!1),a.eatSpace())return null;var c=b.tokenize(a,b);if("comment"==c)return c;b.context&&null==b.context.align&&(b.context.align=!0);var d=a.current();return"("==d?g(a,b,")"):"["==d?g(a,b,"]"):b.context&&b.context.type==d&&h(b),c},indent:function(c,d){var e=c.context;if(!e)return a.Pass;var f=d.charAt(0)==e.type;return e.align?e.col+(f?0:1):e.indent+(f?0:b.indentUnit)},blockCommentStart:"/*",blockCommentEnd:"*/",lineComment:n.commentSlashSlash?"//":n.commentHash?"#":null}})),(function(){function b(a){for(var b;null!=(b=a.next());)if("`"==b&&!a.eat("`"))return"variable-2";return a.backUp(a.current().length-1),a.eatWhile(/\w/)?"variable-2":null}function c(a){return a.eat("@")&&(a.match(/^session\./),a.match(/^local\./),a.match(/^global\./)),a.eat("'")?(a.match(/^.*'/),"variable-2"):a.eat('"')?(a.match(/^.*"/),"variable-2"):a.eat("`")?(a.match(/^.*`/),"variable-2"):a.match(/^[0-9a-zA-Z$\.\_]+/)?"variable-2":null}function d(a){return a.eat("N")?"atom":a.match(/^[a-zA-Z.#!?]/)?"variable-2":null}function e(a){for(var b={},c=a.split(" "),d=0;d!=]/,dateSQL:e("date time timestamp"),support:e("ODBCdotTable doubleQuote binaryNumber hexNumber")}),a.defineMIME("text/x-mssql",{name:"sql",client:e("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),keywords:e(f+"begin trigger proc view index for add constraint key primary foreign collate clustered nonclustered declare exec"),builtin:e("bigint numeric bit smallint decimal smallmoney int tinyint money float real char varchar text nchar nvarchar ntext binary varbinary image cursor timestamp hierarchyid uniqueidentifier sql_variant xml table "),atoms:e("false true null unknown"),operatorChars:/^[*+\-%<>!=]/,dateSQL:e("date datetimeoffset datetime2 smalldatetime datetime time"),hooks:{"@":c}}),a.defineMIME("text/x-mysql",{name:"sql",client:e("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),keywords:e(f+"accessible action add after algorithm all analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance diagnostics directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general get global grant grants group group_concat handler hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show signal slave slow smallint snapshot soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"),builtin:e("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric"),atoms:e("false true null unknown"),operatorChars:/^[*+\-%<>!=&|^]/,dateSQL:e("date time timestamp"),support:e("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"),hooks:{"@":c,"`":b,"\\":d}}),a.defineMIME("text/x-mariadb",{name:"sql",client:e("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),keywords:e(f+"accessible action add after algorithm all always analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance diagnostics directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general generated get global grant grants group groupby_concat handler hard hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password persistent phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show shutdown signal slave slow smallint snapshot soft soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views virtual warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"),builtin:e("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric"),atoms:e("false true null unknown"),operatorChars:/^[*+\-%<>!=&|^]/,dateSQL:e("date time timestamp"),support:e("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"),hooks:{"@":c,"`":b,"\\":d}}),a.defineMIME("text/x-cassandra",{name:"sql",client:{},keywords:e("add all allow alter and any apply as asc authorize batch begin by clustering columnfamily compact consistency count create custom delete desc distinct drop each_quorum exists filtering from grant if in index insert into key keyspace keyspaces level limit local_one local_quorum modify nan norecursive nosuperuser not of on one order password permission permissions primary quorum rename revoke schema select set storage superuser table three to token truncate ttl two type unlogged update use user users using values where with writetime"),builtin:e("ascii bigint blob boolean counter decimal double float frozen inet int list map static text timestamp timeuuid tuple uuid varchar varint"),atoms:e("false true infinity NaN"),operatorChars:/^[<>=]/,dateSQL:{},support:e("commentSlashSlash decimallessFloat"),hooks:{}}),a.defineMIME("text/x-plsql",{name:"sql",client:e("appinfo arraysize autocommit autoprint autorecovery autotrace blockterminator break btitle cmdsep colsep compatibility compute concat copycommit copytypecheck define describe echo editfile embedded escape exec execute feedback flagger flush heading headsep instance linesize lno loboffset logsource long longchunksize markup native newpage numformat numwidth pagesize pause pno recsep recsepchar release repfooter repheader serveroutput shiftinout show showmode size spool sqlblanklines sqlcase sqlcode sqlcontinue sqlnumber sqlpluscompatibility sqlprefix sqlprompt sqlterminator suffix tab term termout time timing trimout trimspool ttitle underline verify version wrap"),keywords:e("abort accept access add all alter and any array arraylen as asc assert assign at attributes audit authorization avg base_table begin between binary_integer body boolean by case cast char char_base check close cluster clusters colauth column comment commit compress connect connected constant constraint crash create current currval cursor data_base database date dba deallocate debugoff debugon decimal declare default definition delay delete desc digits dispose distinct do drop else elseif elsif enable end entry escape exception exception_init exchange exclusive exists exit external fast fetch file for force form from function generic goto grant group having identified if immediate in increment index indexes indicator initial initrans insert interface intersect into is key level library like limited local lock log logging long loop master maxextents maxtrans member minextents minus mislabel mode modify multiset new next no noaudit nocompress nologging noparallel not nowait number_base object of off offline on online only open option or order out package parallel partition pctfree pctincrease pctused pls_integer positive positiven pragma primary prior private privileges procedure public raise range raw read rebuild record ref references refresh release rename replace resource restrict return returning returns reverse revoke rollback row rowid rowlabel rownum rows run savepoint schema segment select separate session set share snapshot some space split sql start statement storage subtype successful synonym tabauth table tables tablespace task terminate then to trigger truncate type union unique unlimited unrecoverable unusable update use using validate value values variable view views when whenever where while with work"),builtin:e("abs acos add_months ascii asin atan atan2 average bfile bfilename bigserial bit blob ceil character chartorowid chr clob concat convert cos cosh count dec decode deref dual dump dup_val_on_index empty error exp false float floor found glb greatest hextoraw initcap instr instrb int integer isopen last_day least length lengthb ln lower lpad ltrim lub make_ref max min mlslabel mod months_between natural naturaln nchar nclob new_time next_day nextval nls_charset_decl_len nls_charset_id nls_charset_name nls_initcap nls_lower nls_sort nls_upper nlssort no_data_found notfound null number numeric nvarchar2 nvl others power rawtohex real reftohex round rowcount rowidtochar rowtype rpad rtrim serial sign signtype sin sinh smallint soundex sqlcode sqlerrm sqrt stddev string substr substrb sum sysdate tan tanh to_char text to_date to_label to_multi_byte to_number to_single_byte translate true trunc uid unlogged upper user userenv varchar varchar2 variance varying vsize xml"),operatorChars:/^[*+\-%<>!=~]/,dateSQL:e("date time timestamp"),support:e("doubleQuote nCharCast zerolessFloat binaryNumber hexNumber")}),a.defineMIME("text/x-hive",{name:"sql",keywords:e("select alter $elem$ $key$ $value$ add after all analyze and archive as asc before between binary both bucket buckets by cascade case cast change cluster clustered clusterstatus collection column columns comment compute concatenate continue create cross cursor data database databases dbproperties deferred delete delimited desc describe directory disable distinct distribute drop else enable end escaped exclusive exists explain export extended external false fetch fields fileformat first format formatted from full function functions grant group having hold_ddltime idxproperties if import in index indexes inpath inputdriver inputformat insert intersect into is items join keys lateral left like limit lines load local location lock locks mapjoin materialized minus msck no_drop nocompress not of offline on option or order out outer outputdriver outputformat overwrite partition partitioned partitions percent plus preserve procedure purge range rcfile read readonly reads rebuild recordreader recordwriter recover reduce regexp rename repair replace restrict revoke right rlike row schema schemas semi sequencefile serde serdeproperties set shared show show_database sort sorted ssl statistics stored streamtable table tables tablesample tblproperties temporary terminated textfile then tmp to touch transform trigger true unarchive undo union uniquejoin unlock update use using utc utc_tmestamp view when where while with"),builtin:e("bool boolean long timestamp tinyint smallint bigint int float double date datetime unsigned string array struct map uniontype"),atoms:e("false true null unknown"),operatorChars:/^[*+\-%<>!=]/,dateSQL:e("date timestamp"),support:e("ODBCdotTable doubleQuote binaryNumber hexNumber")}),a.defineMIME("text/x-pgsql",{name:"sql",client:e("source"),keywords:e(f+"a abort abs absent absolute access according action ada add admin after aggregate all allocate also always analyse analyze any are array array_agg array_max_cardinality asensitive assertion assignment asymmetric at atomic attribute attributes authorization avg backward base64 before begin begin_frame begin_partition bernoulli binary bit_length blob blocked bom both breadth c cache call called cardinality cascade cascaded case cast catalog catalog_name ceil ceiling chain characteristics characters character_length character_set_catalog character_set_name character_set_schema char_length check checkpoint class class_origin clob close cluster coalesce cobol collate collation collation_catalog collation_name collation_schema collect column columns column_name command_function command_function_code comment comments commit committed concurrently condition condition_number configuration conflict connect connection connection_name constraint constraints constraint_catalog constraint_name constraint_schema constructor contains content continue control conversion convert copy corr corresponding cost covar_pop covar_samp cross csv cube cume_dist current current_catalog current_date current_default_transform_group current_path current_role current_row current_schema current_time current_timestamp current_transform_group_for_type current_user cursor cursor_name cycle data database datalink datetime_interval_code datetime_interval_precision day db deallocate dec declare default defaults deferrable deferred defined definer degree delimiter delimiters dense_rank depth deref derived describe descriptor deterministic diagnostics dictionary disable discard disconnect dispatch dlnewcopy dlpreviouscopy dlurlcomplete dlurlcompleteonly dlurlcompletewrite dlurlpath dlurlpathonly dlurlpathwrite dlurlscheme dlurlserver dlvalue do document domain dynamic dynamic_function dynamic_function_code each element else empty enable encoding encrypted end end-exec end_frame end_partition enforced enum equals escape event every except exception exclude excluding exclusive exec execute exists exp explain expression extension external extract false family fetch file filter final first first_value flag float floor following for force foreign fortran forward found frame_row free freeze fs full function functions fusion g general generated get global go goto grant granted greatest grouping groups handler header hex hierarchy hold hour id identity if ignore ilike immediate immediately immutable implementation implicit import including increment indent index indexes indicator inherit inherits initially inline inner inout input insensitive instance instantiable instead integrity intersect intersection invoker isnull isolation k key key_member key_type label lag language large last last_value lateral lead leading leakproof least left length level library like_regex link listen ln load local localtime localtimestamp location locator lock locked logged lower m map mapping match matched materialized max maxvalue max_cardinality member merge message_length message_octet_length message_text method min minute minvalue mod mode modifies module month more move multiset mumps name names namespace national natural nchar nclob nesting new next nfc nfd nfkc nfkd nil no none normalize normalized nothing notify notnull nowait nth_value ntile null nullable nullif nulls number object occurrences_regex octets octet_length of off offset oids old only open operator option options ordering ordinality others out outer output over overlaps overlay overriding owned owner p pad parameter parameter_mode parameter_name parameter_ordinal_position parameter_specific_catalog parameter_specific_name parameter_specific_schema parser partial partition pascal passing passthrough password percent percentile_cont percentile_disc percent_rank period permission placing plans pli policy portion position position_regex power precedes preceding prepare prepared preserve primary prior privileges procedural procedure program public quote range rank read reads reassign recheck recovery recursive ref references referencing refresh regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy regr_syy reindex relative release rename repeatable replace replica requiring reset respect restart restore restrict result return returned_cardinality returned_length returned_octet_length returned_sqlstate returning returns revoke right role rollback rollup routine routine_catalog routine_name routine_schema row rows row_count row_number rule savepoint scale schema schema_name scope scope_catalog scope_name scope_schema scroll search second section security selective self sensitive sequence sequences serializable server server_name session session_user setof sets share show similar simple size skip snapshot some source space specific specifictype specific_name sql sqlcode sqlerror sqlexception sqlstate sqlwarning sqrt stable standalone start state statement static statistics stddev_pop stddev_samp stdin stdout storage strict strip structure style subclass_origin submultiset substring substring_regex succeeds sum symmetric sysid system system_time system_user t tables tablesample tablespace table_name temp template temporary then ties timezone_hour timezone_minute to token top_level_count trailing transaction transactions_committed transactions_rolled_back transaction_active transform transforms translate translate_regex translation treat trigger trigger_catalog trigger_name trigger_schema trim trim_array true truncate trusted type types uescape unbounded uncommitted under unencrypted unique unknown unlink unlisten unlogged unnamed unnest until untyped upper uri usage user user_defined_type_catalog user_defined_type_code user_defined_type_name user_defined_type_schema using vacuum valid validate validator value value_of varbinary variadic var_pop var_samp verbose version versioning view views volatile when whenever whitespace width_bucket window within work wrapper write xmlagg xmlattributes xmlbinary xmlcast xmlcomment xmlconcat xmldeclaration xmldocument xmlelement xmlexists xmlforest xmliterate xmlnamespaces xmlparse xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltext xmlvalidate year yes loop repeat"),builtin:e("bigint int8 bigserial serial8 bit varying varbit boolean bool box bytea character char varchar cidr circle date double precision float8 inet integer int int4 interval json jsonb line lseg macaddr money numeric decimal path pg_lsn point polygon real float4 smallint int2 smallserial serial2 serial serial4 text time without zone with timetz timestamp timestamptz tsquery tsvector txid_snapshot uuid xml"),atoms:e("false true null unknown"),operatorChars:/^[*+\-%<>!=&|^\/#@?~]/,dateSQL:e("date time timestamp"),support:e("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber nCharCast charsetCast")}),a.defineMIME("text/x-gql",{name:"sql",keywords:e("ancestor and asc by contains desc descendant distinct from group has in is limit offset on order select superset where"),atoms:e("false true"),builtin:e("blob datetime first key __key__ string integer double boolean null"),operatorChars:/^[*+\-%<>!=]/})})()})); \ No newline at end of file diff --git a/media/editors/codemirror/mode/swift/swift.js b/media/editors/codemirror/mode/swift/swift.js index 3c28ced329b18..9dcd822e917da 100644 --- a/media/editors/codemirror/mode/swift/swift.js +++ b/media/editors/codemirror/mode/swift/swift.js @@ -19,24 +19,21 @@ return set } - var keywords = wordSet(["var","let","class","deinit","enum","extension","func","import","init","protocol", - "static","struct","subscript","typealias","as","dynamicType","is","new","super", - "self","Self","Type","__COLUMN__","__FILE__","__FUNCTION__","__LINE__","break","case", - "continue","default","do","else","fallthrough","if","in","for","return","switch", - "where","while","associativity","didSet","get","infix","inout","left","mutating", - "none","nonmutating","operator","override","postfix","precedence","prefix","right", - "set","unowned","weak","willSet"]) - var definingKeywords = wordSet(["var","let","class","enum","extension","func","import","protocol","struct", - "typealias","dynamicType","for"]) - var atoms = wordSet(["Infinity","NaN","undefined","null","true","false","on","off","yes","no","nil","null", - "this","super"]) - var types = wordSet(["String","bool","int","string","double","Double","Int","Float","float","public", - "private","extension"]) - var operators = "+-/*%=|&<>#" + var keywords = wordSet(["_","var","let","class","enum","extension","import","protocol","struct","func","typealias","associatedtype", + "open","public","internal","fileprivate","private","deinit","init","new","override","self","subscript","super", + "convenience","dynamic","final","indirect","lazy","required","static","unowned","unowned(safe)","unowned(unsafe)","weak","as","is", + "break","case","continue","default","else","fallthrough","for","guard","if","in","repeat","switch","where","while", + "defer","return","inout","mutating","nonmutating","catch","do","rethrows","throw","throws","try","didSet","get","set","willSet", + "assignment","associativity","infix","left","none","operator","postfix","precedence","precedencegroup","prefix","right", + "Any","AnyObject","Type","dynamicType","Self","Protocol","__COLUMN__","__FILE__","__FUNCTION__","__LINE__"]) + var definingKeywords = wordSet(["var","let","class","enum","extension","import","protocol","struct","func","typealias","associatedtype"]) + var atoms = wordSet(["true","false","nil","self","super","_"]) + var types = wordSet(["Array","Bool","Dictionary","Double","Float","Int","Never","Optional","String","Void"]) + var operators = "+-/*%=|&<>" var punc = ";,.(){}[]" var number = /^-?(?:(?:[\d_]+\.[_\d]*|\.[_\d]+|0o[0-7_\.]+|0b[01_\.]+)(?:e-?[\d_]+)?|0x[\d_a-f\.]+(?:p-?[\d_]+)?)/i var identifier = /^[_A-Za-z$][_A-Za-z$0-9]*/ - var property = /^[@\.][_A-Za-z$][_A-Za-z$0-9]*/ + var property = /^[@\#\.][_A-Za-z$][_A-Za-z$0-9]*/ var regexp = /^\/(?!\s)(?:\/\/)?(?:\\.|[^\/])+\// function tokenBase(stream, state, prev) { diff --git a/media/editors/codemirror/mode/swift/swift.min.js b/media/editors/codemirror/mode/swift/swift.min.js index 9bcd7644e796e..d1bd4d8bda095 100644 --- a/media/editors/codemirror/mode/swift/swift.min.js +++ b/media/editors/codemirror/mode/swift/swift.min.js @@ -1 +1 @@ -!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";function b(a){for(var b={},c=0;c-1)return a.next(),"operator";if(o.indexOf(d)>-1)return a.next(),a.match(".."),"punctuation";if('"'==d||"'"==d){a.next();var g=e(d);return b.tokenize.push(g),g(a,b)}if(a.match(p))return"number";if(a.match(r))return"property";if(a.match(q)){var h=a.current();return j.hasOwnProperty(h)?(k.hasOwnProperty(h)&&(b.prev="define"),"keyword"):m.hasOwnProperty(h)?"variable-2":l.hasOwnProperty(h)?"atom":"define"==c?"def":"variable"}return a.next(),null}function d(){var a=0;return function(b,d,e){var f=c(b,d,e);if("punctuation"==f)if("("==b.current())++a;else if(")"==b.current()){if(0==a)return b.backUp(1),d.tokenize.pop(),d.tokenize[d.tokenize.length-1](b,d);--a}return f}}function e(a){return function(b,c){for(var e,f=!1;e=b.next();)if(f){if("("==e)return c.tokenize.push(d()),"string";f=!1}else{if(e==a)break;f="\\"==e}return c.tokenize.pop(),"string"}}function f(a,b){return a.match(/^(?:[^*]|\*(?!\/))*/),a.match("*/")&&b.tokenize.pop(),"comment"}function g(a,b,c){this.prev=a,this.align=b,this.indented=c}function h(a,b){var c=b.match(/^\s*($|\/[\/\*])/,!1)?null:b.column()+1;a.context=new g(a.context,c,a.indented)}function i(a){a.context&&(a.indented=a.context.indented,a.context=a.context.prev)}var j=b(["var","let","class","deinit","enum","extension","func","import","init","protocol","static","struct","subscript","typealias","as","dynamicType","is","new","super","self","Self","Type","__COLUMN__","__FILE__","__FUNCTION__","__LINE__","break","case","continue","default","do","else","fallthrough","if","in","for","return","switch","where","while","associativity","didSet","get","infix","inout","left","mutating","none","nonmutating","operator","override","postfix","precedence","prefix","right","set","unowned","weak","willSet"]),k=b(["var","let","class","enum","extension","func","import","protocol","struct","typealias","dynamicType","for"]),l=b(["Infinity","NaN","undefined","null","true","false","on","off","yes","no","nil","null","this","super"]),m=b(["String","bool","int","string","double","Double","Int","Float","float","public","private","extension"]),n="+-/*%=|&<>#",o=";,.(){}[]",p=/^-?(?:(?:[\d_]+\.[_\d]*|\.[_\d]+|0o[0-7_\.]+|0b[01_\.]+)(?:e-?[\d_]+)?|0x[\d_a-f\.]+(?:p-?[\d_]+)?)/i,q=/^[_A-Za-z$][_A-Za-z$0-9]*/,r=/^[@\.][_A-Za-z$][_A-Za-z$0-9]*/,s=/^\/(?!\s)(?:\/\/)?(?:\\.|[^\/])+\//;a.defineMode("swift",(function(a){return{startState:function(){return{prev:null,context:null,indented:0,tokenize:[]}},token:function(a,b){var d=b.prev;b.prev=null;var e=b.tokenize[b.tokenize.length-1]||c,f=e(a,b,d);if(f&&"comment"!=f?b.prev||(b.prev=f):b.prev=d,"punctuation"==f){var g=/[\(\[\{]|([\]\)\}])/.exec(a.current());g&&(g[1]?i:h)(b,a)}return f},indent:function(b,c){var d=b.context;if(!d)return 0;var e=/^[\]\}\)]/.test(c);return null!=d.align?d.align-(e?1:0):d.indented+(e?0:a.indentUnit)},electricInput:/^\s*[\)\}\]]$/,lineComment:"//",blockCommentStart:"/*",blockCommentEnd:"*/"}})),a.defineMIME("text/x-swift","swift")})); \ No newline at end of file +!(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){"use strict";function b(a){for(var b={},c=0;c-1)return a.next(),"operator";if(o.indexOf(d)>-1)return a.next(),a.match(".."),"punctuation";if('"'==d||"'"==d){a.next();var g=e(d);return b.tokenize.push(g),g(a,b)}if(a.match(p))return"number";if(a.match(r))return"property";if(a.match(q)){var h=a.current();return j.hasOwnProperty(h)?(k.hasOwnProperty(h)&&(b.prev="define"),"keyword"):m.hasOwnProperty(h)?"variable-2":l.hasOwnProperty(h)?"atom":"define"==c?"def":"variable"}return a.next(),null}function d(){var a=0;return function(b,d,e){var f=c(b,d,e);if("punctuation"==f)if("("==b.current())++a;else if(")"==b.current()){if(0==a)return b.backUp(1),d.tokenize.pop(),d.tokenize[d.tokenize.length-1](b,d);--a}return f}}function e(a){return function(b,c){for(var e,f=!1;e=b.next();)if(f){if("("==e)return c.tokenize.push(d()),"string";f=!1}else{if(e==a)break;f="\\"==e}return c.tokenize.pop(),"string"}}function f(a,b){return a.match(/^(?:[^*]|\*(?!\/))*/),a.match("*/")&&b.tokenize.pop(),"comment"}function g(a,b,c){this.prev=a,this.align=b,this.indented=c}function h(a,b){var c=b.match(/^\s*($|\/[\/\*])/,!1)?null:b.column()+1;a.context=new g(a.context,c,a.indented)}function i(a){a.context&&(a.indented=a.context.indented,a.context=a.context.prev)}var j=b(["_","var","let","class","enum","extension","import","protocol","struct","func","typealias","associatedtype","open","public","internal","fileprivate","private","deinit","init","new","override","self","subscript","super","convenience","dynamic","final","indirect","lazy","required","static","unowned","unowned(safe)","unowned(unsafe)","weak","as","is","break","case","continue","default","else","fallthrough","for","guard","if","in","repeat","switch","where","while","defer","return","inout","mutating","nonmutating","catch","do","rethrows","throw","throws","try","didSet","get","set","willSet","assignment","associativity","infix","left","none","operator","postfix","precedence","precedencegroup","prefix","right","Any","AnyObject","Type","dynamicType","Self","Protocol","__COLUMN__","__FILE__","__FUNCTION__","__LINE__"]),k=b(["var","let","class","enum","extension","import","protocol","struct","func","typealias","associatedtype"]),l=b(["true","false","nil","self","super","_"]),m=b(["Array","Bool","Dictionary","Double","Float","Int","Never","Optional","String","Void"]),n="+-/*%=|&<>",o=";,.(){}[]",p=/^-?(?:(?:[\d_]+\.[_\d]*|\.[_\d]+|0o[0-7_\.]+|0b[01_\.]+)(?:e-?[\d_]+)?|0x[\d_a-f\.]+(?:p-?[\d_]+)?)/i,q=/^[_A-Za-z$][_A-Za-z$0-9]*/,r=/^[@\#\.][_A-Za-z$][_A-Za-z$0-9]*/,s=/^\/(?!\s)(?:\/\/)?(?:\\.|[^\/])+\//;a.defineMode("swift",(function(a){return{startState:function(){return{prev:null,context:null,indented:0,tokenize:[]}},token:function(a,b){var d=b.prev;b.prev=null;var e=b.tokenize[b.tokenize.length-1]||c,f=e(a,b,d);if(f&&"comment"!=f?b.prev||(b.prev=f):b.prev=d,"punctuation"==f){var g=/[\(\[\{]|([\]\)\}])/.exec(a.current());g&&(g[1]?i:h)(b,a)}return f},indent:function(b,c){var d=b.context;if(!d)return 0;var e=/^[\]\}\)]/.test(c);return null!=d.align?d.align-(e?1:0):d.indented+(e?0:a.indentUnit)},electricInput:/^\s*[\)\}\]]$/,lineComment:"//",blockCommentStart:"/*",blockCommentEnd:"*/"}})),a.defineMIME("text/x-swift","swift")})); \ No newline at end of file diff --git a/media/editors/codemirror/theme/dracula.css b/media/editors/codemirror/theme/dracula.css index 57f979ae69412..b2ef62913c65f 100644 --- a/media/editors/codemirror/theme/dracula.css +++ b/media/editors/codemirror/theme/dracula.css @@ -16,7 +16,7 @@ .cm-s-dracula .CodeMirror-gutters { color: #282a36; } .cm-s-dracula .CodeMirror-cursor { border-left: solid thin #f8f8f0; } .cm-s-dracula .CodeMirror-linenumber { color: #6D8A88; } -.cm-s-dracula.CodeMirror-focused div.CodeMirror-selected { background: rgba(255, 255, 255, 0.10); } +.cm-s-dracula .CodeMirror-selected { background: rgba(255, 255, 255, 0.10); } .cm-s-dracula .CodeMirror-line::selection, .cm-s-dracula .CodeMirror-line > span::selection, .cm-s-dracula .CodeMirror-line > span > span::selection { background: rgba(255, 255, 255, 0.10); } .cm-s-dracula .CodeMirror-line::-moz-selection, .cm-s-dracula .CodeMirror-line > span::-moz-selection, .cm-s-dracula .CodeMirror-line > span > span::-moz-selection { background: rgba(255, 255, 255, 0.10); } .cm-s-dracula span.cm-comment { color: #6272a4; } diff --git a/media/editors/codemirror/theme/duotone-dark.css b/media/editors/codemirror/theme/duotone-dark.css new file mode 100644 index 0000000000000..b09a585c97867 --- /dev/null +++ b/media/editors/codemirror/theme/duotone-dark.css @@ -0,0 +1,35 @@ +/* +Name: DuoTone-Dark +Author: by Bram de Haan, adapted from DuoTone themes by Simurai (http://simurai.com/projects/2016/01/01/duotone-themes) + +CodeMirror template by Jan T. Sott (https://github.com/idleberg), adapted by Bram de Haan (https://github.com/atelierbram/) +*/ + +.cm-s-duotone-dark.CodeMirror { background: #2a2734; color: #6c6783; } +.cm-s-duotone-dark div.CodeMirror-selected { background: #545167!important; } +.cm-s-duotone-dark .CodeMirror-gutters { background: #2a2734; border-right: 0px; } +.cm-s-duotone-dark .CodeMirror-linenumber { color: #545167; } + +/* begin cursor */ +.cm-s-duotone-dark .CodeMirror-cursor { border-left: 1px solid #ffad5c; /* border-left: 1px solid #ffad5c80; */ border-right: .5em solid #ffad5c; /* border-right: .5em solid #ffad5c80; */ opacity: .5; } +.cm-s-duotone-dark .CodeMirror-activeline-background { background: #363342; /* background: #36334280; */ opacity: .5;} +.cm-s-duotone-dark .cm-fat-cursor .CodeMirror-cursor { background: #ffad5c; /* background: #ffad5c80; */ opacity: .5;} +/* end cursor */ + +.cm-s-duotone-dark span.cm-atom, .cm-s-duotone-dark span.cm-number, .cm-s-duotone-dark span.cm-keyword, .cm-s-duotone-dark span.cm-variable, .cm-s-duotone-dark span.cm-attribute, .cm-s-duotone-dark span.cm-quote, .cm-s-duotone-dark span.cm-hr, .cm-s-duotone-dark span.cm-link { color: #ffcc99; } + +.cm-s-duotone-dark span.cm-property { color: #9a86fd; } +.cm-s-duotone-dark span.cm-punctuation, .cm-s-duotone-dark span.cm-unit, .cm-s-duotone-dark span.cm-negative { color: #e09142; } +.cm-s-duotone-dark span.cm-string { color: #ffb870; } +.cm-s-duotone-dark span.cm-operator { color: #ffad5c; } +.cm-s-duotone-dark span.cm-positive { color: #6a51e6; } + +.cm-s-duotone-dark span.cm-variable-2, .cm-s-duotone-dark span.cm-variable-3, .cm-s-duotone-dark span.cm-string-2, .cm-s-duotone-dark span.cm-url { color: #7a63ee; } +.cm-s-duotone-dark span.cm-def, .cm-s-duotone-dark span.cm-tag, .cm-s-duotone-dark span.cm-builtin, .cm-s-duotone-dark span.cm-qualifier, .cm-s-duotone-dark span.cm-header, .cm-s-duotone-dark span.cm-em { color: #eeebff; } +.cm-s-duotone-dark span.cm-bracket, .cm-s-duotone-dark span.cm-comment { color: #6c6783; } + +/* using #f00 red for errors, don't think any of the colorscheme variables will stand out enough, ... maybe by giving it a background-color ... */ +.cm-s-duotone-dark span.cm-error, .cm-s-duotone-dark span.cm-invalidchar { color: #f00; } + +.cm-s-duotone-dark span.cm-header { font-weight: normal; } +.cm-s-duotone-dark .CodeMirror-matchingbracket { text-decoration: underline; color: #eeebff !important; } diff --git a/media/editors/codemirror/theme/duotone-light.css b/media/editors/codemirror/theme/duotone-light.css new file mode 100644 index 0000000000000..80203d15d9a6f --- /dev/null +++ b/media/editors/codemirror/theme/duotone-light.css @@ -0,0 +1,36 @@ +/* +Name: DuoTone-Light +Author: by Bram de Haan, adapted from DuoTone themes by Simurai (http://simurai.com/projects/2016/01/01/duotone-themes) + +CodeMirror template by Jan T. Sott (https://github.com/idleberg), adapted by Bram de Haan (https://github.com/atelierbram/) +*/ + +.cm-s-duotone-light.CodeMirror { background: #faf8f5; color: #b29762; } +.cm-s-duotone-light div.CodeMirror-selected { background: #e3dcce !important; } +.cm-s-duotone-light .CodeMirror-gutters { background: #faf8f5; border-right: 0px; } +.cm-s-duotone-light .CodeMirror-linenumber { color: #cdc4b1; } + +/* begin cursor */ +.cm-s-duotone-light .CodeMirror-cursor { border-left: 1px solid #93abdc; /* border-left: 1px solid #93abdc80; */ border-right: .5em solid #93abdc; /* border-right: .5em solid #93abdc80; */ opacity: .5; } +.cm-s-duotone-light .CodeMirror-activeline-background { background: #e3dcce; /* background: #e3dcce80; */ opacity: .5; } +.cm-s-duotone-light .cm-fat-cursor .CodeMirror-cursor { background: #93abdc; /* #93abdc80; */ opacity: .5; } +/* end cursor */ + +.cm-s-duotone-light span.cm-atom, .cm-s-duotone-light span.cm-number, .cm-s-duotone-light span.cm-keyword, .cm-s-duotone-light span.cm-variable, .cm-s-duotone-light span.cm-attribute, .cm-s-duotone-light span.cm-quote, .cm-s-duotone-light-light span.cm-hr, .cm-s-duotone-light-light span.cm-link { color: #063289; } + +.cm-s-duotone-light span.cm-property { color: #b29762; } +.cm-s-duotone-light span.cm-punctuation, .cm-s-duotone-light span.cm-unit, .cm-s-duotone-light span.cm-negative { color: #063289; } +.cm-s-duotone-light span.cm-string, .cm-s-duotone-light span.cm-operator { color: #1659df; } +.cm-s-duotone-light span.cm-positive { color: #896724; } + +.cm-s-duotone-light span.cm-variable-2, .cm-s-duotone-light span.cm-variable-3, .cm-s-duotone-light span.cm-string-2, .cm-s-duotone-light span.cm-url { color: #896724; } +.cm-s-duotone-light span.cm-def, .cm-s-duotone-light span.cm-tag, .cm-s-duotone-light span.cm-builtin, .cm-s-duotone-light span.cm-qualifier, .cm-s-duotone-light span.cm-header, .cm-s-duotone-light span.cm-em { color: #2d2006; } +.cm-s-duotone-light span.cm-bracket, .cm-s-duotone-light span.cm-comment { color: #b6ad9a; } + +/* using #f00 red for errors, don't think any of the colorscheme variables will stand out enough, ... maybe by giving it a background-color ... */ +/* .cm-s-duotone-light span.cm-error { background: #896724; color: #728fcb; } */ +.cm-s-duotone-light span.cm-error, .cm-s-duotone-light span.cm-invalidchar { color: #f00; } + +.cm-s-duotone-light span.cm-header { font-weight: normal; } +.cm-s-duotone-light .CodeMirror-matchingbracket { text-decoration: underline; color: #faf8f5 !important; } + diff --git a/media/editors/codemirror/theme/panda-syntax.css b/media/editors/codemirror/theme/panda-syntax.css index 8c0c754082165..c93b2ea03a76e 100644 --- a/media/editors/codemirror/theme/panda-syntax.css +++ b/media/editors/codemirror/theme/panda-syntax.css @@ -75,11 +75,11 @@ padding-bottom: 2px; color: #e6e6e6; } -.CodeMirror-gutters { +.cm-s-panda-syntax .CodeMirror-gutters { background: #292a2b; border-right-color: rgba(255, 255, 255, 0.1); } -.CodeMirror-linenumber { +.cm-s-panda-syntax .CodeMirror-linenumber { color: #e6e6e6; opacity: 0.6; } diff --git a/plugins/editors/codemirror/codemirror.xml b/plugins/editors/codemirror/codemirror.xml index 0b23beb1c3216..1fa45d720d83a 100644 --- a/plugins/editors/codemirror/codemirror.xml +++ b/plugins/editors/codemirror/codemirror.xml @@ -1,7 +1,7 @@ plg_editors_codemirror - 5.19.0 + 5.20.2 28 March 2011 Marijn Haverbeke marijnh@gmail.com