diff --git a/css/base.css b/css/base.css index 068164f..d702134 100644 --- a/css/base.css +++ b/css/base.css @@ -10,13 +10,13 @@ * 表示状态的应该用do-st-*命名 * 表示功能的应该用do-fn-*命名 * 表示页面模块的应该用do-mod-modname 命名 - * 表示应用的应该用do-uiname命名, 它的子元素应该全部包在 .do-uiname这个根类下 + * 表示UI组件的应该用do-uiname命名, 它的子元素应该全部包在 .do-uiname这个根类下 * 如 .do-layer .body { ... } * * 样式规则的出现顺序 * 1 display float position overflow z-index 表示定位/布局的属性 * 2 width height margin padding border 表示盒子模型的属性 - * 3 line-heightcursor font-size vertical-align text-align user-select outline ....排版相关的属性 + * 3 line-height font-size vertical-align text-align user-select outline ....排版相关的属性 * 4 color background opacity cursor ...表示装饰相关的属性 * 5 content list-style quotes ... 内容生成相关的属性 * diff --git a/js/lib/codemirror/codemirror.css b/js/lib/codemirror/codemirror.css index 9ec9537..c1d9dc1 100644 --- a/js/lib/codemirror/codemirror.css +++ b/js/lib/codemirror/codemirror.css @@ -1 +1,275 @@ -.CodeMirror{font-family:monospace;height:300px;color:#000}.CodeMirror-lines{padding:4px 0}.CodeMirror pre{padding:0 4px}.CodeMirror-gutter-filler,.CodeMirror-scrollbar-filler{background-color:#fff}.CodeMirror-gutters{border-right:1px solid #ddd;background-color:#f7f7f7;white-space:nowrap}.CodeMirror-linenumber{padding:0 3px 0 5px;min-width:20px;text-align:right;color:#999;white-space:nowrap}.CodeMirror-guttermarker{color:#000}.CodeMirror-guttermarker-subtle{color:#999}.CodeMirror-cursor{border-left:1px solid #000;border-right:none;width:0}.CodeMirror div.CodeMirror-secondarycursor{border-left:1px solid silver}.cm-fat-cursor .CodeMirror-cursor{width:auto;border:0!important;background:#7e7}.cm-fat-cursor div.CodeMirror-cursors{z-index:1}.cm-animate-fat-cursor{width:auto;border:0;-webkit-animation:blink 1.06s steps(1) infinite;-moz-animation:blink 1.06s steps(1) infinite;animation:blink 1.06s steps(1) infinite;background-color:#7e7}@-moz-keyframes blink{50%{background-color:transparent}}@-webkit-keyframes blink{50%{background-color:transparent}}@keyframes blink{50%{background-color:transparent}}.cm-tab{display:inline-block;text-decoration:inherit}.CodeMirror-rulers{position:absolute;left:0;right:0;top:-50px;bottom:-20px;overflow:hidden}.CodeMirror-ruler{border-left:1px solid #ccc;top:0;bottom:0;position:absolute}.cm-s-default .cm-header{color:#00f}.cm-s-default .cm-quote{color:#090}.cm-negative{color:#d44}.cm-positive{color:#292}.cm-header,.cm-strong{font-weight:700}.cm-em{font-style:italic}.cm-link{text-decoration:underline}.cm-strikethrough{text-decoration:line-through}.cm-s-default .cm-keyword{color:#708}.cm-s-default .cm-atom{color:#219}.cm-s-default .cm-number{color:#164}.cm-s-default .cm-def{color:#00f}.cm-s-default .cm-variable-2{color:#05a}.cm-s-default .cm-variable-3{color:#085}.cm-s-default .cm-comment{color:#a50}.cm-s-default .cm-string{color:#a11}.cm-s-default .cm-string-2{color:#f50}.cm-s-default .cm-meta,.cm-s-default .cm-qualifier{color:#555}.cm-s-default .cm-builtin{color:#30a}.cm-s-default .cm-bracket{color:#997}.cm-s-default .cm-tag{color:#170}.cm-s-default .cm-attribute{color:#00c}.cm-s-default .cm-hr{color:#999}.cm-s-default .cm-link{color:#00c}.cm-invalidchar,.cm-s-default .cm-error{color:red}.CodeMirror-composing{border-bottom:2px solid}div.CodeMirror span.CodeMirror-matchingbracket{color:#0f0}div.CodeMirror span.CodeMirror-nonmatchingbracket{color:#f22}.CodeMirror-matchingtag{background:rgba(255,150,0,.3)}.CodeMirror-activeline-background{background:#e8f2ff}.CodeMirror{position:relative;overflow:hidden;background:#fff}.CodeMirror-scroll{overflow:scroll!important;margin-bottom:-30px;margin-right:-30px;padding-bottom:30px;height:100%;outline:0;position:relative}.CodeMirror-sizer{position:relative;border-right:30px solid transparent}.CodeMirror-gutter-filler,.CodeMirror-hscrollbar,.CodeMirror-scrollbar-filler,.CodeMirror-vscrollbar{position:absolute;z-index:6;display:none}.CodeMirror-vscrollbar{right:0;top:0;overflow-x:hidden;overflow-y:scroll}.CodeMirror-hscrollbar{bottom:0;left:0;overflow-y:hidden;overflow-x:scroll}.CodeMirror-scrollbar-filler{right:0;bottom:0}.CodeMirror-gutter-filler{left:0;bottom:0}.CodeMirror-gutters{position:absolute;left:0;top:0;min-height:100%;z-index:3}.CodeMirror-gutter{white-space:normal;height:100%;display:inline-block;vertical-align:top;margin-bottom:-30px}.CodeMirror-gutter-wrapper{position:absolute;z-index:4;background:none!important;border:none!important}.CodeMirror-gutter-background{position:absolute;top:0;bottom:0;z-index:4}.CodeMirror-gutter-elt{position:absolute;cursor:default;z-index:4}.CodeMirror-gutter-wrapper::selection{background-color:transparent}.CodeMirror-gutter-wrapper::-moz-selection{background-color:transparent}.CodeMirror-lines{cursor:text;min-height:1px}.CodeMirror pre{-moz-border-radius:0;-webkit-border-radius:0;border-radius:0;border-width:0;background:0 0;font-family:inherit;font-size:inherit;margin:0;white-space:pre;word-wrap:normal;line-height:inherit;color:inherit;z-index:2;position:relative;overflow:visible;-webkit-tap-highlight-color:transparent;-webkit-font-variant-ligatures:contextual;font-variant-ligatures:contextual}.CodeMirror-wrap pre{word-wrap:break-word;white-space:pre-wrap;word-break:normal}.CodeMirror-linebackground{position:absolute;left:0;right:0;top:0;bottom:0;z-index:0}.CodeMirror-linewidget{position:relative;z-index:2;overflow:auto}.CodeMirror-rtl pre{direction:rtl}.CodeMirror-code{outline:0}.CodeMirror-gutter,.CodeMirror-gutters,.CodeMirror-linenumber,.CodeMirror-scroll,.CodeMirror-sizer{-moz-box-sizing:content-box;box-sizing:content-box}.CodeMirror-measure{position:absolute;width:100%;height:0;overflow:hidden;visibility:hidden}.CodeMirror-cursor{position:absolute;pointer-events:none}.CodeMirror-measure pre{position:static}div.CodeMirror-cursors{visibility:hidden;position:relative;z-index:3}.CodeMirror-focused div.CodeMirror-cursors,div.CodeMirror-dragcursors{visibility:visible}.CodeMirror-selected{background:#d9d9d9}.CodeMirror-focused .CodeMirror-selected{background:#d7d4f0}.CodeMirror-crosshair{cursor:crosshair}.CodeMirror-line::selection,.CodeMirror-line>span::selection,.CodeMirror-line>span>span::selection{background:#d7d4f0}.CodeMirror-line::-moz-selection,.CodeMirror-line>span::-moz-selection,.CodeMirror-line>span>span::-moz-selection{background:#d7d4f0}.cm-searching{background:#ffa;background:rgba(255,255,0,.4)}.cm-force-border{padding-right:.1px}@media print{.CodeMirror div.CodeMirror-cursors{visibility:hidden}}.cm-tab-wrap-hack:after{content:''}span.CodeMirror-selectedtext{background:0 0}.cm-s-monokai.CodeMirror{height:100%;line-height:1.5;background:#272822;color:#f8f8f2}.cm-s-monokai div.CodeMirror-selected{background:#49483E}.cm-s-monokai .CodeMirror-line::selection,.cm-s-monokai .CodeMirror-line>span::selection,.cm-s-monokai .CodeMirror-line>span>span::selection{background:rgba(73,72,62,.99)}.cm-s-monokai .CodeMirror-line::-moz-selection,.cm-s-monokai .CodeMirror-line>span::-moz-selection,.cm-s-monokai .CodeMirror-line>span>span::-moz-selection{background:rgba(73,72,62,.99)}.cm-s-monokai .CodeMirror-gutters{background:#272822;border-right:0}.cm-s-monokai .CodeMirror-guttermarker{color:#fff}.cm-s-monokai .CodeMirror-guttermarker-subtle,.cm-s-monokai .CodeMirror-linenumber{color:#d0d0d0}.cm-s-monokai .CodeMirror-cursor{border-left:1px solid #f8f8f0}.cm-s-monokai span.cm-comment{color:#75715e}.cm-s-monokai span.cm-atom,.cm-s-monokai span.cm-number{color:#ae81ff}.cm-s-monokai span.cm-attribute,.cm-s-monokai span.cm-property{color:#a6e22e}.cm-s-monokai span.cm-keyword{color:#f92672}.cm-s-monokai span.cm-builtin{color:#66d9ef}.cm-s-monokai span.cm-string{color:#e6db74}.cm-s-monokai span.cm-variable{color:#f8f8f2}.cm-s-monokai span.cm-variable-2{color:#9effff}.cm-s-monokai span.cm-variable-3{color:#66d9ef}.cm-s-monokai span.cm-def{color:#fd971f}.cm-s-monokai span.cm-bracket{color:#f8f8f2}.cm-s-monokai span.cm-tag{color:#f92672}.cm-s-monokai span.cm-header,.cm-s-monokai span.cm-link{color:#ae81ff}.cm-s-monokai span.cm-error{background:#f92672;color:#f8f8f0}.cm-s-monokai .CodeMirror-activeline-background{background:#373831}.cm-s-monokai .CodeMirror-matchingbracket{text-decoration:underline;color:#fff!important} \ No newline at end of file +.CodeMirror { + height: 100%; + line-height: 1.5; + font-family: monospace; + position: relative; + overflow: hidden; + background: #272822; + color: #f8f8f2 +} + +.CodeMirror-scroll { + overflow: auto; + height: 100%; + width: 100%; + position: relative; + outline: none +} + +.CodeMirror-scrollbar { + position: absolute; + right: 0; + top: 0; + overflow-x: hidden; + overflow-y: scroll; + z-index: 5 +} + +.CodeMirror-scrollbar-inner { + width: 1px +} + +.CodeMirror-scrollbar.cm-sb-overlap { + position: absolute; + z-index: 1; + float: none; + right: 0; + min-width: 12px +} + +.CodeMirror-scrollbar.cm-sb-nonoverlap { + min-width: 12px +} + +.CodeMirror-scrollbar.cm-sb-ie7 { + min-width: 18px +} + +.CodeMirror-gutter { + position: absolute; + left: 0; + top: 0; + z-index: 10; + background-color: transparent; + border-right: 1px solid #454545; + min-width: 2em; + height: 100% +} + +.CodeMirror-gutter-text { + color: #aaa; + text-align: right; + padding: .4em .2em .4em .4em; + white-space: pre !important; + cursor: default +} + +.CodeMirror-lines { + padding: .4em; + white-space: pre; + cursor: text +} + +.CodeMirror pre { + -moz-border-radius: 0; + -webkit-border-radius: 0; + -o-border-radius: 0; + border-radius: 0; + border-width: 0; + margin: 0; + padding: 0; + background: transparent; + font-family: inherit; + font-size: inherit; + padding: 0; + margin: 0; + white-space: pre; + word-wrap: normal; + line-height: inherit; + color: inherit; + overflow: visible +} + +.CodeMirror-wrap pre { + word-wrap: break-word; + white-space: pre-wrap; + word-break: normal +} + +.CodeMirror-wrap .CodeMirror-scroll { + overflow-x: hidden +} + +.CodeMirror textarea { + outline: none !important +} + +.CodeMirror pre.CodeMirror-cursor { + z-index: 10; + position: absolute; + visibility: hidden; + border-left: 1px solid #9effff; + border-right: none; + width: 0 +} + +.cm-keymap-fat-cursor pre.CodeMirror-cursor { + width: auto; + border: 0; + background: transparent; + background: rgba(0, 200, 0, .4); + filter: progid: DXImageTransform.Microsoft.gradient(startColorstr=#6600c800, endColorstr=#4c00c800) +} + +.cm-keymap-fat-cursor pre.CodeMirror-cursor:not(#nonsense_id) { + filter: progid: DXImageTransform.Microsoft.gradient(enabled=false) +} + +.CodeMirror pre.CodeMirror-cursor.CodeMirror-overwrite {} + +.CodeMirror-focused pre.CodeMirror-cursor { + visibility: visible +} + +div.CodeMirror-selected { + background: #49483E +} + +.CodeMirror-focused div.CodeMirror-selected { + background: #49483E +} + +.CodeMirror-searching { + background: #ffa; + background: rgba(255, 255, 0, .4) +} + +.cm-s-default span.cm-keyword { + color: #f92672 +} + +.cm-s-default span.cm-atom { + color: #ae81ff +} + +.cm-s-default span.cm-number { + color: #f30 +} + +.cm-s-default span.cm-def { + color: #fd971f +} + +.cm-s-default span.cm-variable { + color: #f8f8f2 +} + +.cm-s-default span.cm-variable-2 { + color: #9effff +} + +.cm-s-default span.cm-variable-3 { + color: #66d9ef +} + +.cm-s-default span.cm-property { + color: #66d9ef +} + +.cm-s-default span.cm-operator { + color: #9effff +} + +.cm-s-default span.cm-comment { + color: #75715e +} + +.cm-s-default span.cm-string { + color: #e6db74 +} + +.cm-s-default span.cm-string-2 { + color: #f50 +} + +.cm-s-default span.cm-meta { + color: #555 +} + +.cm-s-default span.cm-error { + background: #f92672; + color: #f8f8f0 +} + +.cm-s-default span.cm-qualifier { + color: #75d908 +} + +.cm-s-default span.cm-builtin { + color: #66d9ef +} + +.cm-s-default span.cm-bracket { + color: #f8f8f2 +} + +.cm-s-default span.cm-tag { + color: #f92672 +} + +.cm-s-default span.cm-attribute { + color: #a6e22e +} + +.cm-s-default span.cm-header { + color: #ae81ff +} + +.cm-s-default span.cm-quote { + color: #090 +} + +.cm-s-default span.cm-hr { + color: #999 +} + +.cm-s-default span.cm-link { + color: #ae81ff +} + +span.cm-header, +span.cm-strong { + font-weight: bold +} + +span.cm-em { + font-style: italic +} + +span.cm-emstrong { + font-style: italic; + font-weight: bold +} + +span.cm-link { + text-decoration: underline +} + +span.cm-invalidchar { + color: #f00 +} + +div.CodeMirror span.CodeMirror-matchingbracket { + text-decoration: underline; + color: #fff!important +} + +div.CodeMirror span.CodeMirror-nonmatchingbracket { + color: #f22 +} + +@media print { + .CodeMirror pre.CodeMirror-cursor { + visibility: hidden + } +} diff --git a/js/lib/codemirror/codemirror.js b/js/lib/codemirror/codemirror.js index b85d0f7..f82f87f 100644 --- a/js/lib/codemirror/codemirror.js +++ b/js/lib/codemirror/codemirror.js @@ -1,6 +1,3969 @@ -define(function(){"use strict";function e(e){return new RegExp("(^|\\s)"+e+"(?:$|\\s)\\s*")}function t(e){for(var t=e.childNodes.length;t>0;--t)e.removeChild(e.firstChild);return e}function r(e,r){return t(e).appendChild(r)}function n(e,t,r,n){var i=document.createElement(e);if(r&&(i.className=r),n&&(i.style.cssText=n),"string"==typeof t)i.appendChild(document.createTextNode(t));else if(t)for(var o=0;os||s>=t)return l+(t-o);l+=s-o,l+=r-l%r,o=s+1}}function h(e,t){for(var r=0;r=t)return n+Math.min(l,t-i);if(i+=o-n,i+=r-i%r,n=o+1,i>=t)return n}}function p(e){for(;Os.length<=e;)Os.push(g(Os)+" ");return Os[e]}function g(e){return e[e.length-1]}function v(e,t){for(var r=[],n=0;n"€"&&(e.toUpperCase()!=e.toLowerCase()||Ws.test(e))}function x(e,t){return t?t.source.indexOf("\\w")>-1&&w(e)?!0:t.test(e):w(e)}function C(e){for(var t in e)if(e.hasOwnProperty(t)&&e[t])return!1;return!0}function S(e){return e.charCodeAt(0)>=768&&As.test(e)}function L(e,t,r){for(;(0>r?t>0:tts&&(o.gutters.style.zIndex=-1,o.scroller.style.paddingRight=0),rs||ql&&fs||(o.scroller.draggable=!0),e&&(e.appendChild?e.appendChild(o.wrapper):e(o.wrapper)),o.viewFrom=o.viewTo=t.first,o.reportedViewFrom=o.reportedViewTo=t.first,o.view=[],o.renderedView=null,o.externalMeasured=null,o.viewOffset=0,o.lastWrapHeight=o.lastWrapWidth=0,o.updateLineNumbers=null,o.nativeBarWidth=o.barHeight=o.barWidth=0,o.scrollbarsClipped=!1,o.lineNumWidth=o.lineNumInnerWidth=o.lineNumChars=null,o.alignWidgets=!1,o.cachedCharWidth=o.cachedTextHeight=o.cachedPaddingH=null,o.maxLine=null,o.maxLineLength=0,o.maxLineChanged=!1,o.wheelDX=o.wheelDY=o.wheelStartX=o.wheelStartY=null,o.shift=!1,o.selForContextMenu=null,o.activeTouch=null,r.init(o)}function M(e,t){if(t-=e.first,0>t||t>=e.size)throw new Error("There is no line "+(t+e.first)+" in the document.");for(var r=e;!r.lines;)for(var n=0;;++n){var i=r.children[n],o=i.chunkSize();if(o>t){r=i;break}t-=o}return r.lines[t]}function N(e,t,r){var n=[],i=t.line;return e.iter(t.line,r.line+1,function(e){var o=e.text;i==r.line&&(o=o.slice(0,r.ch)),i==t.line&&(o=o.slice(t.ch)),n.push(o),++i}),n}function O(e,t,r){var n=[];return e.iter(t,r,function(e){n.push(e.text)}),n}function W(e,t){var r=t-e.height;if(r)for(var n=e;n;n=n.parent)n.height+=r}function A(e){if(null==e.parent)return null;for(var t=e.parent,r=h(t.lines,e),n=t.parent;n;t=n,n=n.parent)for(var i=0;n.children[i]!=t;++i)r+=n.children[i].chunkSize();return r+t.first}function D(e,t){var r=e.first;e:do{for(var n=0;nt){e=i;continue e}t-=o,r+=i.chunkSize()}return r}while(!e.lines);for(var l=0;lt)break;t-=a}return r+l}function H(e,t){return t>=e.first&&tr?E(r,M(e,r).text.length):V(t,M(e,t.line).text.length)}function V(e,t){var r=e.ch;return null==r||r>t?E(e.line,t):0>r?E(e.line,0):e}function K(e,t){for(var r=[],n=0;n=t:o.to>t);(n||(n=[])).push(new Y(l,o.from,a?null:o.to))}}return n}function Q(e,t,r){var n;if(e)for(var i=0;i=t:o.to>t);if(s||o.from==t&&"bookmark"==l.type&&(!r||o.marker.insertLeft)){var a=null==o.from||(l.inclusiveLeft?o.from<=t:o.from0&&s)for(var x=0;xC;++C)y.push(b);y.push(a)}return y}function et(e){for(var t=0;t0)){var c=[a,1],f=F(u.from,s.from),d=F(u.to,s.to);(0>f||!l.inclusiveLeft&&!f)&&c.push({from:u.from,to:s.from}),(d>0||!l.inclusiveRight&&!d)&&c.push({from:s.to,to:u.to}),i.splice.apply(i,c),a+=c.length-3}}return i}function rt(e){var t=e.markedSpans;if(t){for(var r=0;r=0&&0>=f||0>=c&&f>=0)&&(0>=c&&(a.marker.inclusiveRight&&i.inclusiveLeft?F(u.to,r)>=0:F(u.to,r)>0)||c>=0&&(a.marker.inclusiveRight&&i.inclusiveLeft?F(u.from,n)<=0:F(u.from,n)<0)))return!0}}}function ft(e){for(var t;t=at(e);)e=t.find(-1,!0).line;return e}function ht(e){for(var t;t=ut(e);)e=t.find(1,!0).line;return e}function dt(e){for(var t,r;t=ut(e);)e=t.find(1,!0).line,(r||(r=[])).push(e);return r}function pt(e,t){var r=M(e,t),n=ft(r);return r==n?t:A(n)}function gt(e,t){if(t>e.lastLine())return t;var r,n=M(e,t);if(!vt(e,n))return t;for(;r=ut(n);)n=r.find(1,!0).line;return A(n)+1}function vt(e,t){var r=Hs&&t.markedSpans;if(r)for(var n=void 0,i=0;it.maxLineLength&&(t.maxLineLength=r,t.maxLine=e)})}function xt(e,t,r,n){if(!e)return n(t,r,"ltr");for(var i=!1,o=0;ot||t==r&&l.to==t)&&(n(Math.max(l.from,t),Math.min(l.to,r),1==l.level?"rtl":"ltr"),i=!0)}i||n(t,r,"ltr")}function Ct(e,t,r){var n;Ps=null;for(var i=0;it)return i;o.to==t&&(o.from!=o.to&&"before"==r?n=i:Ps=i),o.from==t&&(o.from!=o.to&&"before"!=r?n=i:Ps=i)}return null!=n?n:Ps}function St(e,t){var r=e.order;return null==r&&(r=e.order=Es(e.text,t)),r}function Lt(e,t,r){var n=L(e.text,t+r,r);return 0>n||n>e.text.length?null:n}function Tt(e,t,r){var n=Lt(e,t.ch,r);return null==n?null:new E(t.line,n,0>r?"after":"before")}function kt(e,t,r,n,i){if(e){var o=St(r,t.doc.direction);if(o){var l,s=0>i?g(o):o[0],a=0>i==(1==s.level),u=a?"after":"before";if(s.level>0){var c=qr(t,r);l=0>i?r.text.length-1:0;var f=Zr(t,c,l).top;l=T(function(e){return Zr(t,c,e).top==f},0>i==(1==s.level)?s.from:s.to-1,l),"before"==u&&(l=Lt(r,l,1,!0))}else l=0>i?s.to:s.from;return new E(n,l,u)}}return new E(n,0>i?r.text.length:0,0>i?"before":"after")}function Mt(e,t,r,n){var i=St(t,e.doc.direction);if(!i)return Tt(t,r,n);r.ch>=t.text.length?(r.ch=t.text.length,r.sticky="before"):r.ch<=0&&(r.ch=0,r.sticky="after");var o=Ct(i,r.ch,r.sticky),l=i[o];if("ltr"==e.doc.direction&&l.level%2==0&&(n>0?l.to>r.ch:l.fromn,h=a(r,f?1:-1);if(null!=h&&(f?h<=l.to&&h<=c.end:h>=l.from&&h>=c.begin)){var d=f?"before":"after";return new E(r.line,h,d)}}var p=function(e,t,n){for(var o=function(e,t){return t?new E(r.line,a(e,1),"before"):new E(r.line,e,"after")};e>=0&&e0==(1!=l.level),u=s?n.begin:a(n.end,-1);if(l.from<=u&&u0?c.end:a(c.begin,-1);return null==v||n>0&&v==t.text.length||!(g=p(n>0?0:i.length-1,n,u(v)))?null:g}function Nt(e,t){return e._handlers&&e._handlers[t]||Fs}function Ot(e,t,r){if(e.removeEventListener)e.removeEventListener(t,r,!1);else if(e.detachEvent)e.detachEvent("on"+t,r);else{var n=e._handlers,i=n&&n[t];if(i){var o=h(i,r);o>-1&&(n[t]=i.slice(0,o).concat(i.slice(o+1)))}}}function Wt(e,t){var r=Nt(e,t);if(r.length)for(var n=Array.prototype.slice.call(arguments,2),i=0;i0}function Pt(e){e.prototype.on=function(e,t){Is(this,e,t)},e.prototype.off=function(e,t){Ot(this,e,t)}}function Et(e){e.preventDefault?e.preventDefault():e.returnValue=!1}function Ft(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0}function It(e){return null!=e.defaultPrevented?e.defaultPrevented:0==e.returnValue}function zt(e){Et(e),Ft(e)}function Rt(e){return e.target||e.srcElement}function Bt(e){var t=e.which;return null==t&&(1&e.button?t=1:2&e.button?t=3:4&e.button&&(t=2)),hs&&e.ctrlKey&&1==t&&(t=3),t}function Gt(e){if(null==Cs){var t=n("span","​");r(e,n("span",[t,document.createTextNode("x")])),0!=e.firstChild.offsetHeight&&(Cs=t.offsetWidth<=1&&t.offsetHeight>2&&!(es&&8>ts))}var i=Cs?n("span","​"):n("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px");return i.setAttribute("cm-text",""),i}function Ut(e){if(null!=Ss)return Ss;var n=r(e,document.createTextNode("AخA")),i=vs(n,0,1).getBoundingClientRect(),o=vs(n,1,2).getBoundingClientRect();return t(e),i&&i.left!=i.right?Ss=o.right-i.right<3:!1}function Vt(e){if(null!=Us)return Us;var t=r(e,n("span","x")),i=t.getBoundingClientRect(),o=vs(t,0,1).getBoundingClientRect();return Us=Math.abs(i.left-o.left)>1}function Kt(e,t){arguments.length>2&&(t.dependencies=Array.prototype.slice.call(arguments,2)),Vs[e]=t}function jt(e,t){Ks[e]=t}function Xt(e){if("string"==typeof e&&Ks.hasOwnProperty(e))e=Ks[e];else if(e&&"string"==typeof e.name&&Ks.hasOwnProperty(e.name)){var t=Ks[e.name];"string"==typeof t&&(t={name:t}),e=b(t,e),e.name=t.name}else{if("string"==typeof e&&/^[\w\-]+\/[\w\-]+\+xml$/.test(e))return Xt("application/xml");if("string"==typeof e&&/^[\w\-]+\/[\w\-]+\+json$/.test(e))return Xt("application/json")}return"string"==typeof e?{name:e}:e||{name:"null"}}function Yt(e,t){t=Xt(t);var r=Vs[t.name];if(!r)return Yt(e,"text/plain");var n=r(e,t);if(js.hasOwnProperty(t.name)){var i=js[t.name];for(var o in i)i.hasOwnProperty(o)&&(n.hasOwnProperty(o)&&(n["_"+o]=n[o]),n[o]=i[o])}if(n.name=t.name,t.helperType&&(n.helperType=t.helperType),t.modeProps)for(var l in t.modeProps)n[l]=t.modeProps[l];return n}function _t(e,t){var r=js.hasOwnProperty(e)?js[e]:js[e]={};c(t,r)}function $t(e,t){if(t===!0)return t;if(e.copyState)return e.copyState(t);var r={};for(var n in t){var i=t[n];i instanceof Array&&(i=i.concat([])),r[n]=i}return r}function qt(e,t){for(var r;e.innerMode&&(r=e.innerMode(t),r&&r.mode!=e);)t=r.state,e=r.mode;return r||{mode:e,state:t}}function Zt(e,t,r){return e.startState?e.startState(t,r):!0}function Qt(e,t,r,n){var i=[e.state.modeGen],o={};lr(e,t.text,e.doc.mode,r,function(e,t){return i.push(e,t)},o,n);for(var l=function(r){var n=e.state.overlays[r],l=1,s=0;lr(e,t.text,n.mode,!0,function(e,t){for(var r=l;e>s;){var o=i[l];o>e&&i.splice(l,1,e,i[l+1],o),l+=2,s=Math.min(e,o)}if(t)if(n.opaque)i.splice(r,l-r,e,"overlay "+t),l=r+2;else for(;l>r;r+=2){var a=i[r+1];i[r+1]=(a?a+" ":"")+"overlay "+t}},o)},s=0;se.options.maxHighlightLength?$t(e.doc.mode,n):n);t.stateAfter=n,t.styles=i.styles,i.classes?t.styleClasses=i.classes:t.styleClasses&&(t.styleClasses=null),r===e.doc.frontier&&e.doc.frontier++}return t.styles}function er(e,t,r){var n=e.doc,i=e.display;if(!n.mode.startState)return!0;var o=sr(e,t,r),l=o>n.first&&M(n,o-1).stateAfter;return l=l?$t(n.mode,l):Zt(n.mode),n.iter(o,t,function(r){tr(e,r.text,l);var s=o==t-1||o%5==0||o>=i.viewFrom&&oi;i++){n&&(n[0]=qt(e,r).mode);var o=e.token(t,r);if(t.pos>t.start)return o}throw new Error("Mode "+e.name+" failed to advance stream.")}function ir(e,t,r,n){var i,o=function(e){return{start:f.start,end:f.pos,string:f.current(),type:i||null,state:e?$t(l.mode,c):c}},l=e.doc,s=l.mode;t=U(l,t);var a,u=M(l,t.line),c=er(e,t.line,r),f=new Xs(u.text,e.options.tabSize);for(n&&(a=[]);(n||f.pose.options.maxHighlightLength?(s=!1,l&&tr(e,t,n,f.pos),f.pos=t.length,a=null):a=or(nr(r,f,n,h),o),h){var d=h[0].name;d&&(a="m-"+(a?d+" "+a:d))}if(!s||c!=a){for(;ul;--s){if(s<=o.first)return o.first;var a=M(o,s-1);if(a.stateAfter&&(!r||s<=o.frontier))return s;var u=f(a.text,null,e.options.tabSize);(null==i||n>u)&&(i=s-1,n=u)}return i}function ar(e,t,r,n){e.text=t,e.stateAfter&&(e.stateAfter=null),e.styles&&(e.styles=null),null!=e.order&&(e.order=null),rt(e),nt(e,r);var i=n?n(e):1;i!=e.height&&W(e,i)}function ur(e){e.parent=null,rt(e)}function cr(e,t){if(!e||/^\s*$/.test(e))return null;var r=t.addModeClass?qs:$s;return r[e]||(r[e]=e.replace(/\S+/g,"cm-$&"))}function fr(e,t){var r=i("span",null,null,rs?"padding-right: .1px":null),n={pre:i("pre",[r],"CodeMirror-line"),content:r,col:0,pos:0,cm:e,trailingSpace:!1,splitSpaces:(es||rs)&&e.getOption("lineWrapping")};t.measure={};for(var o=0;o<=(t.rest?t.rest.length:0);o++){var l=o?t.rest[o-1]:t.line,s=void 0;n.pos=0,n.addToken=dr,Ut(e.display.measure)&&(s=St(l,e.doc.direction))&&(n.addToken=gr(n.addToken,s)),n.map=[];var u=t!=e.display.externalMeasured&&A(l);mr(l,n,Jt(e,l,u)),l.styleClasses&&(l.styleClasses.bgClass&&(n.bgClass=a(l.styleClasses.bgClass,n.bgClass||"")),l.styleClasses.textClass&&(n.textClass=a(l.styleClasses.textClass,n.textClass||""))),0==n.map.length&&n.map.push(0,0,n.content.appendChild(Gt(e.display.measure))),0==o?(t.measure.map=n.map,t.measure.cache={}):((t.measure.maps||(t.measure.maps=[])).push(n.map),(t.measure.caches||(t.measure.caches=[])).push({}))}if(rs){var c=n.content.lastChild;(/\bcm-tab\b/.test(c.className)||c.querySelector&&c.querySelector(".cm-tab"))&&(n.content.className="cm-tab-wrap-hack")}return Wt(e,"renderLine",e,t.line,n.pre),n.pre.className&&(n.textClass=a(n.pre.className,n.textClass||"")),n}function hr(e){var t=n("span","•","cm-invalidchar");return t.title="\\u"+e.charCodeAt(0).toString(16),t.setAttribute("aria-label",t.title),t}function dr(e,t,r,i,o,l,s){if(t){var a,u=e.splitSpaces?pr(t,e.trailingSpace):t,c=e.cm.state.specialChars,f=!1;if(c.test(t)){a=document.createDocumentFragment();for(var h=0;;){c.lastIndex=h;var d=c.exec(t),g=d?d.index-h:t.length-h;if(g){var v=document.createTextNode(u.slice(h,h+g));a.appendChild(es&&9>ts?n("span",[v]):v),e.map.push(e.pos,e.pos+g,v),e.col+=g,e.pos+=g}if(!d)break;h+=g+1;var m=void 0;if(" "==d[0]){var y=e.cm.options.tabSize,b=y-e.col%y;m=a.appendChild(n("span",p(b),"cm-tab")),m.setAttribute("role","presentation"),m.setAttribute("cm-text"," "),e.col+=b}else"\r"==d[0]||"\n"==d[0]?(m=a.appendChild(n("span","\r"==d[0]?"␍":"␤","cm-invalidchar")),m.setAttribute("cm-text",d[0]),e.col+=1):(m=e.cm.options.specialCharPlaceholder(d[0]),m.setAttribute("cm-text",d[0]),a.appendChild(es&&9>ts?n("span",[m]):m),e.col+=1);e.map.push(e.pos,e.pos+1,m),e.pos++}}else e.col+=t.length,a=document.createTextNode(u),e.map.push(e.pos,e.pos+t.length,a),es&&9>ts&&(f=!0),e.pos+=t.length;if(e.trailingSpace=32==u.charCodeAt(t.length-1),r||i||o||f||s){var w=r||"";i&&(w+=i),o&&(w+=o);var x=n("span",[a],w,s);return l&&(x.title=l),e.content.appendChild(x)}e.content.appendChild(a)}}function pr(e,t){if(e.length>1&&!/ /.test(e))return e;for(var r=t,n="",i=0;iu&&f.from<=u));h++);if(f.to>=c)return e(r,n,i,o,l,s,a);e(r,n.slice(0,f.to-u),i,o,null,s,a),o=null,n=n.slice(f.to-u),u=f.to}}}function vr(e,t,r,n){var i=!n&&r.widgetNode;i&&e.map.push(e.pos,e.pos+t,i),!n&&e.cm.display.input.needsContentAttribute&&(i||(i=e.content.appendChild(document.createElement("span"))),i.setAttribute("cm-marker",r.id)),i&&(e.cm.display.input.setUneditable(i),e.content.appendChild(i)),e.pos+=t,e.trailingSpace=!1}function mr(e,t,r){var n=e.markedSpans,i=e.text,o=0;if(n)for(var l,s,a,u,c,f,h,d=i.length,p=0,g=1,v="",m=0;;){if(m==p){a=u=c=f=s="",h=null,m=1/0;for(var y=[],b=void 0,w=0;wp||C.collapsed&&x.to==p&&x.from==p)?(null!=x.to&&x.to!=p&&m>x.to&&(m=x.to,u=""),C.className&&(a+=" "+C.className),C.css&&(s=(s?s+";":"")+C.css),C.startStyle&&x.from==p&&(c+=" "+C.startStyle),C.endStyle&&x.to==m&&(b||(b=[])).push(C.endStyle,x.to),C.title&&!f&&(f=C.title),C.collapsed&&(!h||lt(h.marker,C)<0)&&(h=x)):x.from>p&&m>x.from&&(m=x.from)}if(b)for(var S=0;S=d)break;for(var T=Math.min(d,m);;){if(v){var k=p+v.length;if(!h){var M=k>T?v.slice(0,T-p):v;t.addToken(t,M,l?l+a:a,c,p+M.length==m?u:"",f,s)}if(k>=T){v=v.slice(T-p),p=T;break}p=k,c=""}v=i.slice(o,o=r[g++]),l=cr(r[g++],t.cm.options)}}else for(var N=1;No;o=n){var l=new yr(e.doc,M(e.doc,o),o);n=o+l.size,i.push(l)}return i}function wr(e){Zs?Zs.ops.push(e):e.ownsGroup=Zs={ops:[e],delayedCallbacks:[]}}function xr(e){var t=e.delayedCallbacks,r=0;do{for(;rts&&(e.node.style.zIndex=2)),e.node}function Mr(e,t){var r=t.bgClass?t.bgClass+" "+(t.line.bgClass||""):t.line.bgClass;if(r&&(r+=" CodeMirror-linebackground"),t.background)r?t.background.className=r:(t.background.parentNode.removeChild(t.background),t.background=null);else if(r){var i=kr(t);t.background=i.insertBefore(n("div",null,r),i.firstChild),e.display.input.setUneditable(t.background)}}function Nr(e,t){var r=e.display.externalMeasured;return r&&r.line==t.line?(e.display.externalMeasured=null,t.measure=r.measure,r.built):fr(e,t)}function Or(e,t){var r=t.text.className,n=Nr(e,t);t.text==t.node&&(t.node=n.pre),t.text.parentNode.replaceChild(n.pre,t.text),t.text=n.pre,n.bgClass!=t.bgClass||n.textClass!=t.textClass?(t.bgClass=n.bgClass,t.textClass=n.textClass,Wr(e,t)):r&&(t.text.className=r)}function Wr(e,t){Mr(e,t),t.line.wrapClass?kr(t).className=t.line.wrapClass:t.node!=t.text&&(t.node.className="");var r=t.textClass?t.textClass+" "+(t.line.textClass||""):t.line.textClass;t.text.className=r||""}function Ar(e,t,r,i){if(t.gutter&&(t.node.removeChild(t.gutter),t.gutter=null),t.gutterBackground&&(t.node.removeChild(t.gutterBackground),t.gutterBackground=null),t.line.gutterClass){var o=kr(t);t.gutterBackground=n("div",null,"CodeMirror-gutter-background "+t.line.gutterClass,"left: "+(e.options.fixedGutter?i.fixedPos:-i.gutterTotalWidth)+"px; width: "+i.gutterTotalWidth+"px"),e.display.input.setUneditable(t.gutterBackground),o.insertBefore(t.gutterBackground,t.text)}var l=t.line.gutterMarkers;if(e.options.lineNumbers||l){var s=kr(t),a=t.gutter=n("div",null,"CodeMirror-gutter-wrapper","left: "+(e.options.fixedGutter?i.fixedPos:-i.gutterTotalWidth)+"px");if(e.display.input.setUneditable(a),s.insertBefore(a,t.text),t.line.gutterClass&&(a.className+=" "+t.line.gutterClass),!e.options.lineNumbers||l&&l["CodeMirror-linenumbers"]||(t.lineNumber=a.appendChild(n("div",P(e.options,r),"CodeMirror-linenumber CodeMirror-gutter-elt","left: "+i.gutterLeft["CodeMirror-linenumbers"]+"px; width: "+e.display.lineNumInnerWidth+"px"))),l)for(var u=0;u2&&o.push((a.bottom+u.top)/2-r.top)}}o.push(r.bottom-r.top)}}function Xr(e,t,r){if(e.line==t)return{map:e.measure.map,cache:e.measure.cache};for(var n=0;nr)return{map:e.measure.maps[i],cache:e.measure.caches[i],before:!0}}function Yr(e,t){t=ft(t);var n=A(t),i=e.display.externalMeasured=new yr(e.doc,t,n);i.lineN=n;var o=i.built=fr(e,i);return i.text=o.pre,r(e.display.lineMeasure,o.pre),i}function _r(e,t,r,n){return Zr(e,qr(e,t),r,n)}function $r(e,t){if(t>=e.display.viewFrom&&t=r.lineN&&tt?(i=0,o=1,l="left"):a>t?(i=t-s,o=i+1):(u==e.length-3||t==a&&e[u+3]>t)&&(o=a-s,i=o-1,t>=a&&(l="right")),null!=i){if(n=e[u+2],s==a&&r==(n.insertLeft?"left":"right")&&(l=r),"left"==r&&0==i)for(;u&&e[u-2]==e[u-3]&&e[u-1].insertLeft;)n=e[(u-=3)+2],l="left";if("right"==r&&i==a-s)for(;u=0&&(r=e[i]).left==r.right;i--);return r}function en(e,t,r,n){var i,o=Qr(t.map,r,n),l=o.node,s=o.start,a=o.end,u=o.collapse;if(3==l.nodeType){for(var c=0;4>c;c++){for(;s&&S(t.line.text.charAt(o.coverStart+s));)--s;for(;o.coverStart+ats&&0==s&&a==o.coverEnd-o.coverStart?l.parentNode.getBoundingClientRect():Jr(vs(l,s,a).getClientRects(),n),i.left||i.right||0==s)break;a=s,s-=1,u="right"}es&&11>ts&&(i=tn(e.display.measure,i))}else{s>0&&(u=n="right");var f;i=e.options.lineWrapping&&(f=l.getClientRects()).length>1?f["right"==n?f.length-1:0]:l.getBoundingClientRect()}if(es&&9>ts&&!s&&(!i||!i.left&&!i.right)){var h=l.parentNode.getClientRects()[0];i=h?{left:h.left,right:h.left+bn(e.display),top:h.top,bottom:h.bottom}:Js}for(var d=i.top-t.rect.top,p=i.bottom-t.rect.top,g=(d+p)/2,v=t.view.measure.heights,m=0;m=n.text.length?(u=n.text.length,c="before"):0>=u&&(u=0,c="after"),!a)return l("before"==c?u-1:u,"before"==c);var f=Ct(a,u,c),h=Ps,d=s(u,f,"before"==c);return null!=h&&(d.other=s(u,h,"before"!=c)),d}function hn(e,t){var r=0;t=U(e.doc,t),e.options.lineWrapping||(r=bn(e.display)*t.ch);var n=M(e.doc,t.line),i=yt(n)+Rr(e.display);return{left:r,right:r,top:i,bottom:i+n.height}}function dn(e,t,r,n,i){var o=E(e,t,r);return o.xRel=i,n&&(o.outside=!0),o}function pn(e,t,r){var n=e.doc;if(r+=e.display.viewOffset,0>r)return dn(n.first,0,null,!0,-1);var i=D(n,r),o=n.first+n.size-1;if(i>o)return dn(n.first+n.size-1,M(n,o).text.length,null,!0,1);0>t&&(t=0);for(var l=M(n,i);;){var s=mn(e,l,i,t,r),a=ut(l),u=a&&a.find(0,!0);if(!a||!(s.ch>u.from.ch||s.ch==u.from.ch&&s.xRel>0))return s;i=A(l=u.to.line)}}function gn(e,t,r,n){var i=function(n){return an(e,t,Zr(e,r,n),"line")},o=t.text.length,l=T(function(e){return i(e-1).bottom<=n},o,0);return o=T(function(e){return i(e).top>n},l,o),{begin:l,end:o}}function vn(e,t,r,n){var i=an(e,t,Zr(e,r,n),"line").top;return gn(e,t,r,i)}function mn(e,t,r,n,i){i-=yt(t);var o,l=0,s=t.text.length,a=qr(e,t),u=St(t,e.doc.direction);if(u){if(e.options.lineWrapping){var c;c=gn(e,t,a,i),l=c.begin,s=c.end,c}o=new E(r,l);var f,h,d=fn(e,o,"line",t,a).left,p=n>d?1:-1,g=d-n;do{if(f=g,h=o,o=Mt(e,t,o,p),null==o||o.chp!=0>g&&Math.abs(g)<=Math.abs(f));if(Math.abs(g)>Math.abs(f)){if(0>g==0>f)throw new Error("Broke out of infinite loop in coordsCharInner");o=h}}else{var v=T(function(r){var o=an(e,t,Zr(e,a,r),"line");return o.top>i?(s=Math.min(r,s),!0):o.bottom<=i?!1:o.left>n?!0:o.rightm.right?1:0,o}function yn(e){if(null!=e.cachedTextHeight)return e.cachedTextHeight;if(null==_s){_s=n("pre");for(var i=0;49>i;++i)_s.appendChild(document.createTextNode("x")),_s.appendChild(n("br"));_s.appendChild(document.createTextNode("x"))}r(e.measure,_s);var o=_s.offsetHeight/50;return o>3&&(e.cachedTextHeight=o),t(e.measure),o||1}function bn(e){if(null!=e.cachedCharWidth)return e.cachedCharWidth;var t=n("span","xxxxxxxxxx"),i=n("pre",[t]);r(e.measure,i);var o=t.getBoundingClientRect(),l=(o.right-o.left)/10;return l>2&&(e.cachedCharWidth=l),l||10}function wn(e){for(var t=e.display,r={},n={},i=t.gutters.clientLeft,o=t.gutters.firstChild,l=0;o;o=o.nextSibling,++l)r[e.options.gutters[l]]=o.offsetLeft+o.clientLeft+i,n[e.options.gutters[l]]=o.clientWidth;return{fixedPos:xn(t),gutterTotalWidth:t.gutters.offsetWidth,gutterLeft:r,gutterWidth:n,wrapperWidth:t.wrapper.clientWidth}}function xn(e){return e.scroller.getBoundingClientRect().left-e.sizer.getBoundingClientRect().left}function Cn(e){var t=yn(e.display),r=e.options.lineWrapping,n=r&&Math.max(5,e.display.scroller.clientWidth/bn(e.display)-3);return function(i){if(vt(e.doc,i))return 0;var o=0;if(i.widgets)for(var l=0;l=e.display.viewTo)return null;if(t-=e.display.viewFrom,0>t)return null;for(var r=e.display.view,n=0;nt)return n}function kn(e){e.display.input.showSelection(e.display.input.prepareSelection())}function Mn(e,t){for(var r=e.doc,n={},i=n.cursors=document.createDocumentFragment(),o=n.selection=document.createDocumentFragment(),l=0;l=e.display.viewTo||s.to().linet&&(t=0),t=Math.round(t),i=Math.round(i),a.appendChild(n("div",null,"CodeMirror-selected","position: absolute; left: "+e+"px;\n top: "+t+"px; width: "+(null==r?f-e:r)+"px;\n height: "+(i-t)+"px"))}function o(t,r,n){function o(r,n){return cn(e,E(t,r),"div",u,n)}var l,a,u=M(s,t),h=u.text.length;return xt(St(u,s.direction),r||0,null==n?h:n,function(e,t,s){var u,d,p,g=o(e,"left");if(e==t)u=g,d=p=g.left;else{if(u=o(t-1,"right"),"rtl"==s){var v=g;g=u,u=v}d=g.left,p=u.right}null==r&&0==e&&(d=c),u.top-g.top>3&&(i(d,g.top,null,g.bottom),d=c,g.bottoma.bottom||u.bottom==a.bottom&&u.right>a.right)&&(a=u),c+1>d&&(d=c),i(d,u.top,p-d,u.bottom)}),{start:l,end:a}}var l=e.display,s=e.doc,a=document.createDocumentFragment(),u=Gr(e.display),c=u.left,f=Math.max(l.sizerWidth,Vr(e)-l.sizer.offsetLeft)-u.right,h=t.from(),d=t.to();if(h.line==d.line)o(h.line,h.ch,d.ch);else{var p=M(s,h.line),g=M(s,d.line),v=ft(p)==ft(g),m=o(h.line,h.ch,v?p.text.length+1:null).end,y=o(d.line,v?0:null,d.ch).start;v&&(m.top0?t.blinker=setInterval(function(){return t.cursorDiv.style.visibility=(r=!r)?"":"hidden"},e.options.cursorBlinkRate):e.options.cursorBlinkRate<0&&(t.cursorDiv.style.visibility="hidden")}}function An(e){e.state.focused||(e.display.input.focus(),Hn(e))}function Dn(e){e.state.delayingBlurEvent=!0,setTimeout(function(){e.state.delayingBlurEvent&&(e.state.delayingBlurEvent=!1,Pn(e))},100)}function Hn(e,t){e.state.delayingBlurEvent&&(e.state.delayingBlurEvent=!1),"nocursor"!=e.options.readOnly&&(e.state.focused||(Wt(e,"focus",e,t),e.state.focused=!0,s(e.display.wrapper,"CodeMirror-focused"),e.curOp||e.display.selForContextMenu==e.doc.sel||(e.display.input.reset(),rs&&setTimeout(function(){return e.display.input.reset(!0)},20)),e.display.input.receivedFocus()),Wn(e))}function Pn(e,t){e.state.delayingBlurEvent||(e.state.focused&&(Wt(e,"blur",e,t),e.state.focused=!1,bs(e.display.wrapper,"CodeMirror-focused")),clearInterval(e.display.blinker),setTimeout(function(){e.state.focused||(e.display.shift=!1)},150))}function En(e){var t=e.display,r=t.view;if(t.alignWidgets||t.gutters.firstChild&&e.options.fixedGutter){for(var n=xn(t)-t.scroller.scrollLeft+e.doc.scrollLeft,i=t.gutters.offsetWidth,o=n+"px",l=0;lts){var l=i.node.offsetTop+i.node.offsetHeight;o=l-r,r=l}else{var s=i.node.getBoundingClientRect();o=s.bottom-s.top}var a=i.line.height-o;if(2>o&&(o=yn(t)),(a>.001||-.001>a)&&(W(i.line,o),zn(i.line),i.rest))for(var u=0;us?(o=s,l=D(t,yt(M(t,s))+e.wrapper.clientHeight)):Math.min(a,t.lastLine())>=l&&(o=D(t,yt(M(t,a))-e.wrapper.clientHeight),l=a)}return{from:o,to:Math.max(l,o+1)}}function Bn(e,t){Math.abs(e.doc.scrollTop-t)<2||(e.doc.scrollTop=t,ql||Ti(e,{top:t}),e.display.scroller.scrollTop!=t&&(e.display.scroller.scrollTop=t),e.display.scrollbars.setScrollTop(t),ql&&Ti(e),wi(e,100))}function Gn(e,t,r){(r?t==e.doc.scrollLeft:Math.abs(e.doc.scrollLeft-t)<2)||(t=Math.min(t,e.display.scroller.scrollWidth-e.display.scroller.clientWidth),e.doc.scrollLeft=t,En(e),e.display.scroller.scrollLeft!=t&&(e.display.scroller.scrollLeft=t),e.display.scrollbars.setScrollLeft(t))}function Un(e){var t=e.wheelDeltaX,r=e.wheelDeltaY;return null==t&&e.detail&&e.axis==e.HORIZONTAL_AXIS&&(t=e.detail),null==r&&e.detail&&e.axis==e.VERTICAL_AXIS?r=e.detail:null==r&&(r=e.wheelDelta),{x:t,y:r}}function Vn(e){var t=Un(e);return t.x*=ta,t.y*=ta,t}function Kn(e,t){var r=Un(t),n=r.x,i=r.y,o=e.display,l=o.scroller,s=l.scrollWidth>l.clientWidth,a=l.scrollHeight>l.clientHeight;if(n&&s||i&&a){if(i&&hs&&rs)e:for(var u=t.target,c=o.view;u!=l;u=u.parentNode)for(var f=0;fh?d=Math.max(0,d+h-50):p=Math.min(e.doc.height,p+h+50),Ti(e,{top:d,bottom:p})}20>ea&&(null==o.wheelStartX?(o.wheelStartX=l.scrollLeft,o.wheelStartY=l.scrollTop,o.wheelDX=n,o.wheelDY=i,setTimeout(function(){if(null!=o.wheelStartX){var e=l.scrollLeft-o.wheelStartX,t=l.scrollTop-o.wheelStartY,r=t&&o.wheelDY&&t/o.wheelDY||e&&o.wheelDX&&e/o.wheelDX;o.wheelStartX=o.wheelStartY=null,r&&(ta=(ta*ea+r)/(ea+1),++ea)}},200)):(o.wheelDX+=n,o.wheelDY+=i))}}function jn(e){var t=e.display,r=t.gutters.offsetWidth,n=Math.round(e.doc.height+Br(e.display));return{clientHeight:t.scroller.clientHeight,viewHeight:t.wrapper.clientHeight,scrollWidth:t.scroller.scrollWidth,clientWidth:t.scroller.clientWidth,viewWidth:t.wrapper.clientWidth,barLeft:e.options.fixedGutter?r:0,docHeight:n,scrollHeight:n+Ur(e)+t.barHeight,nativeBarWidth:t.nativeBarWidth,gutterWidth:r}}function Xn(e,t){t||(t=jn(e));var r=e.display.barWidth,n=e.display.barHeight;Yn(e,t);for(var i=0;4>i&&r!=e.display.barWidth||n!=e.display.barHeight;i++)r!=e.display.barWidth&&e.options.lineWrapping&&In(e),Yn(e,jn(e)),r=e.display.barWidth,n=e.display.barHeight}function Yn(e,t){var r=e.display,n=r.scrollbars.update(t);r.sizer.style.paddingRight=(r.barWidth=n.right)+"px",r.sizer.style.paddingBottom=(r.barHeight=n.bottom)+"px",r.heightForcer.style.borderBottom=n.bottom+"px solid transparent",n.right&&n.bottom?(r.scrollbarFiller.style.display="block",r.scrollbarFiller.style.height=n.bottom+"px",r.scrollbarFiller.style.width=n.right+"px"):r.scrollbarFiller.style.display="",n.bottom&&e.options.coverGutterNextToScrollbar&&e.options.fixedGutter?(r.gutterFiller.style.display="block",r.gutterFiller.style.height=n.bottom+"px",r.gutterFiller.style.width=t.gutterWidth+"px"):r.gutterFiller.style.display=""}function _n(e){e.display.scrollbars&&(e.display.scrollbars.clear(),e.display.scrollbars.addClass&&bs(e.display.wrapper,e.display.scrollbars.addClass)),e.display.scrollbars=new ia[e.options.scrollbarStyle](function(t){e.display.wrapper.insertBefore(t,e.display.scrollbarFiller),Is(t,"mousedown",function(){e.state.focused&&setTimeout(function(){return e.display.input.focus()},0)}),t.setAttribute("cm-not-content","true")},function(t,r){"horizontal"==r?Gn(e,t):Bn(e,t)},e),e.display.scrollbars.addClass&&s(e.display.wrapper,e.display.scrollbars.addClass)}function $n(e,t){if(!At(e,"scrollCursorIntoView")){var r=e.display,i=r.sizer.getBoundingClientRect(),o=null;if(t.top+i.top<0?o=!0:t.bottom+i.top>(window.innerHeight||document.documentElement.clientHeight)&&(o=!1),null!=o&&!as){var l=n("div","​",null,"position: absolute;\n top: "+(t.top-r.viewOffset-Rr(e.display))+"px;\n height: "+(t.bottom-t.top+Ur(e)+r.barHeight)+"px;\n left: "+t.left+"px; width: "+Math.max(2,t.right-t.left)+"px;");e.display.lineSpace.appendChild(l),l.scrollIntoView(o),e.display.lineSpace.removeChild(l)}}}function qn(e,t,r,n){null==n&&(n=0);for(var i,o=0;5>o;o++){var l=!1,s=fn(e,t),a=r&&r!=t?fn(e,r):s;i={left:Math.min(s.left,a.left),top:Math.min(s.top,a.top)-n,right:Math.max(s.left,a.left),bottom:Math.max(s.bottom,a.bottom)+n};var u=Qn(e,i),c=e.doc.scrollTop,f=e.doc.scrollLeft;if(null!=u.scrollTop&&(Bn(e,u.scrollTop),Math.abs(e.doc.scrollTop-c)>1&&(l=!0)),null!=u.scrollLeft&&(Gn(e,u.scrollLeft),Math.abs(e.doc.scrollLeft-f)>1&&(l=!0)),!l)break}return i}function Zn(e,t){var r=Qn(e,t);null!=r.scrollTop&&Bn(e,r.scrollTop),null!=r.scrollLeft&&Gn(e,r.scrollLeft)}function Qn(e,t){var r=e.display,n=yn(e.display);t.top<0&&(t.top=0);var i=e.curOp&&null!=e.curOp.scrollTop?e.curOp.scrollTop:r.scroller.scrollTop,o=Kr(e),l={};t.bottom-t.top>o&&(t.bottom=t.top+o);var s=e.doc.height+Br(r),a=t.tops-n;if(t.topi+o){var c=Math.min(t.top,(u?s:t.bottom)-o);c!=i&&(l.scrollTop=c)}var f=e.curOp&&null!=e.curOp.scrollLeft?e.curOp.scrollLeft:r.scroller.scrollLeft,h=Vr(e)-(e.options.fixedGutter?r.gutters.offsetWidth:0),d=t.right-t.left>h;return d&&(t.right=t.left+h),t.left<10?l.scrollLeft=0:t.lefth+f-3&&(l.scrollLeft=t.right+(d?0:10)-h),l}function Jn(e,t,r){(null!=t||null!=r)&&ti(e),null!=t&&(e.curOp.scrollLeft=(null==e.curOp.scrollLeft?e.doc.scrollLeft:e.curOp.scrollLeft)+t),null!=r&&(e.curOp.scrollTop=(null==e.curOp.scrollTop?e.doc.scrollTop:e.curOp.scrollTop)+r)}function ei(e){ti(e);var t=e.getCursor(),r=t,n=t;e.options.lineWrapping||(r=t.ch?E(t.line,t.ch-1):t,n=E(t.line,t.ch+1)),e.curOp.scrollToPos={from:r,to:n,margin:e.options.cursorScrollMargin}}function ti(e){var t=e.curOp.scrollToPos;if(t){e.curOp.scrollToPos=null;var r=hn(e,t.from),n=hn(e,t.to),i=Qn(e,{left:Math.min(r.left,n.left),top:Math.min(r.top,n.top)-t.margin,right:Math.max(r.right,n.right),bottom:Math.max(r.bottom,n.bottom)+t.margin});e.scrollTo(i.scrollLeft,i.scrollTop)}}function ri(e){e.curOp={cm:e,viewChanged:!1,startHeight:e.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:++oa},wr(e.curOp)}function ni(e){var t=e.curOp;Cr(t,function(e){for(var t=0;t=r.viewTo)||r.maxLineChanged&&t.options.lineWrapping,e.update=e.mustUpdate&&new la(t,e.mustUpdate&&{top:e.scrollTop,ensure:e.scrollToPos},e.forceUpdate)}function li(e){e.updatedDisplay=e.mustUpdate&&Si(e.cm,e.update)}function si(e){var t=e.cm,r=t.display;e.updatedDisplay&&In(t),e.barMeasure=jn(t),r.maxLineChanged&&!t.options.lineWrapping&&(e.adjustWidthTo=_r(t,r.maxLine,r.maxLine.text.length).left+3,t.display.sizerWidth=e.adjustWidthTo,e.barMeasure.scrollWidth=Math.max(r.scroller.clientWidth,r.sizer.offsetLeft+e.adjustWidthTo+Ur(t)+t.display.barWidth),e.maxScrollLeft=Math.max(0,r.sizer.offsetLeft+e.adjustWidthTo-Vr(t))),(e.updatedDisplay||e.selectionChanged)&&(e.preparedSelection=r.input.prepareSelection(e.focus))}function ai(e){var t=e.cm;null!=e.adjustWidthTo&&(t.display.sizer.style.minWidth=e.adjustWidthTo+"px",e.maxScrollLeftt)&&(i.updateLineNumbers=t),e.curOp.viewChanged=!0,t>=i.viewTo)Hs&&pt(e.doc,t)i.viewFrom?vi(e):(i.viewFrom+=n,i.viewTo+=n);else if(t<=i.viewFrom&&r>=i.viewTo)vi(e);else if(t<=i.viewFrom){var o=mi(e,r,r+n,1);o?(i.view=i.view.slice(o.index),i.viewFrom=o.lineN,i.viewTo+=n):vi(e)}else if(r>=i.viewTo){var l=mi(e,t,t,-1);l?(i.view=i.view.slice(0,l.index),i.viewTo=l.lineN):vi(e)}else{var s=mi(e,t,t,-1),a=mi(e,r,r+n,1);s&&a?(i.view=i.view.slice(0,s.index).concat(br(e,s.lineN,a.lineN)).concat(i.view.slice(a.index)),i.viewTo+=n):vi(e)}var u=i.externalMeasured;u&&(r=i.lineN&&t=n.viewTo)){var o=n.view[Tn(e,t)];if(null!=o.node){var l=o.changes||(o.changes=[]);-1==h(l,r)&&l.push(r)}}}function vi(e){e.display.viewFrom=e.display.viewTo=e.doc.first,e.display.view=[],e.display.viewOffset=0}function mi(e,t,r,n){var i,o=Tn(e,t),l=e.display.view;if(!Hs||r==e.doc.first+e.doc.size)return{index:o,lineN:r};for(var s=e.display.viewFrom,a=0;o>a;a++)s+=l[a].size;if(s!=t){if(n>0){if(o==l.length-1)return null;i=s+l[o].size-t,o++}else i=s-t;t+=i,r+=i}for(;pt(e.doc,r)!=r;){if(o==(0>n?0:l.length-1))return null;r+=n*l[o-(0>n?1:0)].size,o+=n}return{index:o,lineN:r}}function yi(e,t,r){var n=e.display,i=n.view;0==i.length||t>=n.viewTo||r<=n.viewFrom?(n.view=br(e,t,r),n.viewFrom=t):(n.viewFrom>t?n.view=br(e,t,n.viewFrom).concat(n.view):n.viewFromr&&(n.view=n.view.slice(0,Tn(e,r)))),n.viewTo=r}function bi(e){for(var t=e.display.view,r=0,n=0;n=e.display.viewTo)){var r=+new Date+e.options.workTime,n=$t(t.mode,er(e,t.frontier)),i=[];t.iter(t.frontier,Math.min(t.first+t.size,e.display.viewTo+500),function(o){if(t.frontier>=e.display.viewFrom){var l=o.styles,s=o.text.length>e.options.maxHighlightLength,a=Qt(e,o,s?$t(t.mode,n):n,!0);o.styles=a.styles;var u=o.styleClasses,c=a.classes;c?o.styleClasses=c:u&&(o.styleClasses=null);for(var f=!l||l.length!=o.styles.length||u!=c&&(!u||!c||u.bgClass!=c.bgClass||u.textClass!=c.textClass),h=0;!f&&hr?(wi(e,e.options.workDelay),!0):void 0}),i.length&&ci(e,function(){for(var t=0;t=n.viewFrom&&r.visible.to<=n.viewTo&&(null==n.updateLineNumbers||n.updateLineNumbers>=n.viewTo)&&n.renderedView==n.view&&0==bi(e))return!1;Fn(e)&&(vi(e),r.dims=wn(e));var o=i.first+i.size,s=Math.max(r.visible.from-e.options.viewportMargin,i.first),a=Math.min(o,r.visible.to+e.options.viewportMargin);n.viewFroma&&n.viewTo-a<20&&(a=Math.min(o,n.viewTo)),Hs&&(s=pt(e.doc,s),a=gt(e.doc,a));var u=s!=n.viewFrom||a!=n.viewTo||n.lastWrapHeight!=r.wrapperHeight||n.lastWrapWidth!=r.wrapperWidth;yi(e,s,a),n.viewOffset=yt(M(e.doc,n.viewFrom)),e.display.mover.style.top=n.viewOffset+"px";var c=bi(e);if(!u&&0==c&&!r.force&&n.renderedView==n.view&&(null==n.updateLineNumbers||n.updateLineNumbers>=n.viewTo))return!1;var f=l();return c>4&&(n.lineDiv.style.display="none"),ki(e,n.updateLineNumbers,r.dims),c>4&&(n.lineDiv.style.display=""),n.renderedView=n.view,f&&l()!=f&&f.offsetHeight&&f.focus(),t(n.cursorDiv),t(n.selectionDiv),n.gutters.style.height=n.sizer.style.minHeight=0,u&&(n.lastWrapHeight=r.wrapperHeight,n.lastWrapWidth=r.wrapperWidth,wi(e,400)),n.updateLineNumbers=null,!0}function Li(e,t){for(var r=t.viewport,n=!0;(n&&e.options.lineWrapping&&t.oldDisplayWidth!=Vr(e)||(r&&null!=r.top&&(r={top:Math.min(e.doc.height+Br(e.display)-Kr(e),r.top)}),t.visible=Rn(e.display,e.doc,r),!(t.visible.from>=e.display.viewFrom&&t.visible.to<=e.display.viewTo)))&&Si(e,t);n=!1){In(e);var i=jn(e);kn(e),Xn(e,i),Ni(e,i)}t.signal(e,"update",e),(e.display.viewFrom!=e.display.reportedViewFrom||e.display.viewTo!=e.display.reportedViewTo)&&(t.signal(e,"viewportChange",e,e.display.viewFrom,e.display.viewTo),e.display.reportedViewFrom=e.display.viewFrom,e.display.reportedViewTo=e.display.viewTo)}function Ti(e,t){var r=new la(e,t);if(Si(e,r)){In(e),Li(e,r);var n=jn(e);kn(e),Xn(e,n),Ni(e,n),r.finish()}}function ki(e,r,n){function i(t){var r=t.nextSibling;return rs&&hs&&e.display.currentWheelTarget==t?t.style.display="none":t.parentNode.removeChild(t),r}for(var o=e.display,l=e.options.lineNumbers,s=o.lineDiv,a=s.firstChild,u=o.view,c=o.viewFrom,f=0;f=r&&d.lineNumber;d.changes&&(h(d.changes,"gutter")>-1&&(p=!1),Tr(e,d,c,n)),p&&(t(d.lineNumber),d.lineNumber.appendChild(document.createTextNode(P(e.options,c)))),a=d.node.nextSibling}else{var g=Hr(e,d,c,n);s.insertBefore(g,a)}c+=d.size}for(;a;)a=i(a)}function Mi(e){var t=e.display.gutters.offsetWidth;e.display.sizer.style.marginLeft=t+"px"}function Ni(e,t){e.display.sizer.style.minHeight=t.docHeight+"px",e.display.heightForcer.style.top=t.docHeight+"px",e.display.gutters.style.height=t.docHeight+e.display.barHeight+Ur(e)+"px"}function Oi(e){var r=e.display.gutters,i=e.options.gutters;t(r);for(var o=0;o-1&&!e.lineNumbers&&(e.gutters=e.gutters.slice(0),e.gutters.splice(t,1))}function Ai(e,t){var r=e[t];e.sort(function(e,t){return F(e.from(),t.from())}),t=h(e,r);for(var n=1;n=0){var l=B(o.from(),i.from()),s=R(o.to(),i.to()),a=o.empty()?i.from()==i.head:o.from()==o.head;t>=n&&--t,e.splice(--n,2,new aa(a?s:l,a?l:s))}}return new sa(e,t)}function Di(e,t){return new sa([new aa(e,t||e)],0)}function Hi(e){return e.text?E(e.from.line+e.text.length-1,g(e.text).length+(1==e.text.length?e.from.ch:0)):e.to}function Pi(e,t){if(F(e,t.from)<0)return e;if(F(e,t.to)<=0)return Hi(t);var r=e.line+t.text.length-(t.to.line-t.from.line)-1,n=e.ch;return e.line==t.to.line&&(n+=Hi(t).ch-t.to.ch),E(r,n)}function Ei(e,t){for(var r=[],n=0;no;++o)r.push(new Ys(u[o],i(o),n));return r}var s=t.from,a=t.to,u=t.text,c=M(e,s.line),f=M(e,a.line),h=g(u),d=i(u.length-1),p=a.line-s.line;if(t.full)e.insert(0,l(0,u.length)),e.remove(u.length,e.size-u.length);else if(Bi(e,t)){var v=l(0,u.length-1);o(f,f.text,d),p&&e.remove(s.line,p),v.length&&e.insert(s.line,v)}else if(c==f)if(1==u.length)o(c,c.text.slice(0,s.ch)+h+c.text.slice(a.ch),d);else{var m=l(1,u.length-1);m.push(new Ys(h+c.text.slice(a.ch),d,n)),o(c,c.text.slice(0,s.ch)+u[0],i(0)),e.insert(s.line+1,m)}else if(1==u.length)o(c,c.text.slice(0,s.ch)+u[0]+f.text.slice(a.ch),i(0)),e.remove(s.line+1,p);else{o(c,c.text.slice(0,s.ch)+u[0],i(0)),o(f,h+f.text.slice(a.ch),d);var y=l(1,u.length-1);p>1&&e.remove(s.line+1,p-1),e.insert(s.line+1,y) -}Sr(e,"change",e,t)}function Ui(e,t,r){function n(e,i,o){if(e.linked)for(var l=0;l1&&!e.done[e.done.length-2].ranges?(e.done.pop(),g(e.done)):void 0}function qi(e,t,r,n){var i=e.history;i.undone.length=0;var o,l,s=+new Date;if((i.lastOp==n||i.lastOrigin==t.origin&&t.origin&&("+"==t.origin.charAt(0)&&e.cm&&i.lastModTime>s-e.cm.options.historyEventDelay||"*"==t.origin.charAt(0)))&&(o=$i(i,i.lastOp==n)))l=g(o.changes),0==F(t.from,t.to)&&0==F(t.from,l.to)?l.to=Hi(t):o.changes.push(Yi(e,t));else{var a=g(i.done);for(a&&a.ranges||Ji(e.sel,i.done),o={changes:[Yi(e,t)],generation:i.generation},i.done.push(o);i.done.length>i.undoDepth;)i.done.shift(),i.done[0].ranges||i.done.shift()}i.done.push(r),i.generation=++i.maxGeneration,i.lastModTime=i.lastSelTime=s,i.lastOp=i.lastSelOp=n,i.lastOrigin=i.lastSelOrigin=t.origin,l||Wt(e,"historyAdded")}function Zi(e,t,r,n){var i=t.charAt(0);return"*"==i||"+"==i&&r.ranges.length==n.ranges.length&&r.somethingSelected()==n.somethingSelected()&&new Date-e.history.lastSelTime<=(e.cm?e.cm.options.historyEventDelay:500)}function Qi(e,t,r,n){var i=e.history,o=n&&n.origin;r==i.lastSelOp||o&&i.lastSelOrigin==o&&(i.lastModTime==i.lastSelTime&&i.lastOrigin==o||Zi(e,o,g(i.done),t))?i.done[i.done.length-1]=t:Ji(t,i.done),i.lastSelTime=+new Date,i.lastSelOrigin=o,i.lastSelOp=r,n&&n.clearRedo!==!1&&_i(i.undone)}function Ji(e,t){var r=g(t);r&&r.ranges&&r.equals(e)||t.push(e)}function eo(e,t,r,n){var i=t["spans_"+e.id],o=0;e.iter(Math.max(e.first,r),Math.min(e.first+e.size,n),function(r){r.markedSpans&&((i||(i=t["spans_"+e.id]={}))[o]=r.markedSpans),++o})}function to(e){if(!e)return null;for(var t,r=0;r-1&&(g(s)[f]=u[f],delete u[f])}}}return n}function oo(e,t,r,n){if(e.cm&&e.cm.display.shift||e.extend){var i=t.anchor;if(n){var o=F(r,i)<0;o!=F(n,i)<0?(i=r,r=n):o!=F(r,n)<0&&(r=n)}return new aa(i,r)}return new aa(n||r,r)}function lo(e,t,r,n){ho(e,new sa([oo(e,e.sel.primary(),t,r)],0),n)}function so(e,t,r){for(var n=[],i=0;i=t.ch:s.to>t.ch))){if(i&&(Wt(a,"beforeCursorEnter"),a.explicitlyCleared)){if(o.markedSpans){--l;continue}break}if(!a.atomic)continue;if(r){var u=a.find(0>n?1:-1),c=void 0;if((0>n?a.inclusiveRight:a.inclusiveLeft)&&(u=wo(e,u,-n,u&&u.line==t.line?o:null)),u&&u.line==t.line&&(c=F(u,r))&&(0>n?0>c:c>0))return yo(e,u,t,n,i)}var f=a.find(0>n?-1:1);return(0>n?a.inclusiveLeft:a.inclusiveRight)&&(f=wo(e,f,n,f.line==t.line?o:null)),f?yo(e,f,t,n,i):null}}return t}function bo(e,t,r,n,i){var o=n||1,l=yo(e,t,r,o,i)||!i&&yo(e,t,r,o,!0)||yo(e,t,r,-o,i)||!i&&yo(e,t,r,-o,!0);return l?l:(e.cantEdit=!0,E(e.first,0))}function wo(e,t,r,n){return 0>r&&0==t.ch?t.line>e.first?U(e,E(t.line-1)):null:r>0&&t.ch==(n||M(e,t.line)).text.length?t.line=0;--i)Lo(e,{from:n[i].from,to:n[i].to,text:i?[""]:t.text});else Lo(e,t)}}function Lo(e,t){if(1!=t.text.length||""!=t.text[0]||0!=F(t.from,t.to)){var r=Ei(e,t);qi(e,t,r,e.cm?e.cm.curOp.id:0/0),Mo(e,t,r,J(e,t));var n=[];Ui(e,function(e,r){r||-1!=h(n,e.history)||(Do(e.history,t),n.push(e.history)),Mo(e,t,null,J(e,t))})}}function To(e,t,r){if(!e.cm||!e.cm.state.suppressEdits||r){for(var n,i=e.history,o=e.sel,l="undo"==t?i.done:i.undone,s="undo"==t?i.undone:i.done,a=0;a=0;--d){var p=f(d);if(p)return p.v}}}}function ko(e,t){if(0!=t&&(e.first+=t,e.sel=new sa(v(e.sel.ranges,function(e){return new aa(E(e.anchor.line+t,e.anchor.ch),E(e.head.line+t,e.head.ch))}),e.sel.primIndex),e.cm)){pi(e.cm,e.first,e.first-t,t);for(var r=e.cm.display,n=r.viewFrom;ne.lastLine())){if(t.from.lineo&&(t={from:t.from,to:E(o,M(e,o).text.length),text:[t.text[0]],origin:t.origin}),t.removed=N(e,t.from,t.to),r||(r=Ei(e,t)),e.cm?No(e.cm,t,n):Gi(e,t,n),po(e,r,ks)}}function No(e,t,r){var n=e.doc,i=e.display,o=t.from,l=t.to,s=!1,a=o.line;e.options.lineWrapping||(a=A(ft(M(n,o.line))),n.iter(a,l.line+1,function(e){return e==i.maxLine?(s=!0,!0):void 0})),n.sel.contains(t.from,t.to)>-1&&Dt(e),Gi(n,t,r,Cn(e)),e.options.lineWrapping||(n.iter(a,o.line+t.text.length,function(e){var t=bt(e);t>i.maxLineLength&&(i.maxLine=e,i.maxLineLength=t,i.maxLineChanged=!0,s=!1)}),s&&(e.curOp.updateMaxLine=!0)),n.frontier=Math.min(n.frontier,o.line),wi(e,400);var u=t.text.length-(l.line-o.line)-1;t.full?pi(e):o.line!=l.line||1!=t.text.length||Bi(e.doc,t)?pi(e,o.line,l.line+1,u):gi(e,o.line,"text");var c=Ht(e,"changes"),f=Ht(e,"change");if(f||c){var h={from:o,to:l,text:t.text,removed:t.removed,origin:t.origin};f&&Sr(e,"change",e,h),c&&(e.curOp.changeObjs||(e.curOp.changeObjs=[])).push(h)}e.display.selForContextMenu=null}function Oo(e,t,r,n,i){if(n||(n=r),F(n,r)<0){var o=n;n=r,r=o}"string"==typeof t&&(t=e.splitLines(t)),So(e,{from:r,to:n,text:t,origin:i})}function Wo(e,t,r,n){r0||0==s&&l.clearWhenEmpty!==!1)return l;if(l.replacedWith&&(l.collapsed=!0,l.widgetNode=i("span",[l.replacedWith],"CodeMirror-widget"),n.handleMouseEvents||l.widgetNode.setAttribute("cm-ignore-events","true"),n.insertLeft&&(l.widgetNode.insertLeft=!0)),l.collapsed){if(ct(e,t.line,t,r,l)||t.line!=r.line&&ct(e,r.line,t,r,l))throw new Error("Inserting collapsed marker partially overlapping an existing one");X()}l.addToHistory&&qi(e,{from:t,to:r,origin:"markText"},e.sel,0/0);var a,u=t.line,f=e.cm;if(e.iter(u,r.line+1,function(e){f&&l.collapsed&&!f.options.lineWrapping&&ft(e)==f.display.maxLine&&(a=!0),l.collapsed&&u!=t.line&&W(e,0),q(e,new Y(l,u==t.line?t.ch:null,u==r.line?r.ch:null)),++u}),l.collapsed&&e.iter(t.line,r.line+1,function(t){vt(e,t)&&W(t,0)}),l.clearOnEnter&&Is(l,"beforeCursorEnter",function(){return l.clear()}),l.readOnly&&(j(),(e.history.done.length||e.history.undone.length)&&e.clearHistory()),l.collapsed&&(l.id=++ha,l.atomic=!0),f){if(a&&(f.curOp.updateMaxLine=!0),l.collapsed)pi(f,t.line,r.line+1);else if(l.className||l.title||l.startStyle||l.endStyle||l.css)for(var h=t.line;h<=r.line;h++)gi(f,h,"text");l.atomic&&vo(f.doc),Sr(f,"markerAdded",f,l)}return l}function Io(e,t,r,n,i){n=c(n),n.shared=!1;var o=[Fo(e,t,r,n,i)],l=o[0],s=n.widgetNode;return Ui(e,function(e){s&&(n.widgetNode=s.cloneNode(!0)),o.push(Fo(e,U(e,t),U(e,r),n,i));for(var a=0;aa;++a)s(n[a],a);else{if(t.state.draggingText&&t.doc.sel.contains(r)>-1)return t.state.draggingText(e),void setTimeout(function(){return t.display.input.focus()},20);try{var u=e.dataTransfer.getData("Text");if(u){var c;if(t.state.draggingText&&!t.state.draggingText.copy&&(c=t.listSelections()),po(t.doc,Di(r,r)),c)for(var f=0;f=0;t--)Oo(e.doc,"",n[t].from,n[t].to,"+delete");ei(e)})}function rl(e,t){var r=M(e.doc,t),n=ft(r);return n!=r&&(t=A(n)),kt(!0,e,n,t,1)}function nl(e,t){var r=M(e.doc,t),n=ht(r);return n!=r&&(t=A(n)),kt(!0,e,r,t,-1)}function il(e,t){var r=rl(e,t.line),n=M(e.doc,r.line),i=St(n,e.doc.direction);if(!i||0==i[0].level){var o=Math.max(0,n.text.search(/\S/)),l=t.line==r.line&&t.ch<=o&&t.ch;return E(r.line,l?0:o,r.sticky)}return r}function ol(e,t,r){if("string"==typeof t&&(t=ka[t],!t))return!1;e.display.input.ensurePolled();var n=e.display.shift,i=!1;try{e.isReadOnly()&&(e.state.suppressEdits=!0),r&&(e.display.shift=!1),i=t(e)!=Ts}finally{e.display.shift=n,e.state.suppressEdits=!1}return i}function ll(e,t,r){for(var n=0;nts&&27==e.keyCode&&(e.returnValue=!1);var r=e.keyCode;t.display.shift=16==r||e.shiftKey;var n=al(t,e);os&&(Na=n?r:null,!n&&88==r&&!Gs&&(hs?e.metaKey:e.ctrlKey)&&t.replaceSelection("",null,"cut")),18!=r||/\bCodeMirror-crosshair\b/.test(t.display.lineDiv.className)||fl(t)}}function fl(e){function t(e){18!=e.keyCode&&e.altKey||(bs(r,"CodeMirror-crosshair"),Ot(document,"keyup",t),Ot(document,"mouseover",t))}var r=e.display.lineDiv;s(r,"CodeMirror-crosshair"),Is(document,"keyup",t),Is(document,"mouseover",t)}function hl(e){16==e.keyCode&&(this.doc.sel.shift=!1),At(this,e)}function dl(e){var t=this;if(!(zr(t.display,e)||At(t,e)||e.ctrlKey&&!e.altKey||hs&&e.metaKey)){var r=e.keyCode,n=e.charCode;if(os&&r==Na)return Na=null,void Et(e);if(!os||e.which&&!(e.which<10)||!al(t,e)){var i=String.fromCharCode(null==n?r:n);"\b"!=i&&(ul(t,e,i)||t.display.input.onKeyPress(e))}}}function pl(e){var t=this,r=t.display;if(!(At(t,e)||r.activeTouch&&r.input.supportsTouch())){if(r.input.ensurePolled(),r.shift=e.shiftKey,zr(r,e))return void(rs||(r.scroller.draggable=!1,setTimeout(function(){return r.scroller.draggable=!0},100)));if(!bl(t,e)){var n=Ln(t,e);switch(window.focus(),Bt(e)){case 1:t.state.selectingText?t.state.selectingText(e):n?gl(t,e,n):Rt(e)==r.scroller&&Et(e);break;case 2:rs&&(t.state.lastMiddleDown=+new Date),n&&lo(t.doc,n),setTimeout(function(){return r.input.focus()},20),Et(e);break;case 3:ys?wl(t,e):Dn(t)}}}}function gl(e,t,r){es?setTimeout(u(An,e),0):e.curOp.focus=l();var n,i=+new Date;Ta&&Ta.time>i-400&&0==F(Ta.pos,r)?n="triple":La&&La.time>i-400&&0==F(La.pos,r)?(n="double",Ta={time:i,pos:r}):(n="single",La={time:i,pos:r});var o,s=e.doc.sel,a=hs?t.metaKey:t.ctrlKey;e.options.dragDrop&&zs&&!e.isReadOnly()&&"single"==n&&(o=s.contains(r))>-1&&(F((o=s.ranges[o]).from(),r)<0||r.xRel>0)&&(F(o.to(),r)>0||r.xRel<0)?vl(e,t,r,a):ml(e,t,r,n,a)}function vl(e,t,r,n){var i=e.display,o=+new Date,l=fi(e,function(s){rs&&(i.scroller.draggable=!1),e.state.draggingText=!1,Ot(document,"mouseup",l),Ot(i.scroller,"drop",l),Math.abs(t.clientX-s.clientX)+Math.abs(t.clientY-s.clientY)<10&&(Et(s),!n&&+new Date-200=v;v++){var y=M(c,v).text,w=d(y,a,o);a==u?i.push(new aa(E(v,w),E(v,w))):y.length>w&&i.push(new aa(E(v,w),E(v,d(y,u,o))))}i.length||i.push(new aa(r,r)),ho(c,Ai(g.ranges.slice(0,p).concat(i),p),{origin:"*mouse",scroll:!1}),e.scrollIntoView(t)}else{var x=h,C=x.anchor,S=t;if("single"!=n){var L;L="double"==n?e.findWordAt(t):new aa(E(t.line,0),U(c,E(t.line+1,0))),F(L.anchor,C)>0?(S=L.head,C=B(x.from(),L.anchor)):(S=L.anchor,C=R(x.to(),L.head))}var T=g.ranges.slice(0);T[p]=new aa(U(c,C),S),ho(c,Ai(T,p),Ms)}}function s(t){var r=++x,i=Ln(e,t,!0,"rect"==n);if(i)if(0!=F(i,b)){e.curOp.focus=l(),o(i);var a=Rn(u,c);(i.line>=a.to||i.linew.bottom?20:0;f&&setTimeout(fi(e,function(){x==r&&(u.scroller.scrollTop+=f,s(t))}),50)}}function a(t){e.state.selectingText=!1,x=1/0,Et(t),u.input.focus(),Ot(document,"mousemove",C),Ot(document,"mouseup",S),c.history.lastSelOrigin=null}var u=e.display,c=e.doc;Et(t);var h,p,g=c.sel,v=g.ranges;if(i&&!t.shiftKey?(p=c.sel.contains(r),h=p>-1?v[p]:new aa(r,r)):(h=c.sel.primary(),p=c.sel.primIndex),ds?t.shiftKey&&t.metaKey:t.altKey)n="rect",i||(h=new aa(r,r)),r=Ln(e,t,!0,!0),p=-1;else if("double"==n){var m=e.findWordAt(r);h=e.display.shift||c.extend?oo(c,h,m.anchor,m.head):m}else if("triple"==n){var y=new aa(E(r.line,0),U(c,E(r.line+1,0)));h=e.display.shift||c.extend?oo(c,h,y.anchor,y.head):y}else h=oo(c,h,r);i?-1==p?(p=v.length,ho(c,Ai(v.concat([h]),p),{scroll:!1,origin:"*mouse"})):v.length>1&&v[p].empty()&&"single"==n&&!t.shiftKey?(ho(c,Ai(v.slice(0,p).concat(v.slice(p+1)),0),{scroll:!1,origin:"*mouse"}),g=c.sel):ao(c,p,h,Ms):(p=0,ho(c,new sa([h],0),Ms),g=c.sel);var b=r,w=u.wrapper.getBoundingClientRect(),x=0,C=fi(e,function(e){Bt(e)?s(e):a(e)}),S=fi(e,a);e.state.selectingText=S,Is(document,"mousemove",C),Is(document,"mouseup",S)}function yl(e,t,r,n){var i,o;try{i=t.clientX,o=t.clientY}catch(t){return!1}if(i>=Math.floor(e.display.gutters.getBoundingClientRect().right))return!1;n&&Et(t);var l=e.display,s=l.lineDiv.getBoundingClientRect();if(o>s.bottom||!Ht(e,r))return It(t);o-=s.top-l.viewOffset;for(var a=0;a=i){var c=D(e.doc,o),f=e.options.gutters[a];return Wt(e,r,e,c,f,t),It(t)}}}function bl(e,t){return yl(e,t,"gutterClick",!0)}function wl(e,t){zr(e.display,t)||xl(e,t)||At(e,t,"contextmenu")||e.display.input.onContextMenu(t)}function xl(e,t){return Ht(e,"gutterContextMenu")?yl(e,t,"gutterContextMenu",!1):!1}function Cl(e){e.display.wrapper.className=e.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+e.options.theme.replace(/(^|\s)\s*/g," cm-s-"),on(e)}function Sl(e){function t(t,n,i,o){e.defaults[t]=n,i&&(r[t]=o?function(e,t,r){r!=Oa&&i(e,t,r)}:i)}var r=e.optionHandlers;e.defineOption=t,e.Init=Oa,t("value","",function(e,t){return e.setValue(t)},!0),t("mode",null,function(e,t){e.doc.modeOption=t,zi(e)},!0),t("indentUnit",2,zi,!0),t("indentWithTabs",!1),t("smartIndent",!0),t("tabSize",4,function(e){Ri(e),on(e),pi(e)},!0),t("lineSeparator",null,function(e,t){if(e.doc.lineSep=t,t){var r=[],n=e.doc.first;e.doc.iter(function(e){for(var i=0;;){var o=e.text.indexOf(t,i);if(-1==o)break;i=o+t.length,r.push(E(n,o))}n++});for(var i=r.length-1;i>=0;i--)Oo(e.doc,t,r[i],E(r[i].line,r[i].ch+t.length))}}),t("specialChars",/[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g,function(e,t,r){e.state.specialChars=new RegExp(t.source+(t.test(" ")?"":"| "),"g"),r!=Oa&&e.refresh()}),t("specialCharPlaceholder",hr,function(e){return e.refresh()},!0),t("electricChars",!0),t("inputStyle",fs?"contenteditable":"textarea",function(){throw new Error("inputStyle can not (yet) be changed in a running editor")},!0),t("spellcheck",!1,function(e,t){return e.getInputField().spellcheck=t},!0),t("rtlMoveVisually",!ps),t("wholeLineUpdateBefore",!0),t("theme","default",function(e){Cl(e),Ll(e)},!0),t("keyMap","default",function(e,t,r){var n=el(t),i=r!=Oa&&el(r);i&&i.detach&&i.detach(e,n),n.attach&&n.attach(e,i||null)}),t("extraKeys",null),t("lineWrapping",!1,kl,!0),t("gutters",[],function(e){Wi(e.options),Ll(e)},!0),t("fixedGutter",!0,function(e,t){e.display.gutters.style.left=t?xn(e.display)+"px":"0",e.refresh()},!0),t("coverGutterNextToScrollbar",!1,function(e){return Xn(e)},!0),t("scrollbarStyle","native",function(e){_n(e),Xn(e),e.display.scrollbars.setScrollTop(e.doc.scrollTop),e.display.scrollbars.setScrollLeft(e.doc.scrollLeft)},!0),t("lineNumbers",!1,function(e){Wi(e.options),Ll(e)},!0),t("firstLineNumber",1,Ll,!0),t("lineNumberFormatter",function(e){return e},Ll,!0),t("showCursorWhenSelecting",!1,kn,!0),t("resetSelectionOnContextMenu",!0),t("lineWiseCopyCut",!0),t("readOnly",!1,function(e,t){"nocursor"==t?(Pn(e),e.display.input.blur(),e.display.disabled=!0):e.display.disabled=!1,e.display.input.readOnlyChanged(t)}),t("disableInput",!1,function(e,t){t||e.display.input.reset()},!0),t("dragDrop",!0,Tl),t("allowDropFileTypes",null),t("cursorBlinkRate",530),t("cursorScrollMargin",0),t("cursorHeight",1,kn,!0),t("singleCursorHeightPerLine",!0,kn,!0),t("workTime",100),t("workDelay",100),t("flattenSpans",!0,Ri,!0),t("addModeClass",!1,Ri,!0),t("pollInterval",100),t("undoDepth",200,function(e,t){return e.doc.history.undoDepth=t}),t("historyEventDelay",1250),t("viewportMargin",10,function(e){return e.refresh()},!0),t("maxHighlightLength",1e4,Ri,!0),t("moveInputWithCursor",!0,function(e,t){t||e.display.input.resetPosition()}),t("tabindex",null,function(e,t){return e.display.input.getField().tabIndex=t||""}),t("autofocus",null),t("direction","ltr",function(e,t){return e.doc.setDirection(t)},!0)}function Ll(e){Oi(e),pi(e),En(e)}function Tl(e,t,r){var n=r&&r!=Oa;if(!t!=!n){var i=e.display.dragFunctions,o=t?Is:Ot;o(e.display.scroller,"dragstart",i.start),o(e.display.scroller,"dragenter",i.enter),o(e.display.scroller,"dragover",i.over),o(e.display.scroller,"dragleave",i.leave),o(e.display.scroller,"drop",i.drop)}}function kl(e){e.options.lineWrapping?(s(e.display.wrapper,"CodeMirror-wrap"),e.display.sizer.style.minWidth="",e.display.sizerWidth=null):(bs(e.display.wrapper,"CodeMirror-wrap"),wt(e)),Sn(e),pi(e),on(e),setTimeout(function(){return Xn(e)},100)}function Ml(e,t){var r=this;if(!(this instanceof Ml))return new Ml(e,t);this.options=t=t?c(t):{},c(Wa,t,!1),Wi(t);var n=t.value;"string"==typeof n&&(n=new va(n,t.mode,null,t.lineSeparator,t.direction)),this.doc=n;var i=new Ml.inputStyles[t.inputStyle](this),o=this.display=new k(e,n,i);o.wrapper.CodeMirror=this,Oi(this),Cl(this),t.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap"),_n(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 xs,keySeq:null,specialChars:null},t.autofocus&&!fs&&o.input.focus(),es&&11>ts&&setTimeout(function(){return r.display.input.reset(!0)},20),Nl(this),Xo(),ri(this),this.curOp.forceUpdate=!0,Vi(this,n),t.autofocus&&!fs||this.hasFocus()?setTimeout(u(Hn,this),20):Pn(this);for(var l in Aa)Aa.hasOwnProperty(l)&&Aa[l](r,t[l],Oa);Fn(this),t.finishInit&&t.finishInit(this);for(var s=0;s400}var i=e.display;Is(i.scroller,"mousedown",fi(e,pl)),es&&11>ts?Is(i.scroller,"dblclick",fi(e,function(t){if(!At(e,t)){var r=Ln(e,t);if(r&&!bl(e,t)&&!zr(e.display,t)){Et(t);var n=e.findWordAt(r);lo(e.doc,n.anchor,n.head)}}})):Is(i.scroller,"dblclick",function(t){return At(e,t)||Et(t)}),ys||Is(i.scroller,"contextmenu",function(t){return wl(e,t)});var o,l={end:0};Is(i.scroller,"touchstart",function(t){if(!At(e,t)&&!r(t)){i.input.ensurePolled(),clearTimeout(o);var n=+new Date;i.activeTouch={start:n,moved:!1,prev:n-l.end<=300?l:null},1==t.touches.length&&(i.activeTouch.left=t.touches[0].pageX,i.activeTouch.top=t.touches[0].pageY)}}),Is(i.scroller,"touchmove",function(){i.activeTouch&&(i.activeTouch.moved=!0)}),Is(i.scroller,"touchend",function(r){var o=i.activeTouch;if(o&&!zr(i,r)&&null!=o.left&&!o.moved&&new Date-o.start<300){var l,s=e.coordsChar(i.activeTouch,"page");l=!o.prev||n(o,o.prev)?new aa(s,s):!o.prev.prev||n(o,o.prev.prev)?e.findWordAt(s):new aa(E(s.line,0),U(e.doc,E(s.line+1,0))),e.setSelection(l.anchor,l.head),e.focus(),Et(r)}t()}),Is(i.scroller,"touchcancel",t),Is(i.scroller,"scroll",function(){i.scroller.clientHeight&&(Bn(e,i.scroller.scrollTop),Gn(e,i.scroller.scrollLeft,!0),Wt(e,"scroll",e))}),Is(i.scroller,"mousewheel",function(t){return Kn(e,t)}),Is(i.scroller,"DOMMouseScroll",function(t){return Kn(e,t)}),Is(i.wrapper,"scroll",function(){return i.wrapper.scrollTop=i.wrapper.scrollLeft=0}),i.dragFunctions={enter:function(t){At(e,t)||zt(t)},over:function(t){At(e,t)||(Vo(e,t),zt(t))},start:function(t){return Uo(e,t)},drop:fi(e,Go),leave:function(t){At(e,t)||Ko(e)}};var s=i.input.getField();Is(s,"keyup",function(t){return hl.call(e,t)}),Is(s,"keydown",fi(e,cl)),Is(s,"keypress",fi(e,dl)),Is(s,"focus",function(t){return Hn(e,t)}),Is(s,"blur",function(t){return Pn(e,t)})}function Ol(e,t,r,n){var i,o=e.doc;null==r&&(r="add"),"smart"==r&&(o.mode.indent?i=er(e,t):r="prev");var l=e.options.tabSize,s=M(o,t),a=f(s.text,null,l);s.stateAfter&&(s.stateAfter=null);var u,c=s.text.match(/^\s*/)[0];if(n||/\S/.test(s.text)){if("smart"==r&&(u=o.mode.indent(i,s.text.slice(c.length),s.text),u==Ts||u>150)){if(!n)return;r="prev"}}else u=0,r="not";"prev"==r?u=t>o.first?f(M(o,t-1).text,null,l):0:"add"==r?u=a+e.options.indentUnit:"subtract"==r?u=a-e.options.indentUnit:"number"==typeof r&&(u=a+r),u=Math.max(0,u);var h="",d=0;if(e.options.indentWithTabs)for(var g=Math.floor(u/l);g;--g)d+=l,h+=" "; -if(u>d&&(h+=p(u-d)),h!=c)return Oo(o,h,E(t,0),E(t,c.length),"+input"),s.stateAfter=null,!0;for(var v=0;v1)if(Ha&&Ha.text.join("\n")==t){if(n.ranges.length%Ha.text.length==0){a=[];for(var u=0;u=0;f--){var h=n.ranges[f],d=h.from(),p=h.to();h.empty()&&(r&&r>0?d=E(d.line,d.ch-r):e.state.overwrite&&!l?p=E(p.line,Math.min(M(o,p.line).text.length,p.ch+g(s).length)):Ha&&Ha.lineWise&&Ha.text.join("\n")==t&&(d=p=E(d.line,0))),c=e.curOp.updateInput;var m={from:d,to:p,text:a?a[f%a.length]:s,origin:i||(l?"paste":e.state.cutIncoming?"cut":"+input")};So(e.doc,m),Sr(e,"inputRead",e,m)}t&&!l&&Hl(e,t),ei(e),e.curOp.updateInput=c,e.curOp.typing=!0,e.state.pasteIncoming=e.state.cutIncoming=!1}function Dl(e,t){var r=e.clipboardData&&e.clipboardData.getData("Text");return r?(e.preventDefault(),t.isReadOnly()||t.options.disableInput||ci(t,function(){return Al(t,r,0,null,"paste")}),!0):void 0}function Hl(e,t){if(e.options.electricChars&&e.options.smartIndent)for(var r=e.doc.sel,n=r.ranges.length-1;n>=0;n--){var i=r.ranges[n];if(!(i.head.ch>100||n&&r.ranges[n-1].head.line==i.head.line)){var o=e.getModeAt(i.head),l=!1;if(o.electricChars){for(var s=0;s-1){l=Ol(e,i.head.line,"smart");break}}else o.electricInput&&o.electricInput.test(M(e.doc,i.head.line).text.slice(0,i.head.ch))&&(l=Ol(e,i.head.line,"smart"));l&&Sr(e,"electricInput",e,i.head.line)}}}function Pl(e){for(var t=[],r=[],n=0;nn&&(Ol(t,o.head.line,e,!0),n=o.head.line,i==t.doc.sel.primIndex&&ei(t));else{var l=o.from(),s=o.to(),a=Math.max(n,l.line);n=Math.min(t.lastLine(),s.line-(s.ch?0:1))+1;for(var u=a;n>u;++u)Ol(t,u,e);var c=t.doc.sel.ranges;0==l.ch&&r.length==c.length&&c[i].from().ch>0&&ao(t.doc,i,new aa(l,c[i].to()),ks)}}}),getTokenAt:function(e,t){return ir(this,e,t)},getLineTokens:function(e,t){return ir(this,E(e),t,!0)},getTokenTypeAt:function(e){e=U(this.doc,e);var t,r=Jt(this,M(this.doc,e.line)),n=0,i=(r.length-1)/2,o=e.ch;if(0==o)t=r[2];else for(;;){var l=n+i>>1;if((l?r[2*l-1]:0)>=o)i=l;else{if(!(r[2*l+1]s?t:0==s?null:t.slice(0,s-1)},getModeAt:function(t){var r=this.doc.mode;return r.innerMode?e.innerMode(r,this.getTokenAt(t).state).mode:r},getHelper:function(e,t){return this.getHelpers(e,t)[0]},getHelpers:function(e,t){var n=this,i=[];if(!r.hasOwnProperty(t))return i;var o=r[t],l=this.getModeAt(e);if("string"==typeof l[t])o[l[t]]&&i.push(o[l[t]]);else if(l[t])for(var s=0;so&&(e=o,i=!0),n=M(this.doc,e)}else n=e;return an(this,n,{top:0,left:0},t||"page",r||i).top+(i?this.doc.height-yt(n):0)},defaultTextHeight:function(){return yn(this.display)},defaultCharWidth:function(){return bn(this.display)},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(e,t,r,n,i){var o=this.display;e=fn(this,U(this.doc,e));var l=e.bottom,s=e.left;if(t.style.position="absolute",t.setAttribute("cm-ignore-events","true"),this.display.input.setUneditable(t),o.sizer.appendChild(t),"over"==n)l=e.top;else if("above"==n||"near"==n){var a=Math.max(o.wrapper.clientHeight,this.doc.height),u=Math.max(o.sizer.clientWidth,o.lineSpace.clientWidth);("above"==n||e.bottom+t.offsetHeight>a)&&e.top>t.offsetHeight?l=e.top-t.offsetHeight:e.bottom+t.offsetHeight<=a&&(l=e.bottom),s+t.offsetWidth>u&&(s=u-t.offsetWidth)}t.style.top=l+"px",t.style.left=t.style.right="","right"==i?(s=o.sizer.clientWidth-t.offsetWidth,t.style.right="0px"):("left"==i?s=0:"middle"==i&&(s=(o.sizer.clientWidth-t.offsetWidth)/2),t.style.left=s+"px"),r&&Zn(this,{left:s,top:l,right:s+t.offsetWidth,bottom:l+t.offsetHeight})},triggerOnKeyDown:hi(cl),triggerOnKeyPress:hi(dl),triggerOnKeyUp:hl,execCommand:function(e){return ka.hasOwnProperty(e)?ka[e].call(null,this):void 0},triggerElectric:hi(function(e){Hl(this,e)}),findPosH:function(e,t,r,n){var i=this,o=1;0>t&&(o=-1,t=-t);for(var l=U(this.doc,e),s=0;t>s&&(l=zl(i.doc,l,o,r,n),!l.hitSide);++s);return l},moveH:hi(function(e,t){var r=this;this.extendSelectionsBy(function(n){return r.display.shift||r.doc.extend||n.empty()?zl(r.doc,n.head,e,t,r.options.rtlMoveVisually):0>e?n.from():n.to()},Ns)}),deleteH:hi(function(e,t){var r=this.doc.sel,n=this.doc;r.somethingSelected()?n.replaceSelection("",null,"+delete"):tl(this,function(r){var i=zl(n,r.head,e,t,!1);return 0>e?{from:i,to:r.head}:{from:r.head,to:i}})}),findPosV:function(e,t,r,n){var i=this,o=1,l=n;0>t&&(o=-1,t=-t);for(var s=U(this.doc,e),a=0;t>a;++a){var u=fn(i,s,"div");if(null==l?l=u.left:u.left=l,s=Rl(i,u,o,r),s.hitSide)break}return s},moveV:hi(function(e,t){var r=this,n=this.doc,i=[],o=!this.display.shift&&!n.extend&&n.sel.somethingSelected();if(n.extendSelectionsBy(function(l){if(o)return 0>e?l.from():l.to();var s=fn(r,l.head,"div");null!=l.goalColumn&&(s.left=l.goalColumn),i.push(s.left);var a=Rl(r,s,e,t);return"page"==t&&l==n.sel.primary()&&Jn(r,null,cn(r,a,"div").top-s.top),a},Ns),i.length)for(var l=0;l0&&s(r.charAt(n-1));)--n;for(;i.5)&&Sn(this),Wt(this,"refresh",this)}),swapDoc:hi(function(e){var t=this.doc;return t.cm=null,Vi(this,e),on(this),this.display.input.reset(),this.scrollTo(e.scrollLeft,e.scrollTop),this.curOp.forceScroll=!0,Sr(this,"swapDoc",this,t),t}),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}},Pt(e),e.registerHelper=function(t,n,i){r.hasOwnProperty(t)||(r[t]=e[t]={_global:[]}),r[t][n]=i},e.registerGlobalHelper=function(t,n,i,o){e.registerHelper(t,n,o),r[t]._global.push({pred:i,val:o})}}function zl(e,t,r,n,i){function o(){var n=t.line+r;return n=e.first+e.size?!1:(t=new E(n,t.ch,t.sticky),u=M(e,n))}function l(n){var l;if(l=i?Mt(e.cm,u,t,r):Tt(u,t,r),null==l){if(n||!o())return!1;t=kt(i,e.cm,u,t.line,r)}else t=l;return!0}var s=t,a=r,u=M(e,t.line);if("char"==n)l();else if("column"==n)l(!0);else if("word"==n||"group"==n)for(var c=null,f="group"==n,h=e.cm&&e.cm.getHelper(t,"wordChars"),d=!0;!(0>r)||l(!d);d=!1){var p=u.text.charAt(t.ch)||"\n",g=x(p,h)?"w":f&&"\n"==p?"n":!f||/\s/.test(p)?null:"p";if(!f||d||g||(g="s"),c&&c!=g){0>r&&(r=1,l(),t.sticky="after");break}if(g&&(c=g),r>0&&!l(!d))break}var v=bo(e,t,s,a,!0);return I(s,v)&&(v.hitSide=!0),v}function Rl(e,t,r,n){var i,o=e.doc,l=t.left;if("page"==n){var s=Math.min(e.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight),a=Math.max(s-.5*yn(e.display),3);i=(r>0?t.bottom:t.top)+r*a}else"line"==n&&(i=r>0?t.bottom+3:t.top-3);for(var u;u=pn(e,l,i),u.outside;){if(0>r?0>=i:i>=o.height){u.hitSide=!0;break}i+=5*r}return u}function Bl(e,t){var r=$r(e,t.line);if(!r||r.hidden)return null;var n=M(e.doc,t.line),i=Xr(r,n,t.line),o=St(n,e.doc.direction),l="left";if(o){var s=Ct(o,t.ch);l=s%2?"right":"left"}var a=Qr(i.map,t.ch,l);return a.offset="right"==a.collapse?a.end:a.start,a}function Gl(e){for(var t=e;t;t=t.parentNode)if(/CodeMirror-gutter-wrapper/.test(t.className))return!0;return!1}function Ul(e,t){return t&&(e.bad=!0),e}function Vl(e,t,r,n,i){function o(e){return function(t){return t.id==e}}function l(){c&&(u+=f,c=!1)}function s(e){e&&(l(),u+=e)}function a(t){if(1==t.nodeType){var r=t.getAttribute("cm-text");if(null!=r)return void s(r||t.textContent.replace(/\u200b/g,""));var u,h=t.getAttribute("cm-marker");if(h){var d=e.findMarks(E(n,0),E(i+1,0),o(+h));return void(d.length&&(u=d[0].find())&&s(N(e.doc,u.from,u.to).join(f)))}if("false"==t.getAttribute("contenteditable"))return;var p=/^(pre|div|p)$/i.test(t.nodeName);p&&l();for(var g=0;gi?c.map:f[i],l=0;li?e.line:e.rest[i]),u=o[l]+n;return(0>n||s!=t)&&(u=o[l+(n?1:0)]),E(a,u)}}}var i=e.text.firstChild,l=!1;if(!t||!o(i,t))return Ul(E(A(e.line),0),!0);if(t==i&&(l=!0,t=i.childNodes[r],r=0,!t)){var s=e.rest?g(e.rest):e.line;return Ul(E(A(s),s.text.length),l)}var a=3==t.nodeType?t:null,u=t;for(a||1!=t.childNodes.length||3!=t.firstChild.nodeType||(a=t.firstChild,r&&(r=a.nodeValue.length));u.parentNode!=i;)u=u.parentNode;var c=e.measure,f=c.maps,h=n(a,u,r);if(h)return Ul(h,l);for(var d=u.nextSibling,p=a?a.nodeValue.length-r:0;d;d=d.nextSibling){if(h=n(d,d.firstChild,0))return Ul(E(h.line,h.ch-p),l);p+=d.textContent.length}for(var v=u.previousSibling,m=r;v;v=v.previousSibling){if(h=n(v,v.firstChild,-1))return Ul(E(h.line,h.ch+m),l);m+=v.textContent.length}}function Xl(e,t){function r(){e.value=u.getValue()}if(t=t?c(t):{},t.value=e.value,!t.tabindex&&e.tabIndex&&(t.tabindex=e.tabIndex),!t.placeholder&&e.placeholder&&(t.placeholder=e.placeholder),null==t.autofocus){var n=l();t.autofocus=n==e||null!=e.getAttribute("autofocus")&&n==document.body}var i;if(e.form&&(Is(e.form,"submit",r),!t.leaveSubmitMethodAlone)){var o=e.form;i=o.submit;try{var s=o.submit=function(){r(),o.submit=i,o.submit(),o.submit=s}}catch(a){}}t.finishInit=function(t){t.save=r,t.getTextArea=function(){return e},t.toTextArea=function(){t.toTextArea=isNaN,r(),e.parentNode.removeChild(t.getWrapperElement()),e.style.display="",e.form&&(Ot(e.form,"submit",r),"function"==typeof e.form.submit&&(e.form.submit=i))}},e.style.display="none";var u=Ml(function(t){return e.parentNode.insertBefore(t,e.nextSibling)},t);return u}function Yl(e){e.off=Ot,e.on=Is,e.wheelEventPixels=Vn,e.Doc=va,e.splitLines=Rs,e.countColumn=f,e.findColumn=d,e.isWordChar=w,e.Pass=Ts,e.signal=Wt,e.Line=Ys,e.changeEnd=Hi,e.scrollbarModel=ia,e.Pos=E,e.cmpPos=F,e.modes=Vs,e.mimeModes=Ks,e.resolveMode=Xt,e.getMode=Yt,e.modeExtensions=js,e.extendMode=_t,e.copyState=$t,e.startState=Zt,e.innerMode=qt,e.commands=ka,e.keyMap=Sa,e.keyName=Jo,e.isModifierKey=Qo,e.lookupKey=Zo,e.normalizeKeyMap=qo,e.StringStream=Xs,e.SharedTextMarker=pa,e.TextMarker=da,e.LineWidget=fa,e.e_preventDefault=Et,e.e_stopPropagation=Ft,e.e_stop=zt,e.addClass=s,e.contains=o,e.rmClass=bs,e.keyNames=ba}var _l=navigator.userAgent,$l=navigator.platform,ql=/gecko\/\d/i.test(_l),Zl=/MSIE \d/.test(_l),Ql=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(_l),Jl=/Edge\/(\d+)/.exec(_l),es=Zl||Ql||Jl,ts=es&&(Zl?document.documentMode||6:+(Jl||Ql)[1]),rs=!Jl&&/WebKit\//.test(_l),ns=rs&&/Qt\/\d+\.\d+/.test(_l),is=!Jl&&/Chrome\//.test(_l),os=/Opera\//.test(_l),ls=/Apple Computer/.test(navigator.vendor),ss=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(_l),as=/PhantomJS/.test(_l),us=!Jl&&/AppleWebKit/.test(_l)&&/Mobile\/\w+/.test(_l),cs=/Android/.test(_l),fs=us||cs||/webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(_l),hs=us||/Mac/.test($l),ds=/\bCrOS\b/.test(_l),ps=/win/i.test($l),gs=os&&_l.match(/Version\/(\d*\.\d*)/);gs&&(gs=Number(gs[1])),gs&&gs>=15&&(os=!1,rs=!0);var vs,ms=hs&&(ns||os&&(null==gs||12.11>gs)),ys=ql||es&&ts>=9,bs=function(t,r){var n=t.className,i=e(r).exec(n);if(i){var o=n.slice(i.index+i[0].length);t.className=n.slice(0,i.index)+(o?i[1]+o:"")}};vs=document.createRange?function(e,t,r,n){var i=document.createRange();return i.setEnd(n||e,r),i.setStart(e,t),i}:function(e,t,r){var n=document.body.createTextRange();try{n.moveToElementText(e.parentNode)}catch(i){return n}return n.collapse(!0),n.moveEnd("character",r),n.moveStart("character",t),n};var ws=function(e){e.select()};us?ws=function(e){e.selectionStart=0,e.selectionEnd=e.value.length}:es&&(ws=function(e){try{e.select()}catch(t){}});var xs=function(){this.id=null};xs.prototype.set=function(e,t){clearTimeout(this.id),this.id=setTimeout(t,e)};var Cs,Ss,Ls=30,Ts={toString:function(){return"CodeMirror.Pass"}},ks={scroll:!1},Ms={origin:"*mouse"},Ns={origin:"+move"},Os=[""],Ws=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,As=/[\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]/,Ds=!1,Hs=!1,Ps=null,Es=function(){function e(e){return 247>=e?r.charAt(e):e>=1424&&1524>=e?"R":e>=1536&&1785>=e?n.charAt(e-1536):e>=1774&&2220>=e?"r":e>=8192&&8203>=e?"w":8204==e?"b":"L"}function t(e,t,r){this.level=e,this.from=t,this.to=r}var r="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",n="nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111",i=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,o=/[stwN]/,l=/[LRr]/,s=/[Lb1n]/,a=/[1n]/;return function(r,n){var u="ltr"==n?"L":"R";if(0==r.length||"ltr"==n&&!i.test(r))return!1;for(var c=r.length,f=[],h=0;c>h;++h)f.push(e(r.charCodeAt(h)));for(var d=0,p=u;c>d;++d){var v=f[d];"m"==v?f[d]=p:p=v}for(var m=0,y=u;c>m;++m){var b=f[m];"1"==b&&"r"==y?f[m]="n":l.test(b)&&(y=b,"r"==b&&(f[m]="R"))}for(var w=1,x=f[0];c-1>w;++w){var C=f[w];"+"==C&&"1"==x&&"1"==f[w+1]?f[w]="1":","!=C||x!=f[w+1]||"1"!=x&&"n"!=x||(f[w]=x),x=C}for(var S=0;c>S;++S){var L=f[S];if(","==L)f[S]="N";else if("%"==L){var T=void 0;for(T=S+1;c>T&&"%"==f[T];++T);for(var k=S&&"!"==f[S-1]||c>T&&"1"==f[T]?"1":"N",M=S;T>M;++M)f[M]=k;S=T-1}}for(var N=0,O=u;c>N;++N){var W=f[N];"L"==O&&"1"==W?f[N]="L":l.test(W)&&(O=W)}for(var A=0;c>A;++A)if(o.test(f[A])){var D=void 0;for(D=A+1;c>D&&o.test(f[D]);++D);for(var H="L"==(A?f[A-1]:u),P="L"==(c>D?f[D]:u),E=H==P?H?"L":"R":u,F=A;D>F;++F)f[F]=E;A=D-1}for(var I,z=[],R=0;c>R;)if(s.test(f[R])){var B=R;for(++R;c>R&&s.test(f[R]);++R);z.push(new t(0,B,R))}else{var G=R,U=z.length;for(++R;c>R&&"L"!=f[R];++R);for(var V=G;R>V;)if(a.test(f[V])){V>G&&z.splice(U,0,new t(1,G,V));var K=V;for(++V;R>V&&a.test(f[V]);++V);z.splice(U,0,new t(2,K,V)),G=V}else++V;R>G&&z.splice(U,0,new t(1,G,R))}return 1==z[0].level&&(I=r.match(/^\s+/))&&(z[0].from=I[0].length,z.unshift(new t(0,0,I[0].length))),1==g(z).level&&(I=r.match(/\s+$/))&&(g(z).to-=I[0].length,z.push(new t(0,c-I[0].length,c))),"rtl"==n?z.reverse():z}}(),Fs=[],Is=function(e,t,r){if(e.addEventListener)e.addEventListener(t,r,!1);else if(e.attachEvent)e.attachEvent("on"+t,r);else{var n=e._handlers||(e._handlers={});n[t]=(n[t]||Fs).concat(r)}},zs=function(){if(es&&9>ts)return!1;var e=n("div");return"draggable"in e||"dragDrop"in e}(),Rs=3!="\n\nb".split(/\n/).length?function(e){for(var t=0,r=[],n=e.length;n>=t;){var i=e.indexOf("\n",t);-1==i&&(i=e.length);var o=e.slice(t,"\r"==e.charAt(i-1)?i-1:i),l=o.indexOf("\r");-1!=l?(r.push(o.slice(0,l)),t+=l+1):(r.push(o),t=i+1)}return r}:function(e){return e.split(/\r\n?|\n/)},Bs=window.getSelection?function(e){try{return e.selectionStart!=e.selectionEnd}catch(t){return!1}}:function(e){var t;try{t=e.ownerDocument.selection.createRange()}catch(r){}return t&&t.parentElement()==e?0!=t.compareEndPoints("StartToEnd",t):!1},Gs=function(){var e=n("div");return"oncopy"in e?!0:(e.setAttribute("oncopy","return;"),"function"==typeof e.oncopy)}(),Us=null,Vs={},Ks={},js={},Xs=function(e,t){this.pos=this.start=0,this.string=e,this.tabSize=t||8,this.lastColumnPos=this.lastColumnValue=0,this.lineStart=0};Xs.prototype.eol=function(){return this.pos>=this.string.length},Xs.prototype.sol=function(){return this.pos==this.lineStart},Xs.prototype.peek=function(){return this.string.charAt(this.pos)||void 0},Xs.prototype.next=function(){return this.post},Xs.prototype.eatSpace=function(){for(var e=this,t=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++e.pos;return this.pos>t},Xs.prototype.skipToEnd=function(){this.pos=this.string.length},Xs.prototype.skipTo=function(e){var t=this.string.indexOf(e,this.pos);return t>-1?(this.pos=t,!0):void 0},Xs.prototype.backUp=function(e){this.pos-=e},Xs.prototype.column=function(){return this.lastColumnPos0?null:(n&&t!==!1&&(this.pos+=n[0].length),n)}var i=function(e){return r?e.toLowerCase():e},o=this.string.substr(this.pos,e.length);return i(o)==i(e)?(t!==!1&&(this.pos+=e.length),!0):void 0},Xs.prototype.current=function(){return this.string.slice(this.start,this.pos)},Xs.prototype.hideFirstChars=function(e,t){this.lineStart+=e;try{return t()}finally{this.lineStart-=e}};var Ys=function(e,t,r){this.text=e,nt(this,t),this.height=r?r(this):1};Ys.prototype.lineNo=function(){return A(this)},Pt(Ys);var _s,$s={},qs={},Zs=null,Qs=null,Js={left:0,right:0,top:0,bottom:0},ea=0,ta=null;es?ta=-.53:ql?ta=15:is?ta=-.7:ls&&(ta=-1/3);var ra=function(e,t,r){this.cm=r;var i=this.vert=n("div",[n("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),o=this.horiz=n("div",[n("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");e(i),e(o),Is(i,"scroll",function(){i.clientHeight&&t(i.scrollTop,"vertical")}),Is(o,"scroll",function(){o.clientWidth&&t(o.scrollLeft,"horizontal")}),this.checkedZeroWidth=!1,es&&8>ts&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px")};ra.prototype.update=function(e){var t=e.scrollWidth>e.clientWidth+1,r=e.scrollHeight>e.clientHeight+1,n=e.nativeBarWidth;if(r){this.vert.style.display="block",this.vert.style.bottom=t?n+"px":"0";var i=e.viewHeight-(t?n:0);this.vert.firstChild.style.height=Math.max(0,e.scrollHeight-e.clientHeight+i)+"px"}else this.vert.style.display="",this.vert.firstChild.style.height="0";if(t){this.horiz.style.display="block",this.horiz.style.right=r?n+"px":"0",this.horiz.style.left=e.barLeft+"px";var o=e.viewWidth-e.barLeft-(r?n:0);this.horiz.firstChild.style.width=Math.max(0,e.scrollWidth-e.clientWidth+o)+"px"}else this.horiz.style.display="",this.horiz.firstChild.style.width="0";return!this.checkedZeroWidth&&e.clientHeight>0&&(0==n&&this.zeroWidthHack(),this.checkedZeroWidth=!0),{right:r?n:0,bottom:t?n:0}},ra.prototype.setScrollLeft=function(e){this.horiz.scrollLeft!=e&&(this.horiz.scrollLeft=e),this.disableHoriz&&this.enableZeroWidthBar(this.horiz,this.disableHoriz)},ra.prototype.setScrollTop=function(e){this.vert.scrollTop!=e&&(this.vert.scrollTop=e),this.disableVert&&this.enableZeroWidthBar(this.vert,this.disableVert)},ra.prototype.zeroWidthHack=function(){var e=hs&&!ss?"12px":"18px";this.horiz.style.height=this.vert.style.width=e,this.horiz.style.pointerEvents=this.vert.style.pointerEvents="none",this.disableHoriz=new xs,this.disableVert=new xs},ra.prototype.enableZeroWidthBar=function(e,t){function r(){var n=e.getBoundingClientRect(),i=document.elementFromPoint(n.left+1,n.bottom-1);i!=e?e.style.pointerEvents="none":t.set(1e3,r)}e.style.pointerEvents="auto",t.set(1e3,r)},ra.prototype.clear=function(){var e=this.horiz.parentNode;e.removeChild(this.horiz),e.removeChild(this.vert)};var na=function(){};na.prototype.update=function(){return{bottom:0,right:0}},na.prototype.setScrollLeft=function(){},na.prototype.setScrollTop=function(){},na.prototype.clear=function(){};var ia={"native":ra,"null":na},oa=0,la=function(e,t,r){var n=e.display;this.viewport=t,this.visible=Rn(n,e.doc,t),this.editorIsHidden=!n.wrapper.offsetWidth,this.wrapperHeight=n.wrapper.clientHeight,this.wrapperWidth=n.wrapper.clientWidth,this.oldDisplayWidth=Vr(e),this.force=r,this.dims=wn(e),this.events=[]};la.prototype.signal=function(e,t){Ht(e,t)&&this.events.push(arguments)},la.prototype.finish=function(){for(var e=this,t=0;t=0&&F(e,i.to())<=0)return n}return-1};var aa=function(e,t){this.anchor=e,this.head=t};aa.prototype.from=function(){return B(this.anchor,this.head)},aa.prototype.to=function(){return R(this.anchor,this.head)},aa.prototype.empty=function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch};var ua=function(e){var t=this;this.lines=e,this.parent=null;for(var r=0,n=0;nn;++n){var o=r.lines[n];r.height-=o.height,ur(o),Sr(o,"delete")}this.lines.splice(e,t)},ua.prototype.collapse=function(e){e.push.apply(e,this.lines)},ua.prototype.insertInner=function(e,t,r){var n=this;this.height+=r,this.lines=this.lines.slice(0,e).concat(t).concat(this.lines.slice(e));for(var i=0;ie;++e)if(r(n.lines[e]))return!0};var ca=function(e){var t=this;this.children=e;for(var r=0,n=0,i=0;ie){var l=Math.min(t,o-e),s=i.height;if(i.removeInner(e,l),r.height-=s-i.height,o==l&&(r.children.splice(n--,1),i.parent=null),0==(t-=l))break;e=0}else e-=o}if(this.size-t<25&&(this.children.length>1||!(this.children[0]instanceof ua))){var a=[];this.collapse(a),this.children=[new ua(a)],this.children[0].parent=this}},ca.prototype.collapse=function(e){for(var t=this,r=0;r=e){if(o.insertInner(e,t,r),o.lines&&o.lines.length>50){for(var s=o.lines.length%25+25,a=s;a10);e.parent.maybeSpill()}},ca.prototype.iterN=function(e,t,r){for(var n=this,i=0;ie){var s=Math.min(t,l-e);if(o.iterN(e,s,r))return!0;if(0==(t-=s))break;e=0}else e-=l}};var fa=function(e,t,r){var n=this;if(r)for(var i in r)r.hasOwnProperty(i)&&(n[i]=r[i]);this.doc=e,this.node=t};fa.prototype.clear=function(){var e=this,t=this.doc.cm,r=this.line.widgets,n=this.line,i=A(n); -if(null!=i&&r){for(var o=0;ot.display.maxLineLength&&(t.display.maxLine=c,t.display.maxLineLength=f,t.display.maxLineChanged=!0)}null!=i&&t&&this.collapsed&&pi(t,i,o+1),this.lines.length=0,this.explicitlyCleared=!0,this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,t&&vo(t.doc)),t&&Sr(t,"markerCleared",t,this,i,o),r&&ni(t),this.parent&&this.parent.clear()}},da.prototype.find=function(e,t){var r=this;null==e&&"bookmark"==this.type&&(e=1);for(var n,i,o=0;o=0;u--)So(n,i[u]);a?fo(this,a):this.cm&&ei(this.cm)}),undo:di(function(){To(this,"undo")}),redo:di(function(){To(this,"redo")}),undoSelection:di(function(){To(this,"undo",!0)}),redoSelection:di(function(){To(this,"redo",!0)}),setExtending:function(e){this.extend=e},getExtending:function(){return this.extend},historySize:function(){for(var e=this.history,t=0,r=0,n=0;n=e.ch)&&t.push(i.marker.parent||i.marker)}return t},findMarks:function(e,t,r){e=U(this,e),t=U(this,t);var n=[],i=e.line;return this.iter(e.line,t.line+1,function(o){var l=o.markedSpans;if(l)for(var s=0;s=a.to||null==a.from&&i!=e.line||null!=a.from&&i==t.line&&a.from>=t.ch||r&&!r(a.marker)||n.push(a.marker.parent||a.marker)}++i}),n},getAllMarks:function(){var e=[];return this.iter(function(t){var r=t.markedSpans;if(r)for(var n=0;ne?(t=e,!0):(e-=o,void++r)}),U(this,E(r,t))},indexFromPos:function(e){e=U(this,e);var t=e.ch;if(e.linet&&(t=e.from),null!=e.to&&e.towa;wa++)ba[wa+48]=ba[wa+96]=String(wa);for(var xa=65;90>=xa;xa++)ba[xa]=String.fromCharCode(xa);for(var Ca=1;12>=Ca;Ca++)ba[Ca+111]=ba[Ca+63235]="F"+Ca;var Sa={};Sa.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"},Sa.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"},Sa.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"},Sa.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"]},Sa["default"]=hs?Sa.macDefault:Sa.pcDefault;var La,Ta,ka={selectAll:xo,singleSelection:function(e){return e.setSelection(e.getCursor("anchor"),e.getCursor("head"),ks)},killLine:function(e){return tl(e,function(t){if(t.empty()){var r=M(e.doc,t.head.line).text.length;return t.head.ch==r&&t.head.line0)i=new E(i.line,i.ch+1),e.replaceRange(o.charAt(i.ch-1)+o.charAt(i.ch-2),E(i.line,i.ch-2),i,"+transpose");else if(i.line>e.doc.first){var l=M(e.doc,i.line-1).text;l&&(i=new E(i.line,1),e.replaceRange(o.charAt(0)+e.doc.lineSeparator()+l.charAt(l.length-1),E(i.line-1,l.length-1),i,"+transpose"))}r.push(new aa(i,i))}e.setSelections(r)})},newlineAndIndent:function(e){return ci(e,function(){for(var t=e.listSelections(),r=t.length-1;r>=0;r--)e.replaceRange(e.doc.lineSeparator(),t[r].anchor,t[r].head,"+input");t=e.listSelections();for(var n=0;n=ts&&setTimeout(fi(i,function(){return r.updateFromDOM()}),20)}),Is(o,"compositionstart",function(e){r.composing={data:e.data,done:!1}}),Is(o,"compositionupdate",function(e){r.composing||(r.composing={data:e.data,done:!1})}),Is(o,"compositionend",function(e){r.composing&&(e.data!=r.composing.data&&r.readFromDOMSoon(),r.composing.done=!0)}),Is(o,"touchstart",function(){return n.forceCompositionEnd()}),Is(o,"input",function(){r.composing||r.readFromDOMSoon()}),Is(o,"copy",t),Is(o,"cut",t)},Pa.prototype.prepareSelection=function(){var e=Mn(this.cm,!1);return e.focus=this.cm.state.focused,e},Pa.prototype.showSelection=function(e,t){e&&this.cm.display.view.length&&((e.focus||t)&&this.showPrimarySelection(),this.showMultipleSelections(e))},Pa.prototype.showPrimarySelection=function(){var e=window.getSelection(),t=this.cm.doc.sel.primary(),r=Kl(this.cm,e.anchorNode,e.anchorOffset),n=Kl(this.cm,e.focusNode,e.focusOffset);if(!r||r.bad||!n||n.bad||0!=F(B(r,n),t.from())||0!=F(R(r,n),t.to())){var i=Bl(this.cm,t.from()),o=Bl(this.cm,t.to());if(!i&&!o)return void e.removeAllRanges();var l=this.cm.display.view,s=e.rangeCount&&e.getRangeAt(0);if(i){if(!o){var a=l[l.length-1].measure,u=a.maps?a.maps[a.maps.length-1]:a.map;o={node:u[u.length-1],offset:u[u.length-2]-u[u.length-3]}}}else i={node:l[0].measure.map[2],offset:0};var c;try{c=vs(i.node,i.offset,o.offset,o.node)}catch(f){}c&&(!ql&&this.cm.state.focused?(e.collapse(i.node,i.offset),c.collapsed||(e.removeAllRanges(),e.addRange(c))):(e.removeAllRanges(),e.addRange(c)),s&&null==e.anchorNode?e.addRange(s):ql&&this.startGracePeriod()),this.rememberSelection()}},Pa.prototype.startGracePeriod=function(){var e=this;clearTimeout(this.gracePeriod),this.gracePeriod=setTimeout(function(){e.gracePeriod=!1,e.selectionChanged()&&e.cm.operation(function(){return e.cm.curOp.selectionChanged=!0})},20)},Pa.prototype.showMultipleSelections=function(e){r(this.cm.display.cursorDiv,e.cursors),r(this.cm.display.selectionDiv,e.selection)},Pa.prototype.rememberSelection=function(){var e=window.getSelection();this.lastAnchorNode=e.anchorNode,this.lastAnchorOffset=e.anchorOffset,this.lastFocusNode=e.focusNode,this.lastFocusOffset=e.focusOffset},Pa.prototype.selectionInEditor=function(){var e=window.getSelection();if(!e.rangeCount)return!1;var t=e.getRangeAt(0).commonAncestorContainer;return o(this.div,t)},Pa.prototype.focus=function(){"nocursor"!=this.cm.options.readOnly&&(this.selectionInEditor()||this.showSelection(this.prepareSelection(),!0),this.div.focus())},Pa.prototype.blur=function(){this.div.blur()},Pa.prototype.getField=function(){return this.div},Pa.prototype.supportsTouch=function(){return!0},Pa.prototype.receivedFocus=function(){function e(){t.cm.state.focused&&(t.pollSelection(),t.polling.set(t.cm.options.pollInterval,e))}var t=this;this.selectionInEditor()?this.pollSelection():ci(this.cm,function(){return t.cm.curOp.selectionChanged=!0}),this.polling.set(this.cm.options.pollInterval,e)},Pa.prototype.selectionChanged=function(){var e=window.getSelection();return e.anchorNode!=this.lastAnchorNode||e.anchorOffset!=this.lastAnchorOffset||e.focusNode!=this.lastFocusNode||e.focusOffset!=this.lastFocusOffset},Pa.prototype.pollSelection=function(){if(null==this.readDOMTimeout&&!this.gracePeriod&&this.selectionChanged()){var e=window.getSelection(),t=this.cm;if(cs&&is&&this.cm.options.gutters.length&&Gl(e.anchorNode))return this.cm.triggerOnKeyDown({type:"keydown",keyCode:8,preventDefault:Math.abs}),this.blur(),void this.focus();if(!this.composing){this.rememberSelection();var r=Kl(t,e.anchorNode,e.anchorOffset),n=Kl(t,e.focusNode,e.focusOffset);r&&n&&ci(t,function(){ho(t.doc,Di(r,n),ks),(r.bad||n.bad)&&(t.curOp.selectionChanged=!0)})}}},Pa.prototype.pollContent=function(){null!=this.readDOMTimeout&&(clearTimeout(this.readDOMTimeout),this.readDOMTimeout=null);var e=this.cm,t=e.display,r=e.doc.sel.primary(),n=r.from(),i=r.to();if(0==n.ch&&n.line>e.firstLine()&&(n=E(n.line-1,M(e.doc,n.line-1).length)),i.ch==M(e.doc,i.line).text.length&&i.linet.viewTo-1)return!1;var o,l,s;n.line==t.viewFrom||0==(o=Tn(e,n.line))?(l=A(t.view[0].line),s=t.view[0].node):(l=A(t.view[o].line),s=t.view[o-1].node.nextSibling);var a,u,c=Tn(e,i.line);if(c==t.view.length-1?(a=t.viewTo-1,u=t.lineDiv.lastChild):(a=A(t.view[c+1].line)-1,u=t.view[c+1].node.previousSibling),!s)return!1;for(var f=e.doc.splitLines(Vl(e,s,u,l,a)),h=N(e.doc,E(l,0),E(a,M(e.doc,a).text.length));f.length>1&&h.length>1;)if(g(f)==g(h))f.pop(),h.pop(),a--;else{if(f[0]!=h[0])break;f.shift(),h.shift(),l++}for(var d=0,p=0,v=f[0],m=h[0],y=Math.min(v.length,m.length);y>d&&v.charCodeAt(d)==m.charCodeAt(d);)++d;for(var b=g(f),w=g(h),x=Math.min(b.length-(1==f.length?d:0),w.length-(1==h.length?d:0));x>p&&b.charCodeAt(b.length-p-1)==w.charCodeAt(w.length-p-1);)++p;if(1==f.length&&1==h.length&&l==n.line)for(;d&&d>n.ch&&b.charCodeAt(b.length-p-1)==w.charCodeAt(w.length-p-1);)d--,p++;f[f.length-1]=b.slice(0,b.length-p).replace(/^\u200b+/,""),f[0]=f[0].slice(d).replace(/\u200b+$/,"");var C=E(l,d),S=E(a,h.length?g(h).length-p:0);return f.length>1||f[0]||F(C,S)?(Oo(e.doc,f,C,S,"+input"),!0):void 0},Pa.prototype.ensurePolled=function(){this.forceCompositionEnd()},Pa.prototype.reset=function(){this.forceCompositionEnd()},Pa.prototype.forceCompositionEnd=function(){this.composing&&(clearTimeout(this.readDOMTimeout),this.composing=null,this.updateFromDOM(),this.div.blur(),this.div.focus())},Pa.prototype.readFromDOMSoon=function(){var e=this;null==this.readDOMTimeout&&(this.readDOMTimeout=setTimeout(function(){if(e.readDOMTimeout=null,e.composing){if(!e.composing.done)return;e.composing=null}e.updateFromDOM()},80))},Pa.prototype.updateFromDOM=function(){var e=this;(this.cm.isReadOnly()||!this.pollContent())&&ci(this.cm,function(){return pi(e.cm)})},Pa.prototype.setUneditable=function(e){e.contentEditable="false"},Pa.prototype.onKeyPress=function(e){0!=e.charCode&&(e.preventDefault(),this.cm.isReadOnly()||fi(this.cm,Al)(this.cm,String.fromCharCode(null==e.charCode?e.keyCode:e.charCode),0))},Pa.prototype.readOnlyChanged=function(e){this.div.contentEditable=String("nocursor"!=e)},Pa.prototype.onContextMenu=function(){},Pa.prototype.resetPosition=function(){},Pa.prototype.needsContentAttribute=!0;var Ea=function(e){this.cm=e,this.prevInput="",this.pollingFast=!1,this.polling=new xs,this.inaccurateSelection=!1,this.hasSelection=!1,this.composing=null};Ea.prototype.init=function(e){function t(e){if(!At(i,e)){if(i.somethingSelected())Wl({lineWise:!1,text:i.getSelections()}),n.inaccurateSelection&&(n.prevInput="",n.inaccurateSelection=!1,l.value=Ha.text.join("\n"),ws(l));else{if(!i.options.lineWiseCopyCut)return;var t=Pl(i);Wl({lineWise:!0,text:t.text}),"cut"==e.type?i.setSelections(t.ranges,null,ks):(n.prevInput="",l.value=t.text.join("\n"),ws(l))}"cut"==e.type&&(i.state.cutIncoming=!0)}}var r=this,n=this,i=this.cm,o=this.wrapper=Fl(),l=this.textarea=o.firstChild;e.wrapper.insertBefore(o,e.wrapper.firstChild),us&&(l.style.width="0px"),Is(l,"input",function(){es&&ts>=9&&r.hasSelection&&(r.hasSelection=null),n.poll()}),Is(l,"paste",function(e){At(i,e)||Dl(e,i)||(i.state.pasteIncoming=!0,n.fastPoll())}),Is(l,"cut",t),Is(l,"copy",t),Is(e.scroller,"paste",function(t){zr(e,t)||At(i,t)||(i.state.pasteIncoming=!0,n.focus())}),Is(e.lineSpace,"selectstart",function(t){zr(e,t)||Et(t)}),Is(l,"compositionstart",function(){var e=i.getCursor("from");n.composing&&n.composing.range.clear(),n.composing={start:e,range:i.markText(e,i.getCursor("to"),{className:"CodeMirror-composing"})}}),Is(l,"compositionend",function(){n.composing&&(n.poll(),n.composing.range.clear(),n.composing=null)})},Ea.prototype.prepareSelection=function(){var e=this.cm,t=e.display,r=e.doc,n=Mn(e);if(e.options.moveInputWithCursor){var i=fn(e,r.sel.primary().head,"div"),o=t.wrapper.getBoundingClientRect(),l=t.lineDiv.getBoundingClientRect();n.teTop=Math.max(0,Math.min(t.wrapper.clientHeight-10,i.top+l.top-o.top)),n.teLeft=Math.max(0,Math.min(t.wrapper.clientWidth-10,i.left+l.left-o.left))}return n},Ea.prototype.showSelection=function(e){var t=this.cm,n=t.display;r(n.cursorDiv,e.cursors),r(n.selectionDiv,e.selection),null!=e.teTop&&(this.wrapper.style.top=e.teTop+"px",this.wrapper.style.left=e.teLeft+"px")},Ea.prototype.reset=function(e){if(!this.contextMenuPending){var t,r,n=this.cm,i=n.doc;if(n.somethingSelected()){this.prevInput="";var o=i.sel.primary();t=Gs&&(o.to().line-o.from().line>100||(r=n.getSelection()).length>1e3);var l=t?"-":r||n.getSelection();this.textarea.value=l,n.state.focused&&ws(this.textarea),es&&ts>=9&&(this.hasSelection=l)}else e||(this.prevInput=this.textarea.value="",es&&ts>=9&&(this.hasSelection=null));this.inaccurateSelection=t}},Ea.prototype.getField=function(){return this.textarea},Ea.prototype.supportsTouch=function(){return!1},Ea.prototype.focus=function(){if("nocursor"!=this.cm.options.readOnly&&(!fs||l()!=this.textarea))try{this.textarea.focus()}catch(e){}},Ea.prototype.blur=function(){this.textarea.blur()},Ea.prototype.resetPosition=function(){this.wrapper.style.top=this.wrapper.style.left=0},Ea.prototype.receivedFocus=function(){this.slowPoll()},Ea.prototype.slowPoll=function(){var e=this;this.pollingFast||this.polling.set(this.cm.options.pollInterval,function(){e.poll(),e.cm.state.focused&&e.slowPoll()})},Ea.prototype.fastPoll=function(){function e(){var n=r.poll();n||t?(r.pollingFast=!1,r.slowPoll()):(t=!0,r.polling.set(60,e))}var t=!1,r=this;r.pollingFast=!0,r.polling.set(20,e)},Ea.prototype.poll=function(){var e=this,t=this.cm,r=this.textarea,n=this.prevInput;if(this.contextMenuPending||!t.state.focused||Bs(r)&&!n&&!this.composing||t.isReadOnly()||t.options.disableInput||t.state.keySeq)return!1;var i=r.value;if(i==n&&!t.somethingSelected())return!1;if(es&&ts>=9&&this.hasSelection===i||hs&&/[\uf700-\uf7ff]/.test(i))return t.display.input.reset(),!1;if(t.doc.sel==t.display.selForContextMenu){var o=i.charCodeAt(0);if(8203!=o||n||(n="​"),8666==o)return this.reset(),this.cm.execCommand("undo")}for(var l=0,s=Math.min(n.length,i.length);s>l&&n.charCodeAt(l)==i.charCodeAt(l);)++l;return ci(t,function(){Al(t,i.slice(l),n.length-l,null,e.composing?"*compose":null),i.length>1e3||i.indexOf("\n")>-1?r.value=e.prevInput="":e.prevInput=i,e.composing&&(e.composing.range.clear(),e.composing.range=t.markText(e.composing.start,t.getCursor("to"),{className:"CodeMirror-composing"}))}),!0},Ea.prototype.ensurePolled=function(){this.pollingFast&&this.poll()&&(this.pollingFast=!1)},Ea.prototype.onKeyPress=function(){es&&ts>=9&&(this.hasSelection=null),this.fastPoll()},Ea.prototype.onContextMenu=function(e){function t(){if(null!=l.selectionStart){var e=i.somethingSelected(),t="​"+(e?l.value:"");l.value="⇚",l.value=t,n.prevInput=e?"":"​",l.selectionStart=1,l.selectionEnd=t.length,o.selForContextMenu=i.doc.sel}}function r(){if(n.contextMenuPending=!1,n.wrapper.style.cssText=f,l.style.cssText=c,es&&9>ts&&o.scrollbars.setScrollTop(o.scroller.scrollTop=a),null!=l.selectionStart){(!es||es&&9>ts)&&t();var e=0,r=function(){o.selForContextMenu==i.doc.sel&&0==l.selectionStart&&l.selectionEnd>0&&"​"==n.prevInput?fi(i,xo)(i):e++<10?o.detectingSelectAll=setTimeout(r,500):(o.selForContextMenu=null,o.input.reset())};o.detectingSelectAll=setTimeout(r,200)}}var n=this,i=n.cm,o=i.display,l=n.textarea,s=Ln(i,e),a=o.scroller.scrollTop;if(s&&!os){var u=i.options.resetSelectionOnContextMenu;u&&-1==i.doc.sel.contains(s)&&fi(i,ho)(i.doc,Di(s),ks);var c=l.style.cssText,f=n.wrapper.style.cssText;n.wrapper.style.cssText="position: absolute"; -var h=n.wrapper.getBoundingClientRect();l.style.cssText="position: absolute; width: 30px; height: 30px;\n top: "+(e.clientY-h.top-5)+"px; left: "+(e.clientX-h.left-5)+"px;\n z-index: 1000; background: "+(es?"rgba(255, 255, 255, .05)":"transparent")+";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";var d;if(rs&&(d=window.scrollY),o.input.focus(),rs&&window.scrollTo(null,d),o.input.reset(),i.somethingSelected()||(l.value=n.prevInput=" "),n.contextMenuPending=!0,o.selForContextMenu=i.doc.sel,clearTimeout(o.detectingSelectAll),es&&ts>=9&&t(),ys){zt(e);var p=function(){Ot(window,"mouseup",p),setTimeout(r,20)};Is(window,"mouseup",p)}else setTimeout(r,50)}},Ea.prototype.readOnlyChanged=function(e){e||this.reset()},Ea.prototype.setUneditable=function(){},Ea.prototype.needsContentAttribute=!1,Sl(Ml),Il(Ml);var Fa="iter insert remove copy getEditor constructor".split(" ");for(var Ia in va.prototype)va.prototype.hasOwnProperty(Ia)&&h(Fa,Ia)<0&&(Ml.prototype[Ia]=function(e){return function(){return e.apply(this.doc,arguments)}}(va.prototype[Ia]));return Pt(va),Ml.inputStyles={textarea:Ea,contenteditable:Pa},Ml.defineMode=function(e){Ml.defaults.mode||"null"==e||(Ml.defaults.mode=e),Kt.apply(this,arguments)},Ml.defineMIME=jt,Ml.defineMode("null",function(){return{token:function(e){return e.skipToEnd()}}}),Ml.defineMIME("text/plain","null"),Ml.defineExtension=function(e,t){Ml.prototype[e]=t},Ml.defineDocExtension=function(e,t){va.prototype[e]=t},Ml.fromTextArea=Xl,Yl(Ml),Ml.version="5.25.1",Ml}); \ No newline at end of file +define(function(){ + "use strict"; + + function CodeMirror(place, givenOptions) { + var options = {}, + defaults = CodeMirror.defaults; + for (var opt in defaults) + if (defaults.hasOwnProperty(opt)) + options[opt] = (givenOptions && givenOptions.hasOwnProperty(opt) ? givenOptions : defaults)[opt]; + var input = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em"); + input.setAttribute("wrap", "off"); + input.setAttribute("autocorrect", "off"); + input.setAttribute("autocapitalize", "off"); + var inputDiv = elt("div", [input], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); + var scrollbarInner = elt("div", null, "CodeMirror-scrollbar-inner"); + var scrollbar = elt("div", [scrollbarInner], "CodeMirror-scrollbar"); + var lineDiv = elt("div"), + selectionDiv = elt("div", null, null, "position: relative; z-index: -1"); + var cursor = elt("pre", "\u00a0", "CodeMirror-cursor"), + widthForcer = elt("pre", "\u00a0", "CodeMirror-cursor", "visibility: hidden"); + var measure = elt("div", null, null, "position: absolute; width: 100%; height: 0px; overflow: hidden; visibility: hidden;"); + var lineSpace = elt("div", [measure, cursor, widthForcer, selectionDiv, lineDiv], null, "position: relative; z-index: 0"); + var gutterText = elt("div", null, "CodeMirror-gutter-text"), + gutter = elt("div", [gutterText], "CodeMirror-gutter"); + var mover = elt("div", [gutter, elt("div", [lineSpace], "CodeMirror-lines")], null, "position: relative"); + var sizer = elt("div", [mover], null, "position: relative"); + var scroller = elt("div", [sizer], "CodeMirror-scroll"); + scroller.setAttribute("tabIndex", "-1"); + var wrapper = elt("div", [inputDiv, scrollbar, scroller], "CodeMirror" + (options.lineWrapping ? " CodeMirror-wrap" : "")); + if (place.appendChild) place.appendChild(wrapper); + else place(wrapper); + themeChanged(); + keyMapChanged(); + if (ios) input.style.width = "0px"; + if (!webkit) scroller.draggable = true; + lineSpace.style.outline = "none"; + if (options.tabindex != null) input.tabIndex = options.tabindex; + if (options.autofocus) focusInput(); + if (!options.gutter && !options.lineNumbers) gutter.style.display = "none"; + if (khtml) inputDiv.style.height = "1px", inputDiv.style.position = "absolute"; + if (mac_geLion) { + scrollbar.style.zIndex = -2; + scrollbar.style.visibility = "hidden"; + } else if (ie_lt8) scrollbar.style.minWidth = "18px"; + var poll = new Delayed(), + highlight = new Delayed(), + blinker; + var mode, doc = new BranchChunk([new LeafChunk([new Line("")])]), + frontier = 0, + focused; + loadMode(); + var sel = { + from: { + line: 0, + ch: 0 + }, + to: { + line: 0, + ch: 0 + }, + inverted: false + }; + var shiftSelecting, lastClick, lastDoubleClick, lastScrollTop = 0, + draggingText, overwrite = false, + suppressEdits = false, + pasteIncoming = false; + var updateInput, userSelChange, changes, textChanged, selectionChanged, gutterDirty, callbacks; + var displayOffset = 0, + showingFrom = 0, + showingTo = 0, + lastSizeC = 0; + var bracketHighlighted; + var maxLine = getLine(0), + updateMaxLine = false, + maxLineChanged = true; + var pollingFast = false; + var goalColumn = null; + operation(function() { + setValue(options.value || ""); + updateInput = false; + })(); + var history = new History(); + connect(scroller, "mousedown", operation(onMouseDown)); + connect(scroller, "dblclick", operation(onDoubleClick)); + connect(lineSpace, "selectstart", e_preventDefault); + if (!gecko) connect(scroller, "contextmenu", onContextMenu); + connect(scroller, "scroll", onScrollMain); + connect(scrollbar, "scroll", onScrollBar); + connect(scrollbar, "mousedown", function() { + if (focused) setTimeout(focusInput, 0); + }); + var resizeHandler = connect(window, "resize", function() { + if (wrapper.parentNode) updateDisplay(true); + else resizeHandler(); + }, true); + connect(input, "keyup", operation(onKeyUp)); + connect(input, "input", fastPoll); + connect(input, "keydown", operation(onKeyDown)); + connect(input, "keypress", operation(onKeyPress)); + connect(input, "focus", onFocus); + connect(input, "blur", onBlur); + + function drag_(e) { + if (options.onDragEvent && options.onDragEvent(instance, addStop(e))) return; + e_stop(e); + } + if (options.dragDrop) { + connect(scroller, "dragstart", onDragStart); + connect(scroller, "dragenter", drag_); + connect(scroller, "dragover", drag_); + connect(scroller, "drop", operation(onDrop)); + } + connect(scroller, "paste", function() { + focusInput(); + fastPoll(); + }); + connect(input, "paste", function() { + pasteIncoming = true; + fastPoll(); + }); + connect(input, "cut", operation(function() { + if (!options.readOnly) replaceSelection(""); + })); + if (khtml) connect(sizer, "mouseup", function() { + if (document.activeElement == input) input.blur(); + focusInput(); + }); + var hasFocus; + try { + hasFocus = (document.activeElement == input); + } catch (e) {} + if (hasFocus || options.autofocus) setTimeout(onFocus, 20); + else onBlur(); + + function isLine(l) { + return l >= 0 && l < doc.size; + } + var __events = {}, noop = function(){}; + var instance = wrapper.CodeMirror = { + getValue: getValue, + setValue: operation(setValue), + getSelection: getSelection, + replaceSelection: operation(replaceSelection), + focus: function() { + window.focus(); + focusInput(); + onFocus(); + fastPoll(); + }, + setOption: function(option, value) { + var oldVal = options[option]; + options[option] = value; + if (option == "mode" || option == "indentUnit") loadMode(); + else if (option == "readOnly" && value == "nocursor") { + onBlur(); + input.blur(); + } else if (option == "readOnly" && !value) { + resetInput(true); + } else if (option == "theme") themeChanged(); + else if (option == "lineWrapping" && oldVal != value) operation(wrappingChanged)(); + else if (option == "tabSize") updateDisplay(true); + else if (option == "keyMap") keyMapChanged(); + else if (option == "tabindex") input.tabIndex = value; + if (option == "lineNumbers" || option == "gutter" || option == "firstLineNumber" || option == "theme" || option == "lineNumberFormatter") { + gutterChanged(); + updateDisplay(true); + } + }, + getOption: function(option) { + return options[option]; + }, + getMode: function() { + return mode; + }, + undo: operation(undo), + redo: operation(redo), + indentLine: operation(function(n, dir) { + if (typeof dir != "string") { + if (dir == null) dir = options.smartIndent ? "smart" : "prev"; + else dir = dir ? "add" : "subtract"; + } + if (isLine(n)) indentLine(n, dir); + }), + indentSelection: operation(indentSelected), + historySize: function() { + return { + undo: history.done.length, + redo: history.undone.length + }; + }, + clearHistory: function() { + history = new History(); + }, + setHistory: function(histData) { + history = new History(); + history.done = histData.done; + history.undone = histData.undone; + }, + getHistory: function() { + function cp(arr) { + for (var i = 0, nw = [], nwelt; i < arr.length; ++i) { + nw.push(nwelt = []); + for (var j = 0, elt = arr[i]; j < elt.length; ++j) { + var old = [], + cur = elt[j]; + nwelt.push({ + start: cur.start, + added: cur.added, + old: old + }); + for (var k = 0; k < cur.old.length; ++k) old.push(hlText(cur.old[k])); + } + } + return nw; + } + return { + done: cp(history.done), + undone: cp(history.undone) + }; + }, + matchBrackets: operation(function() { + matchBrackets(true); + }), + getTokenAt: operation(function(pos) { + pos = clipPos(pos); + return getLine(pos.line).getTokenAt(mode, getStateBefore(pos.line), options.tabSize, pos.ch); + }), + getStateAfter: function(line) { + line = clipLine(line == null ? doc.size - 1 : line); + return getStateBefore(line + 1); + }, + cursorCoords: function(start, mode) { + if (start == null) start = sel.inverted; + return this.charCoords(start ? sel.from : sel.to, mode); + }, + charCoords: function(pos, mode) { + pos = clipPos(pos); + if (mode == "local") return localCoords(pos, false); + if (mode == "div") return localCoords(pos, true); + return pageCoords(pos); + }, + coordsChar: function(coords) { + var off = eltOffset(lineSpace); + return coordsChar(coords.x - off.left, coords.y - off.top); + }, + defaultTextHeight: function() { + return textHeight(); + }, + markText: operation(markText), + setBookmark: setBookmark, + findMarksAt: findMarksAt, + setMarker: operation(addGutterMarker), + clearMarker: operation(removeGutterMarker), + setLineClass: operation(setLineClass), + hideLine: operation(function(h) { + return setLineHidden(h, true); + }), + showLine: operation(function(h) { + return setLineHidden(h, false); + }), + onDeleteLine: function(line, f) { + if (typeof line == "number") { + if (!isLine(line)) return null; + line = getLine(line); + } + (line.handlers || (line.handlers = [])).push(f); + return line; + }, + lineInfo: lineInfo, + getViewport: function() { + return { + from: showingFrom, + to: showingTo + }; + }, + addWidget: function(pos, node, scroll, vert, horiz) { + pos = localCoords(clipPos(pos)); + var top = pos.yBot, + left = pos.x; + node.style.position = "absolute"; + sizer.appendChild(node); + if (vert == "over") top = pos.y; + else if (vert == "near") { + var vspace = Math.max(scroller.offsetHeight, doc.height * textHeight()), + hspace = Math.max(sizer.clientWidth, lineSpace.clientWidth) - paddingLeft(); + if (pos.yBot + node.offsetHeight > vspace && pos.y > node.offsetHeight) + top = pos.y - node.offsetHeight; + if (left + node.offsetWidth > hspace) + left = hspace - node.offsetWidth; + } + node.style.top = (top + paddingTop()) + "px"; + node.style.left = node.style.right = ""; + if (horiz == "right") { + left = sizer.clientWidth - node.offsetWidth; + node.style.right = "0px"; + } else { + if (horiz == "left") left = 0; + else if (horiz == "middle") left = (sizer.clientWidth - node.offsetWidth) / 2; + node.style.left = (left + paddingLeft()) + "px"; + } + if (scroll) + scrollIntoView(left, top, left + node.offsetWidth, top + node.offsetHeight); + }, + lineCount: function() { + return doc.size; + }, + clipPos: clipPos, + getCursor: function(start) { + if (start == null) start = sel.inverted; + return copyPos(start ? sel.from : sel.to); + }, + somethingSelected: function() { + return !posEq(sel.from, sel.to); + }, + setCursor: operation(function(line, ch, user) { + if (ch == null && typeof line.line == "number") setCursor(line.line, line.ch, user); + else setCursor(line, ch, user); + }), + setSelection: operation(function(from, to, user) { + (user ? setSelectionUser : setSelection)(clipPos(from), clipPos(to || from)); + }), + getLine: function(line) { + if (isLine(line)) return getLine(line).text; + }, + getLineHandle: function(line) { + if (isLine(line)) return getLine(line); + }, + setLine: operation(function(line, text) { + if (isLine(line)) replaceRange(text, { + line: line, + ch: 0 + }, { + line: line, + ch: getLine(line).text.length + }); + }), + removeLine: operation(function(line) { + if (isLine(line)) replaceRange("", { + line: line, + ch: 0 + }, clipPos({ + line: line + 1, + ch: 0 + })); + }), + replaceRange: operation(replaceRange), + getRange: function(from, to, lineSep) { + return getRange(clipPos(from), clipPos(to), lineSep); + }, + triggerOnKeyDown: operation(onKeyDown), + execCommand: function(cmd) { + return commands[cmd](instance); + }, + moveH: operation(moveH), + deleteH: operation(deleteH), + moveV: operation(moveV), + toggleOverwrite: function() { + if (overwrite) { + overwrite = false; + cursor.className = cursor.className.replace(" CodeMirror-overwrite", ""); + } else { + overwrite = true; + cursor.className += " CodeMirror-overwrite"; + } + }, + posFromIndex: function(off) { + var lineNo = 0, + ch; + doc.iter(0, doc.size, function(line) { + var sz = line.text.length + 1; + if (sz > off) { + ch = off; + return true; + } + off -= sz; + ++lineNo; + }); + return clipPos({ + line: lineNo, + ch: ch + }); + }, + indexFromPos: function(coords) { + if (coords.line < 0 || coords.ch < 0) return 0; + var index = coords.ch; + doc.iter(0, coords.line, function(line) { + index += line.text.length + 1; + }); + return index; + }, + scrollTo: function(x, y) { + if (x != null) scroller.scrollLeft = x; + if (y != null) scrollbar.scrollTop = scroller.scrollTop = y; + updateDisplay([]); + }, + getScrollInfo: function() { + return { + x: scroller.scrollLeft, + y: scrollbar.scrollTop, + height: scrollbar.scrollHeight, + width: scroller.scrollWidth + }; + }, + scrollIntoView: function(pos) { + var coords = localCoords(pos ? clipPos(pos) : sel.inverted ? sel.from : sel.to); + scrollIntoView(coords.x, coords.y, coords.x, coords.yBot); + }, + setSize: function(width, height) { + function interpret(val) { + val = String(val); + return /^\d+$/.test(val) ? val + "px" : val; + } + if (width != null) wrapper.style.width = interpret(width); + if (height != null) scroller.style.height = interpret(height); + instance.refresh(); + }, + operation: function(f) { + return operation(f)(); + }, + compoundChange: function(f) { + return compoundChange(f); + }, + refresh: function() { + updateDisplay(true, null, lastScrollTop); + if (scrollbar.scrollHeight > lastScrollTop) + scrollbar.scrollTop = lastScrollTop; + }, + getInputField: function() { + return input; + }, + getWrapperElement: function() { + return wrapper; + }, + getScrollerElement: function() { + return scroller; + }, + getGutterElement: function() { + return gutter; + }, + on: function(name, cb){ + if(!cb || typeof cb !== 'function') return this; + if(!__events[name]){ + __events[name] = [cb] + }else{ + __events[name].push(cb) + } + return this + } + }; + + function getLine(n) { + return getLineAt(doc, n); + } + + function updateLineHeight(line, height) { + gutterDirty = true; + var diff = height - line.height; + for (var n = line; n; n = n.parent) n.height += diff; + } + + function lineContent(line, wrapAt) { + if (!line.styles) + line.highlight(mode, line.stateAfter = getStateBefore(lineNo(line)), options.tabSize); + return line.getContent(options.tabSize, wrapAt, options.lineWrapping); + } + + function setValue(code) { + var top = { + line: 0, + ch: 0 + }; + updateLines(top, { + line: doc.size - 1, + ch: getLine(doc.size - 1).text.length + }, splitLines(code), top, top); + updateInput = true; + } + + function getValue(lineSep) { + var text = []; + doc.iter(0, doc.size, function(line) { + text.push(line.text); + }); + return text.join(lineSep || "\n"); + } + + function onScrollBar(e) { + if (Math.abs(scrollbar.scrollTop - lastScrollTop) > 1) { + lastScrollTop = scroller.scrollTop = scrollbar.scrollTop; + updateDisplay([]); + } + } + + function onScrollMain(e) { + if (options.fixedGutter && gutter.style.left != scroller.scrollLeft + "px") + gutter.style.left = scroller.scrollLeft + "px"; + if (Math.abs(scroller.scrollTop - lastScrollTop) > 1) { + lastScrollTop = scroller.scrollTop; + if (scrollbar.scrollTop != lastScrollTop) + scrollbar.scrollTop = lastScrollTop; + updateDisplay([]); + } + if (options.onScroll) options.onScroll(instance); + } + + function onMouseDown(e) { + setShift(e_prop(e, "shiftKey")); + for (var n = e_target(e); n != wrapper; n = n.parentNode) + if (n.parentNode == sizer && n != mover) return; + for (var n = e_target(e); n != wrapper; n = n.parentNode) + if (n.parentNode == gutterText) { + if (options.onGutterClick) + options.onGutterClick(instance, indexOf(gutterText.childNodes, n) + showingFrom, e); + return e_preventDefault(e); + } + var start = posFromMouse(e); + switch (e_button(e)) { + case 3: + if (gecko) onContextMenu(e); + return; + case 2: + if (start) setCursor(start.line, start.ch, true); + setTimeout(focusInput, 20); + e_preventDefault(e); + return; + } + if (!start) { + if (e_target(e) == scroller) e_preventDefault(e); + return; + } + if (!focused) onFocus(); + var now = +new Date, + type = "single"; + if (lastDoubleClick && lastDoubleClick.time > now - 400 && posEq(lastDoubleClick.pos, start)) { + type = "triple"; + e_preventDefault(e); + setTimeout(focusInput, 20); + selectLine(start.line); + } else if (lastClick && lastClick.time > now - 400 && posEq(lastClick.pos, start)) { + type = "double"; + lastDoubleClick = { + time: now, + pos: start + }; + e_preventDefault(e); + var word = findWordAt(start); + setSelectionUser(word.from, word.to); + } else { + lastClick = { + time: now, + pos: start + }; + } + + function dragEnd(e2) { + if (webkit) scroller.draggable = false; + draggingText = false; + up(); + drop(); + if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) { + e_preventDefault(e2); + setCursor(start.line, start.ch, true); + focusInput(); + } + } + var last = start, + going; + if (options.dragDrop && dragAndDrop && !options.readOnly && !posEq(sel.from, sel.to) && !posLess(start, sel.from) && !posLess(sel.to, start) && type == "single") { + if (webkit) scroller.draggable = true; + var up = connect(document, "mouseup", operation(dragEnd), true); + var drop = connect(scroller, "drop", operation(dragEnd), true); + draggingText = true; + if (scroller.dragDrop) scroller.dragDrop(); + return; + } + e_preventDefault(e); + if (type == "single") setCursor(start.line, start.ch, true); + var startstart = sel.from, + startend = sel.to; + + function doSelect(cur) { + if (type == "single") { + setSelectionUser(start, cur); + } else if (type == "double") { + var word = findWordAt(cur); + if (posLess(cur, startstart)) setSelectionUser(word.from, startend); + else setSelectionUser(startstart, word.to); + } else if (type == "triple") { + if (posLess(cur, startstart)) setSelectionUser(startend, clipPos({ + line: cur.line, + ch: 0 + })); + else setSelectionUser(startstart, clipPos({ + line: cur.line + 1, + ch: 0 + })); + } + } + + function extend(e) { + var cur = posFromMouse(e, true); + if (cur && !posEq(cur, last)) { + if (!focused) onFocus(); + last = cur; + doSelect(cur); + updateInput = false; + var visible = visibleLines(); + if (cur.line >= visible.to || cur.line < visible.from) + going = setTimeout(operation(function() { + extend(e); + }), 150); + } + } + + function done(e) { + clearTimeout(going); + var cur = posFromMouse(e); + if (cur) doSelect(cur); + e_preventDefault(e); + focusInput(); + updateInput = true; + move(); + up(); + } + var move = connect(document, "mousemove", operation(function(e) { + clearTimeout(going); + e_preventDefault(e); + if (!ie && !e_button(e)) done(e); + else extend(e); + }), true); + var up = connect(document, "mouseup", operation(done), true); + } + + function onDoubleClick(e) { + for (var n = e_target(e); n != wrapper; n = n.parentNode) + if (n.parentNode == gutterText) return e_preventDefault(e); + e_preventDefault(e); + } + + function onDrop(e) { + if (options.onDragEvent && options.onDragEvent(instance, addStop(e))) return; + e_preventDefault(e); + var pos = posFromMouse(e, true), + files = e.dataTransfer.files; + if (!pos || options.readOnly) return; + if (files && files.length && window.FileReader && window.File) { + var n = files.length, + text = Array(n), + read = 0; + var loadFile = function(file, i) { + var reader = new FileReader; + reader.onload = function() { + text[i] = reader.result; + if (++read == n) { + pos = clipPos(pos); + operation(function() { + var end = replaceRange(text.join(""), pos, pos); + setSelectionUser(pos, end); + })(); + } + }; + reader.readAsText(file); + }; + for (var i = 0; i < n; ++i) loadFile(files[i], i); + } else { + if (draggingText && !(posLess(pos, sel.from) || posLess(sel.to, pos))) return; + try { + var text = e.dataTransfer.getData("Text"); + if (text) { + compoundChange(function() { + var curFrom = sel.from, + curTo = sel.to; + setSelectionUser(pos, pos); + if (draggingText) replaceRange("", curFrom, curTo); + replaceSelection(text); + focusInput(); + }); + } + } catch (e) {} + } + } + + function onDragStart(e) { + var txt = getSelection(); + e.dataTransfer.setData("Text", txt); + if (e.dataTransfer.setDragImage) + e.dataTransfer.setDragImage(elt('img'), 0, 0); + } + + function doHandleBinding(bound, dropShift) { + if (typeof bound == "string") { + bound = commands[bound]; + if (!bound) return false; + } + var prevShift = shiftSelecting; + try { + if (options.readOnly) suppressEdits = true; + if (dropShift) shiftSelecting = null; + bound(instance); + } catch (e) { + if (e != Pass) throw e; + return false; + } finally { + shiftSelecting = prevShift; + suppressEdits = false; + } + return true; + } + var maybeTransition; + + function handleKeyBinding(e) { + var startMap = getKeyMap(options.keyMap), + next = startMap.auto; + clearTimeout(maybeTransition); + if (next && !isModifierKey(e)) maybeTransition = setTimeout(function() { + if (getKeyMap(options.keyMap) == startMap) { + options.keyMap = (next.call ? next.call(null, instance) : next); + } + }, 50); + var name = keyNames[e_prop(e, "keyCode")], + handled = false; + var flipCtrlCmd = opera && mac; + if (name == null || e.altGraphKey) return false; + if (e_prop(e, "altKey")) name = "Alt-" + name; + if (e_prop(e, flipCtrlCmd ? "metaKey" : "ctrlKey")) name = "Ctrl-" + name; + if (e_prop(e, flipCtrlCmd ? "ctrlKey" : "metaKey")) name = "Cmd-" + name; + var stopped = false; + + function stop() { + stopped = true; + } + if (e_prop(e, "shiftKey")) { + handled = lookupKey("Shift-" + name, options.extraKeys, options.keyMap, function(b) { + return doHandleBinding(b, true); + }, stop) || lookupKey(name, options.extraKeys, options.keyMap, function(b) { + if (typeof b == "string" && /^go[A-Z]/.test(b)) return doHandleBinding(b); + }, stop); + } else { + handled = lookupKey(name, options.extraKeys, options.keyMap, doHandleBinding, stop); + } + if (stopped) handled = false; + if (handled) { + e_preventDefault(e); + restartBlink(); + if (ie_lt9) { + e.oldKeyCode = e.keyCode; + e.keyCode = 0; + } + } + return handled; + } + + function handleCharBinding(e, ch) { + var handled = lookupKey("'" + ch + "'", options.extraKeys, options.keyMap, function(b) { + return doHandleBinding(b, true); + }); + if (handled) { + e_preventDefault(e); + restartBlink(); + } + return handled; + } + var lastStoppedKey = null; + + function onKeyDown(e) { + if (!focused) onFocus(); + if (ie && e.keyCode == 27) { + e.returnValue = false; + } + if (pollingFast) { + if (readInput()) pollingFast = false; + } + if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return; + var code = e_prop(e, "keyCode"); + setShift(code == 16 || e_prop(e, "shiftKey")); + var handled = handleKeyBinding(e); + if (opera) { + lastStoppedKey = handled ? code : null; + if (!handled && code == 88 && e_prop(e, mac ? "metaKey" : "ctrlKey")) + replaceSelection(""); + } + } + + function onKeyPress(e) { + if (pollingFast) readInput(); + if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return; + var keyCode = e_prop(e, "keyCode"), + charCode = e_prop(e, "charCode"); + if (opera && keyCode == lastStoppedKey) { + lastStoppedKey = null; + e_preventDefault(e); + return; + } + if (((opera && (!e.which || e.which < 10)) || khtml) && handleKeyBinding(e)) return; + var ch = String.fromCharCode(charCode == null ? keyCode : charCode); + if (options.electricChars && mode.electricChars && options.smartIndent && !options.readOnly) { + if (mode.electricChars.indexOf(ch) > -1) + setTimeout(operation(function() { + indentLine(sel.to.line, "smart"); + }), 75); + } + if (handleCharBinding(e, ch)) return; + fastPoll(); + } + + function onKeyUp(e) { + if (options.onKeyEvent && options.onKeyEvent(instance, addStop(e))) return; + if (e_prop(e, "keyCode") == 16) shiftSelecting = null; + + if(__events['change']){ + __events['change'].forEach(function(fn){ + fn(instance, getValue()) + }) + } + } + + function onFocus() { + if (options.readOnly == "nocursor") return; + if (!focused) { + if (options.onFocus) options.onFocus(instance); + focused = true; + if (scroller.className.search(/\bCodeMirror-focused\b/) == -1) + scroller.className += " CodeMirror-focused"; + } + slowPoll(); + restartBlink(); + if(__events['focus']){ + __events['focus'].forEach(function(fn){ + fn(instance, getValue()) + }) + } + } + + function onBlur() { + if (focused) { + if (options.onBlur) options.onBlur(instance); + focused = false; + if (bracketHighlighted) + operation(function() { + if (bracketHighlighted) { + bracketHighlighted(); + bracketHighlighted = null; + } + })(); + scroller.className = scroller.className.replace(" CodeMirror-focused", ""); + } + clearInterval(blinker); + setTimeout(function() { + if (!focused) shiftSelecting = null; + }, 150); + } + + function updateLines(from, to, newText, selFrom, selTo) { + if (suppressEdits) return; + var old = []; + doc.iter(from.line, to.line + 1, function(line) { + old.push(newHL(line.text, line.markedSpans)); + }); + if (history) { + history.addChange(from.line, newText.length, old); + while (history.done.length > options.undoDepth) history.done.shift(); + } + var lines = updateMarkedSpans(hlSpans(old[0]), hlSpans(lst(old)), from.ch, to.ch, newText); + updateLinesNoUndo(from, to, lines, selFrom, selTo); + } + + function unredoHelper(from, to) { + if (!from.length) return; + var set = from.pop(), + out = []; + for (var i = set.length - 1; i >= 0; i -= 1) { + var change = set[i]; + var replaced = [], + end = change.start + change.added; + doc.iter(change.start, end, function(line) { + replaced.push(newHL(line.text, line.markedSpans)); + }); + out.push({ + start: change.start, + added: change.old.length, + old: replaced + }); + var pos = { + line: change.start + change.old.length - 1, + ch: editEnd(hlText(lst(replaced)), hlText(lst(change.old))) + }; + updateLinesNoUndo({ + line: change.start, + ch: 0 + }, { + line: end - 1, + ch: getLine(end - 1).text.length + }, change.old, pos, pos); + } + updateInput = true; + to.push(out); + } + + function undo() { + unredoHelper(history.done, history.undone); + } + + function redo() { + unredoHelper(history.undone, history.done); + } + + function updateLinesNoUndo(from, to, lines, selFrom, selTo) { + if (suppressEdits) return; + var recomputeMaxLength = false, + maxLineLength = maxLine.text.length; + if (!options.lineWrapping) + doc.iter(from.line, to.line + 1, function(line) { + if (!line.hidden && line.text.length == maxLineLength) { + recomputeMaxLength = true; + return true; + } + }); + if (from.line != to.line || lines.length > 1) gutterDirty = true; + var nlines = to.line - from.line, + firstLine = getLine(from.line), + lastLine = getLine(to.line); + var lastHL = lst(lines); + if (from.ch == 0 && to.ch == 0 && hlText(lastHL) == "") { + var added = [], + prevLine = null; + for (var i = 0, e = lines.length - 1; i < e; ++i) + added.push(new Line(hlText(lines[i]), hlSpans(lines[i]))); + lastLine.update(lastLine.text, hlSpans(lastHL)); + if (nlines) doc.remove(from.line, nlines, callbacks); + if (added.length) doc.insert(from.line, added); + } else if (firstLine == lastLine) { + if (lines.length == 1) { + firstLine.update(firstLine.text.slice(0, from.ch) + hlText(lines[0]) + firstLine.text.slice(to.ch), hlSpans(lines[0])); + } else { + for (var added = [], i = 1, e = lines.length - 1; i < e; ++i) + added.push(new Line(hlText(lines[i]), hlSpans(lines[i]))); + added.push(new Line(hlText(lastHL) + firstLine.text.slice(to.ch), hlSpans(lastHL))); + firstLine.update(firstLine.text.slice(0, from.ch) + hlText(lines[0]), hlSpans(lines[0])); + doc.insert(from.line + 1, added); + } + } else if (lines.length == 1) { + firstLine.update(firstLine.text.slice(0, from.ch) + hlText(lines[0]) + lastLine.text.slice(to.ch), hlSpans(lines[0])); + doc.remove(from.line + 1, nlines, callbacks); + } else { + var added = []; + firstLine.update(firstLine.text.slice(0, from.ch) + hlText(lines[0]), hlSpans(lines[0])); + lastLine.update(hlText(lastHL) + lastLine.text.slice(to.ch), hlSpans(lastHL)); + for (var i = 1, e = lines.length - 1; i < e; ++i) + added.push(new Line(hlText(lines[i]), hlSpans(lines[i]))); + if (nlines > 1) doc.remove(from.line + 1, nlines - 1, callbacks); + doc.insert(from.line + 1, added); + } + if (options.lineWrapping) { + var perLine = Math.max(5, scroller.clientWidth / charWidth() - 3); + doc.iter(from.line, from.line + lines.length, function(line) { + if (line.hidden) return; + var guess = Math.ceil(line.text.length / perLine) || 1; + if (guess != line.height) updateLineHeight(line, guess); + }); + } else { + doc.iter(from.line, from.line + lines.length, function(line) { + var l = line.text; + if (!line.hidden && l.length > maxLineLength) { + maxLine = line; + maxLineLength = l.length; + maxLineChanged = true; + recomputeMaxLength = false; + } + }); + if (recomputeMaxLength) updateMaxLine = true; + } + frontier = Math.min(frontier, from.line); + startWorker(400); + var lendiff = lines.length - nlines - 1; + changes.push({ + from: from.line, + to: to.line + 1, + diff: lendiff + }); + if (options.onChange) { + for (var i = 0; i < lines.length; ++i) + if (typeof lines[i] != "string") lines[i] = lines[i].text; + var changeObj = { + from: from, + to: to, + text: lines + }; + if (textChanged) { + for (var cur = textChanged; cur.next; cur = cur.next) {} + cur.next = changeObj; + } else textChanged = changeObj; + } + + function updateLine(n) { + return n <= Math.min(to.line, to.line + lendiff) ? n : n + lendiff; + } + setSelection(clipPos(selFrom), clipPos(selTo), updateLine(sel.from.line), updateLine(sel.to.line)); + } + + function needsScrollbar() { + var realHeight = doc.height * textHeight() + 2 * paddingTop(); + return realHeight * .99 > scroller.offsetHeight ? realHeight : false; + } + + function updateVerticalScroll(scrollTop) { + var scrollHeight = needsScrollbar(); + scrollbar.style.display = scrollHeight ? "block" : "none"; + if (scrollHeight) { + scrollbarInner.style.height = sizer.style.minHeight = scrollHeight + "px"; + scrollbar.style.height = scroller.clientHeight + "px"; + if (scrollTop != null) { + scrollbar.scrollTop = scroller.scrollTop = scrollTop; + if (webkit) setTimeout(function() { + if (scrollbar.scrollTop != scrollTop) return; + scrollbar.scrollTop = scrollTop + (scrollTop ? -1 : 1); + scrollbar.scrollTop = scrollTop; + }, 0); + } + } else { + sizer.style.minHeight = ""; + } + mover.style.top = displayOffset * textHeight() + "px"; + } + + function computeMaxLength() { + maxLine = getLine(0); + maxLineChanged = true; + var maxLineLength = maxLine.text.length; + doc.iter(1, doc.size, function(line) { + var l = line.text; + if (!line.hidden && l.length > maxLineLength) { + maxLineLength = l.length; + maxLine = line; + } + }); + updateMaxLine = false; + } + + function replaceRange(code, from, to) { + from = clipPos(from); + if (!to) to = from; + else to = clipPos(to); + code = splitLines(code); + + function adjustPos(pos) { + if (posLess(pos, from)) return pos; + if (!posLess(to, pos)) return end; + var line = pos.line + code.length - (to.line - from.line) - 1; + var ch = pos.ch; + if (pos.line == to.line) + ch += lst(code).length - (to.ch - (to.line == from.line ? from.ch : 0)); + return { + line: line, + ch: ch + }; + } + var end; + replaceRange1(code, from, to, function(end1) { + end = end1; + return { + from: adjustPos(sel.from), + to: adjustPos(sel.to) + }; + }); + return end; + } + + function replaceSelection(code, collapse) { + replaceRange1(splitLines(code), sel.from, sel.to, function(end) { + if (collapse == "end") return { + from: end, + to: end + }; + else if (collapse == "start") return { + from: sel.from, + to: sel.from + }; + else return { + from: sel.from, + to: end + }; + }); + } + + function replaceRange1(code, from, to, computeSel) { + var endch = code.length == 1 ? code[0].length + from.ch : lst(code).length; + var newSel = computeSel({ + line: from.line + code.length - 1, + ch: endch + }); + updateLines(from, to, code, newSel.from, newSel.to); + } + + function getRange(from, to, lineSep) { + var l1 = from.line, + l2 = to.line; + if (l1 == l2) return getLine(l1).text.slice(from.ch, to.ch); + var code = [getLine(l1).text.slice(from.ch)]; + doc.iter(l1 + 1, l2, function(line) { + code.push(line.text); + }); + code.push(getLine(l2).text.slice(0, to.ch)); + return code.join(lineSep || "\n"); + } + + function getSelection(lineSep) { + return getRange(sel.from, sel.to, lineSep); + } + + function slowPoll() { + if (pollingFast) return; + poll.set(options.pollInterval, function() { + readInput(); + if (focused) slowPoll(); + }); + } + + function fastPoll() { + var missed = false; + pollingFast = true; + + function p() { + var changed = readInput(); + if (!changed && !missed) { + missed = true; + poll.set(60, p); + } else { + pollingFast = false; + slowPoll(); + } + } + poll.set(20, p); + } + var prevInput = ""; + + function readInput() { + if (!focused || hasSelection(input) || options.readOnly) return false; + var text = input.value; + if (text == prevInput) return false; + if (!nestedOperation) startOperation(); + shiftSelecting = null; + var same = 0, + l = Math.min(prevInput.length, text.length); + while (same < l && prevInput[same] == text[same]) ++same; + if (same < prevInput.length) + sel.from = { + line: sel.from.line, + ch: sel.from.ch - (prevInput.length - same) + }; + else if (overwrite && posEq(sel.from, sel.to) && !pasteIncoming) + sel.to = { + line: sel.to.line, + ch: Math.min(getLine(sel.to.line).text.length, sel.to.ch + (text.length - same)) + }; + replaceSelection(text.slice(same), "end"); + if (text.length > 1000) { + input.value = prevInput = ""; + } else prevInput = text; + if (!nestedOperation) endOperation(); + pasteIncoming = false; + return true; + } + + function resetInput(user) { + if (!posEq(sel.from, sel.to)) { + prevInput = ""; + input.value = getSelection(); + if (focused) selectInput(input); + } else if (user) prevInput = input.value = ""; + } + + function focusInput() { + if (options.readOnly != "nocursor") input.focus(); + } + + function scrollCursorIntoView() { + var coords = calculateCursorCoords(); + scrollIntoView(coords.x, coords.y, coords.x, coords.yBot); + if (!focused) return; + var box = sizer.getBoundingClientRect(), + doScroll = null; + if (coords.y + box.top < 0) doScroll = true; + else if (coords.y + box.top + textHeight() > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false; + if (doScroll != null) { + var hidden = cursor.style.display == "none"; + if (hidden) { + cursor.style.display = ""; + cursor.style.left = coords.x + "px"; + cursor.style.top = (coords.y - displayOffset) + "px"; + } + cursor.scrollIntoView(doScroll); + if (hidden) cursor.style.display = "none"; + } + } + + function calculateCursorCoords() { + var cursor = localCoords(sel.inverted ? sel.from : sel.to); + var x = options.lineWrapping ? Math.min(cursor.x, lineSpace.offsetWidth) : cursor.x; + return { + x: x, + y: cursor.y, + yBot: cursor.yBot + }; + } + + function scrollIntoView(x1, y1, x2, y2) { + var scrollPos = calculateScrollPos(x1, y1, x2, y2); + if (scrollPos.scrollLeft != null) { + scroller.scrollLeft = scrollPos.scrollLeft; + } + if (scrollPos.scrollTop != null) { + scrollbar.scrollTop = scroller.scrollTop = scrollPos.scrollTop; + } + } + + function calculateScrollPos(x1, y1, x2, y2) { + var pl = paddingLeft(), + pt = paddingTop(); + y1 += pt; + y2 += pt; + x1 += pl; + x2 += pl; + var screen = scroller.clientHeight, + screentop = scrollbar.scrollTop, + result = {}; + var docBottom = needsScrollbar() || Infinity; + var atTop = y1 < pt + 10, + atBottom = y2 + pt > docBottom - 10; + if (y1 < screentop) result.scrollTop = atTop ? 0 : Math.max(0, y1); + else if (y2 > screentop + screen) result.scrollTop = (atBottom ? docBottom : y2) - screen; + var screenw = scroller.clientWidth, + screenleft = scroller.scrollLeft; + var gutterw = options.fixedGutter ? gutter.clientWidth : 0; + var atLeft = x1 < gutterw + pl + 10; + if (x1 < screenleft + gutterw || atLeft) { + if (atLeft) x1 = 0; + result.scrollLeft = Math.max(0, x1 - 10 - gutterw); + } else if (x2 > screenw + screenleft - 3) { + result.scrollLeft = x2 + 10 - screenw; + } + return result; + } + + function visibleLines(scrollTop) { + var lh = textHeight(), + top = (scrollTop != null ? scrollTop : scrollbar.scrollTop) - paddingTop(); + var fromHeight = Math.max(0, Math.floor(top / lh)); + var toHeight = Math.ceil((top + scroller.clientHeight) / lh); + return { + from: lineAtHeight(doc, fromHeight), + to: lineAtHeight(doc, toHeight) + }; + } + + function updateDisplay(changes, suppressCallback, scrollTop) { + if (!scroller.clientWidth) { + showingFrom = showingTo = displayOffset = 0; + return; + } + var visible = visibleLines(scrollTop); + if (changes !== true && changes.length == 0 && visible.from > showingFrom && visible.to < showingTo) { + updateVerticalScroll(scrollTop); + return; + } + var from = Math.max(visible.from - 100, 0), + to = Math.min(doc.size, visible.to + 100); + if (showingFrom < from && from - showingFrom < 20) from = showingFrom; + if (showingTo > to && showingTo - to < 20) to = Math.min(doc.size, showingTo); + var intact = changes === true ? [] : computeIntact([{ + from: showingFrom, + to: showingTo, + domStart: 0 + }], changes); + var intactLines = 0; + for (var i = 0; i < intact.length; ++i) { + var range = intact[i]; + if (range.from < from) { + range.domStart += (from - range.from); + range.from = from; + } + if (range.to > to) range.to = to; + if (range.from >= range.to) intact.splice(i--, 1); + else intactLines += range.to - range.from; + } + if (intactLines == to - from && from == showingFrom && to == showingTo) { + updateVerticalScroll(scrollTop); + return; + } + intact.sort(function(a, b) { + return a.domStart - b.domStart; + }); + var th = textHeight(), + gutterDisplay = gutter.style.display; + lineDiv.style.display = "none"; + patchDisplay(from, to, intact); + lineDiv.style.display = gutter.style.display = ""; + var different = from != showingFrom || to != showingTo || lastSizeC != scroller.clientHeight + th; + if (different) lastSizeC = scroller.clientHeight + th; + if (from != showingFrom || to != showingTo && options.onViewportChange) + setTimeout(function() { + if (options.onViewportChange) options.onViewportChange(instance, from, to); + }); + showingFrom = from; + showingTo = to; + displayOffset = heightAtLine(doc, from); + startWorker(100); + if (lineDiv.childNodes.length != showingTo - showingFrom) + throw new Error("BAD PATCH! " + JSON.stringify(intact) + " size=" + (showingTo - showingFrom) + " nodes=" + lineDiv.childNodes.length); + + function checkHeights() { + var curNode = lineDiv.firstChild, + heightChanged = false; + doc.iter(showingFrom, showingTo, function(line) { + if (!curNode) return; + if (!line.hidden) { + var height = Math.round(curNode.offsetHeight / th) || 1; + if (line.height != height) { + updateLineHeight(line, height); + gutterDirty = heightChanged = true; + } + } + curNode = curNode.nextSibling; + }); + return heightChanged; + } + if (options.lineWrapping) checkHeights(); + gutter.style.display = gutterDisplay; + if (different || gutterDirty) { + updateGutter() && options.lineWrapping && checkHeights() && updateGutter(); + } + updateVerticalScroll(scrollTop); + updateSelection(); + if (!suppressCallback && options.onUpdate) options.onUpdate(instance); + return true; + } + + function computeIntact(intact, changes) { + for (var i = 0, l = changes.length || 0; i < l; ++i) { + var change = changes[i], + intact2 = [], + diff = change.diff || 0; + for (var j = 0, l2 = intact.length; j < l2; ++j) { + var range = intact[j]; + if (change.to <= range.from && change.diff) + intact2.push({ + from: range.from + diff, + to: range.to + diff, + domStart: range.domStart + }); + else if (change.to <= range.from || change.from >= range.to) + intact2.push(range); + else { + if (change.from > range.from) + intact2.push({ + from: range.from, + to: change.from, + domStart: range.domStart + }); + if (change.to < range.to) + intact2.push({ + from: change.to + diff, + to: range.to + diff, + domStart: range.domStart + (change.to - range.from) + }); + } + } + intact = intact2; + } + return intact; + } + + function patchDisplay(from, to, intact) { + function killNode(node) { + var tmp = node.nextSibling; + node.parentNode.removeChild(node); + return tmp; + } + if (!intact.length) removeChildren(lineDiv); + else { + var domPos = 0, + curNode = lineDiv.firstChild, + n; + for (var i = 0; i < intact.length; ++i) { + var cur = intact[i]; + while (cur.domStart > domPos) { + curNode = killNode(curNode); + domPos++; + } + for (var j = 0, e = cur.to - cur.from; j < e; ++j) { + curNode = curNode.nextSibling; + domPos++; + } + } + while (curNode) curNode = killNode(curNode); + } + var nextIntact = intact.shift(), + curNode = lineDiv.firstChild, + j = from; + doc.iter(from, to, function(line) { + if (nextIntact && nextIntact.to == j) nextIntact = intact.shift(); + if (!nextIntact || nextIntact.from > j) { + if (line.hidden) var lineElement = elt("pre"); + else { + var lineElement = lineContent(line); + if (line.className) lineElement.className = line.className; + if (line.bgClassName) { + var pre = elt("pre", "\u00a0", line.bgClassName, "position: absolute; left: 0; right: 0; top: 0; bottom: 0; z-index: -2"); + lineElement = elt("div", [pre, lineElement], null, "position: relative"); + } + } + lineDiv.insertBefore(lineElement, curNode); + } else { + curNode = curNode.nextSibling; + } + ++j; + }); + } + + function updateGutter() { + if (!options.gutter && !options.lineNumbers) return; + var hText = mover.offsetHeight, + hEditor = scroller.clientHeight; + gutter.style.height = (hText - hEditor < 2 ? hEditor : hText) + "px"; + var fragment = document.createDocumentFragment(), + i = showingFrom, + normalNode; + doc.iter(showingFrom, Math.max(showingTo, showingFrom + 1), function(line) { + if (line.hidden) { + fragment.appendChild(elt("pre")); + } else { + var marker = line.gutterMarker; + var text = options.lineNumbers ? options.lineNumberFormatter(i + options.firstLineNumber) : null; + if (marker && marker.text) + text = marker.text.replace("%N%", text != null ? text : ""); + else if (text == null) + text = "\u00a0"; + var markerElement = fragment.appendChild(elt("pre", null, marker && marker.style)); + markerElement.innerHTML = text; + for (var j = 1; j < line.height; ++j) { + markerElement.appendChild(elt("br")); + markerElement.appendChild(document.createTextNode("\u00a0")); + } + if (!marker) normalNode = i; + } + ++i; + }); + gutter.style.display = "none"; + removeChildrenAndAdd(gutterText, fragment); + if (normalNode != null && options.lineNumbers) { + var node = gutterText.childNodes[normalNode - showingFrom]; + var minwidth = String(doc.size).length, + val = eltText(node.firstChild), + pad = ""; + while (val.length + pad.length < minwidth) pad += "\u00a0"; + if (pad) node.insertBefore(document.createTextNode(pad), node.firstChild); + } + gutter.style.display = ""; + var resized = Math.abs((parseInt(lineSpace.style.marginLeft) || 0) - gutter.offsetWidth) > 2; + lineSpace.style.marginLeft = gutter.offsetWidth + "px"; + gutterDirty = false; + return resized; + } + + function updateSelection() { + var collapsed = posEq(sel.from, sel.to); + var fromPos = localCoords(sel.from, true); + var toPos = collapsed ? fromPos : localCoords(sel.to, true); + var headPos = sel.inverted ? fromPos : toPos, + th = textHeight(); + var wrapOff = eltOffset(wrapper), + lineOff = eltOffset(lineDiv); + inputDiv.style.top = Math.max(0, Math.min(scroller.offsetHeight, headPos.y + lineOff.top - wrapOff.top)) + "px"; + inputDiv.style.left = Math.max(0, Math.min(scroller.offsetWidth, headPos.x + lineOff.left - wrapOff.left)) + "px"; + if (collapsed) { + cursor.style.top = headPos.y + "px"; + cursor.style.left = (options.lineWrapping ? Math.min(headPos.x, lineSpace.offsetWidth) : headPos.x) + "px"; + cursor.style.display = ""; + selectionDiv.style.display = "none"; + } else { + var sameLine = fromPos.y == toPos.y, + fragment = document.createDocumentFragment(); + var clientWidth = lineSpace.clientWidth || lineSpace.offsetWidth; + var clientHeight = lineSpace.clientHeight || lineSpace.offsetHeight; + var add = function(left, top, right, height) { + var rstyle = quirksMode ? "width: " + (!right ? clientWidth : clientWidth - right - left) + "px" : "right: " + right + "px"; + fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + "px; top: " + top + "px; " + rstyle + "; height: " + height + "px")); + }; + if (sel.from.ch && fromPos.y >= 0) { + var right = sameLine ? clientWidth - toPos.x : 0; + add(fromPos.x, fromPos.y, right, th); + } + var middleStart = Math.max(0, fromPos.y + (sel.from.ch ? th : 0)); + var middleHeight = Math.min(toPos.y, clientHeight) - middleStart; + if (middleHeight > 0.2 * th) + add(0, middleStart, 0, middleHeight); + if ((!sameLine || !sel.from.ch) && toPos.y < clientHeight - .5 * th) + add(0, toPos.y, clientWidth - toPos.x, th); + removeChildrenAndAdd(selectionDiv, fragment); + cursor.style.display = "none"; + selectionDiv.style.display = ""; + } + } + + function setShift(val) { + if (val) shiftSelecting = shiftSelecting || (sel.inverted ? sel.to : sel.from); + else shiftSelecting = null; + } + + function setSelectionUser(from, to) { + var sh = shiftSelecting && clipPos(shiftSelecting); + if (sh) { + if (posLess(sh, from)) from = sh; + else if (posLess(to, sh)) to = sh; + } + setSelection(from, to); + userSelChange = true; + } + + function setSelection(from, to, oldFrom, oldTo) { + goalColumn = null; + if (oldFrom == null) { + oldFrom = sel.from.line; + oldTo = sel.to.line; + } + if (posEq(sel.from, from) && posEq(sel.to, to)) return; + if (posLess(to, from)) { + var tmp = to; + to = from; + from = tmp; + } + if (from.line != oldFrom) { + var from1 = skipHidden(from, oldFrom, sel.from.ch); + if (!from1) setLineHidden(from.line, false); + else from = from1; + } + if (to.line != oldTo) to = skipHidden(to, oldTo, sel.to.ch); + if (posEq(from, to)) sel.inverted = false; + else if (posEq(from, sel.to)) sel.inverted = false; + else if (posEq(to, sel.from)) sel.inverted = true; + if (options.autoClearEmptyLines && posEq(sel.from, sel.to)) { + var head = sel.inverted ? from : to; + if (head.line != sel.from.line && sel.from.line < doc.size) { + var oldLine = getLine(sel.from.line); + if (/^\s+$/.test(oldLine.text)) + setTimeout(operation(function() { + if (oldLine.parent && /^\s+$/.test(oldLine.text)) { + var no = lineNo(oldLine); + replaceRange("", { + line: no, + ch: 0 + }, { + line: no, + ch: oldLine.text.length + }); + } + }, 10)); + } + } + sel.from = from; + sel.to = to; + selectionChanged = true; + } + + function skipHidden(pos, oldLine, oldCh) { + function getNonHidden(dir) { + var lNo = pos.line + dir, + end = dir == 1 ? doc.size : -1; + while (lNo != end) { + var line = getLine(lNo); + if (!line.hidden) { + var ch = pos.ch; + if (toEnd || ch > oldCh || ch > line.text.length) ch = line.text.length; + return { + line: lNo, + ch: ch + }; + } + lNo += dir; + } + } + var line = getLine(pos.line); + var toEnd = pos.ch == line.text.length && pos.ch != oldCh; + if (!line.hidden) return pos; + if (pos.line >= oldLine) return getNonHidden(1) || getNonHidden(-1); + else return getNonHidden(-1) || getNonHidden(1); + } + + function setCursor(line, ch, user) { + var pos = clipPos({ + line: line, + ch: ch || 0 + }); + (user ? setSelectionUser : setSelection)(pos, pos); + } + + function clipLine(n) { + return Math.max(0, Math.min(n, doc.size - 1)); + } + + function clipPos(pos) { + if (pos.line < 0) return { + line: 0, + ch: 0 + }; + if (pos.line >= doc.size) return { + line: doc.size - 1, + ch: getLine(doc.size - 1).text.length + }; + var ch = pos.ch, + linelen = getLine(pos.line).text.length; + if (ch == null || ch > linelen) return { + line: pos.line, + ch: linelen + }; + else if (ch < 0) return { + line: pos.line, + ch: 0 + }; + else return pos; + } + + function findPosH(dir, unit) { + var end = sel.inverted ? sel.from : sel.to, + line = end.line, + ch = end.ch; + var lineObj = getLine(line); + + function findNextLine() { + for (var l = line + dir, e = dir < 0 ? -1 : doc.size; l != e; l += dir) { + var lo = getLine(l); + if (!lo.hidden) { + line = l; + lineObj = lo; + return true; + } + } + } + + function moveOnce(boundToLine) { + if (ch == (dir < 0 ? 0 : lineObj.text.length)) { + if (!boundToLine && findNextLine()) ch = dir < 0 ? lineObj.text.length : 0; + else return false; + } else ch += dir; + return true; + } + if (unit == "char") moveOnce(); + else if (unit == "column") moveOnce(true); + else if (unit == "word") { + var sawWord = false; + for (;;) { + if (dir < 0) + if (!moveOnce()) break; + if (isWordChar(lineObj.text.charAt(ch))) sawWord = true; + else if (sawWord) { + if (dir < 0) { + dir = 1; + moveOnce(); + } + break; + } + if (dir > 0) + if (!moveOnce()) break; + } + } + return { + line: line, + ch: ch + }; + } + + function moveH(dir, unit) { + var pos = dir < 0 ? sel.from : sel.to; + if (shiftSelecting || posEq(sel.from, sel.to)) pos = findPosH(dir, unit); + setCursor(pos.line, pos.ch, true); + } + + function deleteH(dir, unit) { + if (!posEq(sel.from, sel.to)) replaceRange("", sel.from, sel.to); + else if (dir < 0) replaceRange("", findPosH(dir, unit), sel.to); + else replaceRange("", sel.from, findPosH(dir, unit)); + userSelChange = true; + } + + function moveV(dir, unit) { + var dist = 0, + pos = localCoords(sel.inverted ? sel.from : sel.to, true); + if (goalColumn != null) pos.x = goalColumn; + if (unit == "page") { + var screen = Math.min(scroller.clientHeight, window.innerHeight || document.documentElement.clientHeight); + var target = coordsChar(pos.x, pos.y + screen * dir); + } else if (unit == "line") { + var th = textHeight(); + var target = coordsChar(pos.x, pos.y + .5 * th + dir * th); + } + if (unit == "page") scrollbar.scrollTop += localCoords(target, true).y - pos.y; + setCursor(target.line, target.ch, true); + goalColumn = pos.x; + } + + function findWordAt(pos) { + var line = getLine(pos.line).text; + var start = pos.ch, + end = pos.ch; + if (line) { + if (pos.after === false || end == line.length) --start; + else ++end; + var startChar = line.charAt(start); + var check = isWordChar(startChar) ? isWordChar : /\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 { + from: { + line: pos.line, + ch: start + }, + to: { + line: pos.line, + ch: end + } + }; + } + + function selectLine(line) { + setSelectionUser({ + line: line, + ch: 0 + }, clipPos({ + line: line + 1, + ch: 0 + })); + } + + function indentSelected(mode) { + if (posEq(sel.from, sel.to)) return indentLine(sel.from.line, mode); + var e = sel.to.line - (sel.to.ch ? 0 : 1); + for (var i = sel.from.line; i <= e; ++i) indentLine(i, mode); + } + + function indentLine(n, how) { + if (!how) how = "add"; + if (how == "smart") { + if (!mode.indent) how = "prev"; + else var state = getStateBefore(n); + } + var line = getLine(n), + curSpace = line.indentation(options.tabSize), + curSpaceString = line.text.match(/^\s*/)[0], + indentation; + if (how == "smart") { + indentation = mode.indent(state, line.text.slice(curSpaceString.length), line.text); + if (indentation == Pass) how = "prev"; + } + if (how == "prev") { + if (n) indentation = getLine(n - 1).indentation(options.tabSize); + else indentation = 0; + } else if (how == "add") indentation = curSpace + options.indentUnit; + else if (how == "subtract") indentation = curSpace - options.indentUnit; + indentation = Math.max(0, indentation); + var diff = indentation - curSpace; + var indentString = "", + pos = 0; + if (options.indentWithTabs) + for (var i = Math.floor(indentation / options.tabSize); i; --i) { + pos += options.tabSize; + indentString += "\t"; + } + if (pos < indentation) indentString += spaceStr(indentation - pos); + if (indentString != curSpaceString) + replaceRange(indentString, { + line: n, + ch: 0 + }, { + line: n, + ch: curSpaceString.length + }); + line.stateAfter = null; + } + + function loadMode() { + mode = CodeMirror.getMode(options, options.mode); + doc.iter(0, doc.size, function(line) { + line.stateAfter = null; + }); + frontier = 0; + startWorker(100); + } + + function gutterChanged() { + var visible = options.gutter || options.lineNumbers; + gutter.style.display = visible ? "" : "none"; + if (visible) gutterDirty = true; + else lineDiv.parentNode.style.marginLeft = 0; + } + + function wrappingChanged(from, to) { + if (options.lineWrapping) { + wrapper.className += " CodeMirror-wrap"; + var perLine = scroller.clientWidth / charWidth() - 3; + doc.iter(0, doc.size, function(line) { + if (line.hidden) return; + var guess = Math.ceil(line.text.length / perLine) || 1; + if (guess != 1) updateLineHeight(line, guess); + }); + lineSpace.style.minWidth = widthForcer.style.left = ""; + } else { + wrapper.className = wrapper.className.replace(" CodeMirror-wrap", ""); + computeMaxLength(); + doc.iter(0, doc.size, function(line) { + if (line.height != 1 && !line.hidden) updateLineHeight(line, 1); + }); + } + changes.push({ + from: 0, + to: doc.size + }); + } + + function themeChanged() { + scroller.className = scroller.className.replace(/\s*cm-s-\S+/g, "") + + options.theme.replace(/(^|\s)\s*/g, " cm-s-"); + } + + function keyMapChanged() { + var style = keyMap[options.keyMap].style; + wrapper.className = wrapper.className.replace(/\s*cm-keymap-\S+/g, "") + + (style ? " cm-keymap-" + style : ""); + } + + function TextMarker(type, style) { + this.lines = []; + this.type = type; + if (style) this.style = style; + } + TextMarker.prototype.clear = operation(function() { + var min, max; + for (var i = 0; i < this.lines.length; ++i) { + var line = this.lines[i]; + var span = getMarkedSpanFor(line.markedSpans, this); + if (span.from != null) min = lineNo(line); + if (span.to != null) max = lineNo(line); + line.markedSpans = removeMarkedSpan(line.markedSpans, span); + } + if (min != null) changes.push({ + from: min, + to: max + 1 + }); + this.lines.length = 0; + this.explicitlyCleared = true; + }); + TextMarker.prototype.find = function() { + 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 || span.to != null) { + var found = lineNo(line); + if (span.from != null) from = { + line: found, + ch: span.from + }; + if (span.to != null) to = { + line: found, + ch: span.to + }; + } + } + if (this.type == "bookmark") return from; + return from && { + from: from, + to: to + }; + }; + + function markText(from, to, className, options) { + from = clipPos(from); + to = clipPos(to); + var marker = new TextMarker("range", className); + if (options) + for (var opt in options) + if (options.hasOwnProperty(opt)) + marker[opt] = options[opt]; + var curLine = from.line; + doc.iter(curLine, to.line + 1, function(line) { + var span = { + from: curLine == from.line ? from.ch : null, + to: curLine == to.line ? to.ch : null, + marker: marker + }; + line.markedSpans = (line.markedSpans || []).concat([span]); + marker.lines.push(line); + ++curLine; + }); + changes.push({ + from: from.line, + to: to.line + 1 + }); + return marker; + } + + function setBookmark(pos) { + pos = clipPos(pos); + var marker = new TextMarker("bookmark"), + line = getLine(pos.line); + history.addChange(pos.line, 1, [newHL(line.text, line.markedSpans)], true); + var span = { + from: pos.ch, + to: pos.ch, + marker: marker + }; + line.markedSpans = (line.markedSpans || []).concat([span]); + marker.lines.push(line); + return marker; + } + + function findMarksAt(pos) { + pos = clipPos(pos); + var markers = [], + spans = getLine(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); + } + return markers; + } + + function addGutterMarker(line, text, className) { + if (typeof line == "number") line = getLine(clipLine(line)); + line.gutterMarker = { + text: text, + style: className + }; + gutterDirty = true; + return line; + } + + function removeGutterMarker(line) { + if (typeof line == "number") line = getLine(clipLine(line)); + line.gutterMarker = null; + gutterDirty = true; + } + + function changeLine(handle, op) { + var no = handle, + line = handle; + if (typeof handle == "number") line = getLine(clipLine(handle)); + else no = lineNo(handle); + if (no == null) return null; + if (op(line, no)) changes.push({ + from: no, + to: no + 1 + }); + else return null; + return line; + } + + function setLineClass(handle, className, bgClassName) { + return changeLine(handle, function(line) { + if (line.className != className || line.bgClassName != bgClassName) { + line.className = className; + line.bgClassName = bgClassName; + return true; + } + }); + } + + function setLineHidden(handle, hidden) { + return changeLine(handle, function(line, no) { + if (line.hidden != hidden) { + line.hidden = hidden; + if (!options.lineWrapping) { + if (hidden && line.text.length == maxLine.text.length) { + updateMaxLine = true; + } else if (!hidden && line.text.length > maxLine.text.length) { + maxLine = line; + updateMaxLine = false; + } + } + updateLineHeight(line, hidden ? 0 : 1); + var fline = sel.from.line, + tline = sel.to.line; + if (hidden && (fline == no || tline == no)) { + var from = fline == no ? skipHidden({ + line: fline, + ch: 0 + }, fline, 0) : sel.from; + var to = tline == no ? skipHidden({ + line: tline, + ch: 0 + }, tline, 0) : sel.to; + if (!to) return; + setSelection(from, to); + } + return (gutterDirty = true); + } + }); + } + + function lineInfo(line) { + if (typeof line == "number") { + if (!isLine(line)) return null; + var n = line; + line = getLine(line); + if (!line) return null; + } else { + var n = lineNo(line); + if (n == null) return null; + } + var marker = line.gutterMarker; + return { + line: n, + handle: line, + text: line.text, + markerText: marker && marker.text, + markerClass: marker && marker.style, + lineClass: line.className, + bgClass: line.bgClassName + }; + } + + function measureLine(line, ch) { + if (ch == 0) return { + top: 0, + left: 0 + }; + var pre = lineContent(line, ch); + removeChildrenAndAdd(measure, pre); + var anchor = pre.anchor; + var top = anchor.offsetTop, + left = anchor.offsetLeft; + if (ie && top == 0 && left == 0) { + var backup = elt("span", "x"); + anchor.parentNode.insertBefore(backup, anchor.nextSibling); + top = backup.offsetTop; + } + return { + top: top, + left: left + }; + } + + function localCoords(pos, inLineWrap) { + var x, lh = textHeight(), + y = lh * (heightAtLine(doc, pos.line) - (inLineWrap ? displayOffset : 0)); + if (pos.ch == 0) x = 0; + else { + var sp = measureLine(getLine(pos.line), pos.ch); + x = sp.left; + if (options.lineWrapping) y += Math.max(0, sp.top); + } + return { + x: x, + y: y, + yBot: y + lh + }; + } + + function coordsChar(x, y) { + var th = textHeight(), + cw = charWidth(), + heightPos = displayOffset + Math.floor(y / th); + if (heightPos < 0) return { + line: 0, + ch: 0 + }; + var lineNo = lineAtHeight(doc, heightPos); + if (lineNo >= doc.size) return { + line: doc.size - 1, + ch: getLine(doc.size - 1).text.length + }; + var lineObj = getLine(lineNo), + text = lineObj.text; + var tw = options.lineWrapping, + innerOff = tw ? heightPos - heightAtLine(doc, lineNo) : 0; + if (x <= 0 && innerOff == 0) return { + line: lineNo, + ch: 0 + }; + var wrongLine = false; + + function getX(len) { + var sp = measureLine(lineObj, len); + if (tw) { + var off = Math.round(sp.top / th); + wrongLine = off != innerOff; + return Math.max(0, sp.left + (off - innerOff) * scroller.clientWidth); + } + return sp.left; + } + var from = 0, + fromX = 0, + to = text.length, + toX; + var estimated = Math.min(to, Math.ceil((x + innerOff * scroller.clientWidth * .9) / cw)); + for (;;) { + var estX = getX(estimated); + if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2)); + else { + toX = estX; + to = estimated; + break; + } + } + if (x > toX) return { + line: lineNo, + ch: to + }; + estimated = Math.floor(to * 0.8); + estX = getX(estimated); + if (estX < x) { + from = estimated; + fromX = estX; + } + for (;;) { + if (to - from <= 1) { + var after = x - fromX < toX - x; + return { + line: lineNo, + ch: after ? from : to, + after: after + }; + } + var middle = Math.ceil((from + to) / 2), + middleX = getX(middle); + if (middleX > x) { + to = middle; + toX = middleX; + if (wrongLine) toX += 1000; + } else { + from = middle; + fromX = middleX; + } + } + } + + function pageCoords(pos) { + var local = localCoords(pos, true), + off = eltOffset(lineSpace); + return { + x: off.left + local.x, + y: off.top + local.y, + yBot: off.top + local.yBot + }; + } + var cachedHeight, cachedHeightFor, measurePre; + + function textHeight() { + if (measurePre == null) { + measurePre = elt("pre"); + for (var i = 0; i < 49; ++i) { + measurePre.appendChild(document.createTextNode("x")); + measurePre.appendChild(elt("br")); + } + measurePre.appendChild(document.createTextNode("x")); + } + var offsetHeight = lineDiv.clientHeight; + if (offsetHeight == cachedHeightFor) return cachedHeight; + cachedHeightFor = offsetHeight; + removeChildrenAndAdd(measure, measurePre.cloneNode(true)); + cachedHeight = measure.firstChild.offsetHeight / 50 || 1; + removeChildren(measure); + return cachedHeight; + } + var cachedWidth, cachedWidthFor = 0; + + function charWidth() { + if (scroller.clientWidth == cachedWidthFor) return cachedWidth; + cachedWidthFor = scroller.clientWidth; + var anchor = elt("span", "x"); + var pre = elt("pre", [anchor]); + removeChildrenAndAdd(measure, pre); + return (cachedWidth = anchor.offsetWidth || 10); + } + + function paddingTop() { + return lineSpace.offsetTop; + } + + function paddingLeft() { + return lineSpace.offsetLeft; + } + + function posFromMouse(e, liberal) { + var offW = eltOffset(scroller, true), + x, y; + try { + x = e.clientX; + y = e.clientY; + } catch (e) { + return null; + } + if (!liberal && (x - offW.left > scroller.clientWidth || y - offW.top > scroller.clientHeight)) + return null; + var offL = eltOffset(lineSpace, true); + return coordsChar(x - offL.left, y - offL.top); + } + var detectingSelectAll; + + function onContextMenu(e) { + var pos = posFromMouse(e), + scrollPos = scrollbar.scrollTop; + if (!pos || opera) return; + if (posEq(sel.from, sel.to) || posLess(pos, sel.from) || !posLess(pos, sel.to)) + operation(setCursor)(pos.line, pos.ch); + var oldCSS = input.style.cssText; + inputDiv.style.position = "absolute"; + input.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) + "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: white; " + "border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; + focusInput(); + resetInput(true); + if (posEq(sel.from, sel.to)) input.value = prevInput = " "; + + function rehide() { + inputDiv.style.position = "relative"; + input.style.cssText = oldCSS; + if (ie_lt9) scrollbar.scrollTop = scrollPos; + slowPoll(); + if (input.selectionStart != null) { + clearTimeout(detectingSelectAll); + var extval = input.value = " " + (posEq(sel.from, sel.to) ? "" : input.value), + i = 0; + prevInput = " "; + input.selectionStart = 1; + input.selectionEnd = extval.length; + detectingSelectAll = setTimeout(function poll() { + if (prevInput == " " && input.selectionStart == 0) + operation(commands.selectAll)(instance); + else if (i++ < 10) detectingSelectAll = setTimeout(poll, 500); + else resetInput(); + }, 200); + } + } + if (gecko) { + e_stop(e); + var mouseup = connect(window, "mouseup", function() { + mouseup(); + setTimeout(rehide, 20); + }, true); + } else { + setTimeout(rehide, 50); + } + } + + function restartBlink() { + clearInterval(blinker); + var on = true; + cursor.style.visibility = ""; + blinker = setInterval(function() { + cursor.style.visibility = (on = !on) ? "" : "hidden"; + }, options.cursorBlinkRate); + } + var matching = { + "(": ")>", + ")": "(<", + "[": "]>", + "]": "[<", + "{": "}>", + "}": "{<" + }; + + function matchBrackets(autoclear) { + var head = sel.inverted ? sel.from : sel.to, + line = getLine(head.line), + pos = head.ch - 1; + var match = (pos >= 0 && matching[line.text.charAt(pos)]) || matching[line.text.charAt(++pos)]; + if (!match) return; + var ch = match.charAt(0), + forward = match.charAt(1) == ">", + d = forward ? 1 : -1, + st = line.styles; + for (var off = pos + 1, i = 0, e = st.length; i < e; i += 2) + if ((off -= st[i].length) <= 0) { + var style = st[i + 1]; + break; + } + var stack = [line.text.charAt(pos)], + re = /[(){}[\]]/; + + function scan(line, from, to) { + if (!line.text) return; + var st = line.styles, + pos = forward ? 0 : line.text.length - 1, + cur; + for (var i = forward ? 0 : st.length - 2, e = forward ? st.length : -2; i != e; i += 2 * d) { + var text = st[i]; + if (st[i + 1] != style) { + pos += d * text.length; + continue; + } + for (var j = forward ? 0 : text.length - 1, te = forward ? text.length : -1; j != te; j += d, pos += d) { + if (pos >= from && pos < to && re.test(cur = text.charAt(j))) { + var match = matching[cur]; + if (match.charAt(1) == ">" == forward) stack.push(cur); + else if (stack.pop() != match.charAt(0)) return { + pos: pos, + match: false + }; + else if (!stack.length) return { + pos: pos, + match: true + }; + } + } + } + } + for (var i = head.line, e = forward ? Math.min(i + 100, doc.size) : Math.max(-1, i - 100); i != e; i += d) { + var line = getLine(i), + first = i == head.line; + var found = scan(line, first && forward ? pos + 1 : 0, first && !forward ? pos : line.text.length); + if (found) break; + } + if (!found) found = { + pos: null, + match: false + }; + var style = found.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket"; + var one = markText({ + line: head.line, + ch: pos + }, { + line: head.line, + ch: pos + 1 + }, style), + two = found.pos != null && markText({ + line: i, + ch: found.pos + }, { + line: i, + ch: found.pos + 1 + }, style); + var clear = operation(function() { + one.clear(); + two && two.clear(); + }); + if (autoclear) setTimeout(clear, 800); + else bracketHighlighted = clear; + } + + function findStartLine(n) { + var minindent, minline; + for (var search = n, lim = n - 40; search > lim; --search) { + if (search == 0) return 0; + var line = getLine(search - 1); + if (line.stateAfter) return search; + var indented = line.indentation(options.tabSize); + if (minline == null || minindent > indented) { + minline = search - 1; + minindent = indented; + } + } + return minline; + } + + function getStateBefore(n) { + var pos = findStartLine(n), + state = pos && getLine(pos - 1).stateAfter; + if (!state) state = startState(mode); + else state = copyState(mode, state); + doc.iter(pos, n, function(line) { + line.process(mode, state, options.tabSize); + line.stateAfter = (pos == n - 1 || pos % 5 == 0) ? copyState(mode, state) : null; + }); + return state; + } + + function highlightWorker() { + if (frontier >= showingTo) return; + var end = +new Date + options.workTime, + state = copyState(mode, getStateBefore(frontier)); + var startFrontier = frontier; + doc.iter(frontier, showingTo, function(line) { + if (frontier >= showingFrom) { + line.highlight(mode, state, options.tabSize); + line.stateAfter = copyState(mode, state); + } else { + line.process(mode, state, options.tabSize); + line.stateAfter = frontier % 5 == 0 ? copyState(mode, state) : null; + } + ++frontier; + if (+new Date > end) { + startWorker(options.workDelay); + return true; + } + }); + if (showingTo > startFrontier && frontier >= showingFrom) + operation(function() { + changes.push({ + from: startFrontier, + to: frontier + }); + })(); + } + + function startWorker(time) { + if (frontier < showingTo) + highlight.set(time, highlightWorker); + } + + function startOperation() { + updateInput = userSelChange = textChanged = null; + changes = []; + selectionChanged = false; + callbacks = []; + } + + function endOperation() { + if (updateMaxLine) computeMaxLength(); + if (maxLineChanged && !options.lineWrapping) { + var cursorWidth = widthForcer.offsetWidth, + left = measureLine(maxLine, maxLine.text.length).left; + if (!ie_lt8) { + widthForcer.style.left = left + "px"; + lineSpace.style.minWidth = (left + cursorWidth) + "px"; + } + maxLineChanged = false; + } + var newScrollPos, updated; + if (selectionChanged) { + var coords = calculateCursorCoords(); + newScrollPos = calculateScrollPos(coords.x, coords.y, coords.x, coords.yBot); + } + if (changes.length || newScrollPos && newScrollPos.scrollTop != null) + updated = updateDisplay(changes, true, newScrollPos && newScrollPos.scrollTop); + if (!updated) { + if (selectionChanged) updateSelection(); + if (gutterDirty) updateGutter(); + } + if (newScrollPos) scrollCursorIntoView(); + if (selectionChanged) restartBlink(); + if (focused && (updateInput === true || (updateInput !== false && selectionChanged))) + resetInput(userSelChange); + if (selectionChanged && options.matchBrackets) + setTimeout(operation(function() { + if (bracketHighlighted) { + bracketHighlighted(); + bracketHighlighted = null; + } + if (posEq(sel.from, sel.to)) matchBrackets(false); + }), 20); + var sc = selectionChanged, + cbs = callbacks; + if (textChanged && options.onChange && instance) + options.onChange(instance, textChanged); + if (sc && options.onCursorActivity) + options.onCursorActivity(instance); + for (var i = 0; i < cbs.length; ++i) cbs[i](instance); + if (updated && options.onUpdate) options.onUpdate(instance); + } + var nestedOperation = 0; + + function operation(f) { + return function() { + if (!nestedOperation++) startOperation(); + try { + var result = f.apply(this, arguments); + } finally { + if (!--nestedOperation) endOperation(); + } + return result; + }; + } + + function compoundChange(f) { + history.startCompound(); + try { + return f(); + } finally { + history.endCompound(); + } + } + for (var ext in extensions) + if (extensions.propertyIsEnumerable(ext) && !instance.propertyIsEnumerable(ext)) + instance[ext] = extensions[ext]; + for (var i = 0; i < initHooks.length; ++i) initHooks[i](instance); + return instance; + } + CodeMirror.defaults = { + value: "", + mode: null, + theme: "default", + indentUnit: 2, + indentWithTabs: false, + smartIndent: true, + tabSize: 4, + keyMap: "default", + extraKeys: null, + electricChars: true, + autoClearEmptyLines: false, + onKeyEvent: null, + onDragEvent: null, + lineWrapping: false, + lineNumbers: false, + gutter: false, + fixedGutter: false, + firstLineNumber: 1, + readOnly: false, + dragDrop: true, + onChange: null, + onCursorActivity: null, + onViewportChange: null, + onGutterClick: null, + onUpdate: null, + onFocus: null, + onBlur: null, + onScroll: null, + matchBrackets: false, + cursorBlinkRate: 530, + workTime: 100, + workDelay: 200, + pollInterval: 100, + undoDepth: 40, + tabindex: null, + autofocus: null, + lineNumberFormatter: function(integer) { + return integer; + } + }; + var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent); + var mac = ios || /Mac/.test(navigator.platform); + var win = /Win/.test(navigator.platform); + var modes = CodeMirror.modes = {}, + mimeModes = CodeMirror.mimeModes = {}; + CodeMirror.defineMode = function(name, mode) { + if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name; + if (arguments.length > 2) { + mode.dependencies = []; + for (var i = 2; i < arguments.length; ++i) mode.dependencies.push(arguments[i]); + } + modes[name] = mode; + }; + CodeMirror.defineMIME = function(mime, spec) { + mimeModes[mime] = spec; + }; + CodeMirror.resolveMode = function(spec) { + if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) + spec = mimeModes[spec]; + else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) + return CodeMirror.resolveMode("application/xml"); + if (typeof spec == "string") return { + name: spec + }; + else return spec || { + name: "null" + }; + }; + 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)) modeObj[prop] = exts[prop]; + } + modeObj.name = spec.name; + return modeObj; + }; + CodeMirror.listModes = function() { + var list = []; + for (var m in modes) + if (modes.propertyIsEnumerable(m)) list.push(m); + return list; + }; + CodeMirror.listMIMEs = function() { + var list = []; + for (var m in mimeModes) + if (mimeModes.propertyIsEnumerable(m)) list.push({ + mime: m, + mode: mimeModes[m] + }); + return list; + }; + var extensions = CodeMirror.extensions = {}; + CodeMirror.defineExtension = function(name, func) { + extensions[name] = func; + }; + var initHooks = []; + CodeMirror.defineInitHook = function(f) { + initHooks.push(f); + }; + var modeExtensions = CodeMirror.modeExtensions = {}; + CodeMirror.extendMode = function(mode, properties) { + var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); + for (var prop in properties) + if (properties.hasOwnProperty(prop)) + exts[prop] = properties[prop]; + }; + var commands = CodeMirror.commands = { + selectAll: function(cm) { + cm.setSelection({ + line: 0, + ch: 0 + }, { + line: cm.lineCount() - 1 + }); + }, + killLine: function(cm) { + var from = cm.getCursor(true), + to = cm.getCursor(false), + sel = !posEq(from, to); + if (!sel && cm.getLine(from.line).length == from.ch) cm.replaceRange("", from, { + line: from.line + 1, + ch: 0 + }); + else cm.replaceRange("", from, sel ? to : { + line: from.line + }); + }, + deleteLine: function(cm) { + var l = cm.getCursor().line; + cm.replaceRange("", { + line: l, + ch: 0 + }, { + line: l + }); + }, + undo: function(cm) { + cm.undo(); + }, + redo: function(cm) { + cm.redo(); + }, + goDocStart: function(cm) { + cm.setCursor(0, 0, true); + }, + goDocEnd: function(cm) { + cm.setSelection({ + line: cm.lineCount() - 1 + }, null, true); + }, + goLineStart: function(cm) { + cm.setCursor(cm.getCursor().line, 0, true); + }, + goLineStartSmart: function(cm) { + var cur = cm.getCursor(); + var text = cm.getLine(cur.line), + firstNonWS = Math.max(0, text.search(/\S/)); + cm.setCursor(cur.line, cur.ch <= firstNonWS && cur.ch ? 0 : firstNonWS, true); + }, + goLineEnd: function(cm) { + cm.setSelection({ + line: cm.getCursor().line + }, null, true); + }, + 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"); + }, + goWordRight: function(cm) { + cm.moveH(1, "word"); + }, + delCharLeft: function(cm) { + cm.deleteH(-1, "char"); + }, + delCharRight: function(cm) { + cm.deleteH(1, "char"); + }, + delWordLeft: function(cm) { + cm.deleteH(-1, "word"); + }, + delWordRight: function(cm) { + cm.deleteH(1, "word"); + }, + indentAuto: function(cm) { + cm.indentSelection("smart"); + }, + indentMore: function(cm) { + cm.indentSelection("add"); + }, + indentLess: function(cm) { + cm.indentSelection("subtract"); + }, + insertTab: function(cm) { + cm.replaceSelection("\t", "end"); + }, + defaultTab: function(cm) { + if (cm.somethingSelected()) cm.indentSelection("add"); + else cm.replaceSelection("\t", "end"); + }, + transposeChars: function(cm) { + var cur = cm.getCursor(), + line = cm.getLine(cur.line); + if (cur.ch > 0 && cur.ch < line.length - 1) + cm.replaceRange(line.charAt(cur.ch) + line.charAt(cur.ch - 1), { + line: cur.line, + ch: cur.ch - 1 + }, { + line: cur.line, + ch: cur.ch + 1 + }); + }, + newlineAndIndent: function(cm) { + cm.replaceSelection("\n", "end"); + cm.indentLine(cm.getCursor().line); + }, + toggleOverwrite: function(cm) { + cm.toggleOverwrite(); + } + }; + var keyMap = CodeMirror.keyMap = {}; + keyMap.basic = { + "Left": "goCharLeft", + "Right": "goCharRight", + "Up": "goLineUp", + "Down": "goLineDown", + "End": "goLineEnd", + "Home": "goLineStartSmart", + "PageUp": "goPageUp", + "PageDown": "goPageDown", + "Delete": "delCharRight", + "Backspace": "delCharLeft", + "Tab": "defaultTab", + "Shift-Tab": "indentAuto", + "Enter": "newlineAndIndent", + "Insert": "toggleOverwrite" + }; + keyMap.pcDefault = { + "Ctrl-A": "selectAll", + "Ctrl-D": "deleteLine", + "Ctrl-Z": "undo", + "Shift-Ctrl-Z": "redo", + "Ctrl-Y": "redo", + "Ctrl-Home": "goDocStart", + "Alt-Up": "goDocStart", + "Ctrl-End": "goDocEnd", + "Ctrl-Down": "goDocEnd", + "Ctrl-Left": "goWordLeft", + "Ctrl-Right": "goWordRight", + "Alt-Left": "goLineStart", + "Alt-Right": "goLineEnd", + "Ctrl-Backspace": "delWordLeft", + "Ctrl-Delete": "delWordRight", + "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", + fallthrough: "basic" + }; + keyMap.macDefault = { + "Cmd-A": "selectAll", + "Cmd-D": "deleteLine", + "Cmd-Z": "undo", + "Shift-Cmd-Z": "redo", + "Cmd-Y": "redo", + "Cmd-Up": "goDocStart", + "Cmd-End": "goDocEnd", + "Cmd-Down": "goDocEnd", + "Alt-Left": "goWordLeft", + "Alt-Right": "goWordRight", + "Cmd-Left": "goLineStart", + "Cmd-Right": "goLineEnd", + "Alt-Backspace": "delWordLeft", + "Ctrl-Alt-Backspace": "delWordRight", + "Alt-Delete": "delWordRight", + "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", + fallthrough: ["basic", "emacsy"] + }; + keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; + 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": "delCharRight", + "Ctrl-H": "delCharLeft", + "Alt-D": "delWordRight", + "Alt-Backspace": "delWordLeft", + "Ctrl-K": "killLine", + "Ctrl-T": "transposeChars" + }; + + function getKeyMap(val) { + if (typeof val == "string") return keyMap[val]; + else return val; + } + + function lookupKey(name, extraMap, map, handle, stop) { + function lookup(map) { + map = getKeyMap(map); + var found = map[name]; + if (found === false) { + if (stop) stop(); + return true; + } + if (found != null && handle(found)) return true; + if (map.nofallthrough) { + if (stop) stop(); + return true; + } + var fallthrough = map.fallthrough; + if (fallthrough == null) return false; + if (Object.prototype.toString.call(fallthrough) != "[object Array]") + return lookup(fallthrough); + for (var i = 0, e = fallthrough.length; i < e; ++i) { + if (lookup(fallthrough[i])) return true; + } + return false; + } + if (extraMap && lookup(extraMap)) return true; + return lookup(map); + } + + function isModifierKey(event) { + var name = keyNames[e_prop(event, "keyCode")]; + return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; + } + CodeMirror.isModifierKey = isModifierKey; + CodeMirror.fromTextArea = function(textarea, options) { + if (!options) options = {}; + options.value = textarea.value; + if (!options.tabindex && textarea.tabindex) + options.tabindex = textarea.tabindex; + if (options.autofocus == null) { + var hasFocus = document.body; + try { + hasFocus = document.activeElement; + } catch (e) {} + options.autofocus = hasFocus == textarea || textarea.getAttribute("autofocus") != null && hasFocus == document.body; + } + + function save() { + textarea.value = instance.getValue(); + } + if (textarea.form) { + var rmSubmit = connect(textarea.form, "submit", save, true); + var realSubmit = textarea.form.submit; + textarea.form.submit = function wrappedSubmit() { + save(); + textarea.form.submit = realSubmit; + textarea.form.submit(); + textarea.form.submit = wrappedSubmit; + }; + } + textarea.style.display = "none"; + var instance = CodeMirror(function(node) { + textarea.parentNode.insertBefore(node, textarea.nextSibling); + }, options); + instance.save = save; + instance.getTextArea = function() { + return textarea; + }; + instance.toTextArea = function() { + save(); + textarea.parentNode.removeChild(instance.getWrapperElement()); + textarea.style.display = ""; + if (textarea.form) { + rmSubmit(); + if (typeof textarea.form.submit == "function") + textarea.form.submit = realSubmit; + } + }; + return instance; + }; + var gecko = /gecko\/\d{7}/i.test(navigator.userAgent); + var ie = /MSIE \d/.test(navigator.userAgent); + var ie_lt8 = /MSIE [1-7]\b/.test(navigator.userAgent); + var ie_lt9 = /MSIE [1-8]\b/.test(navigator.userAgent); + var quirksMode = ie && document.documentMode == 5; + var webkit = /WebKit\//.test(navigator.userAgent); + var chrome = /Chrome\//.test(navigator.userAgent); + var opera = /Opera\//.test(navigator.userAgent); + var safari = /Apple Computer/.test(navigator.vendor); + var khtml = /KHTML\//.test(navigator.userAgent); + var mac_geLion = /Mac OS X 10\D([7-9]|\d\d)\D/.test(navigator.userAgent); + + 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; + } + CodeMirror.copyState = copyState; + + function startState(mode, a1, a2) { + return mode.startState ? mode.startState(a1, a2) : true; + } + CodeMirror.startState = startState; + CodeMirror.innerMode = function(mode, state) { + while (mode.innerMode) { + var info = mode.innerMode(state); + state = info.state; + mode = info.mode; + } + return info || { + mode: mode, + state: state + }; + }; + + function StringStream(string, tabSize) { + this.pos = this.start = 0; + this.string = string; + this.tabSize = tabSize || 8; + } + StringStream.prototype = { + eol: function() { + return this.pos >= this.string.length; + }, + sol: function() { + return this.pos == 0; + }, + 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() { + return countColumn(this.string, this.start, this.tabSize); + }, + indentation: function() { + return countColumn(this.string, null, this.tabSize); + }, + match: function(pattern, consume, caseInsensitive) { + if (typeof pattern == "string") { + var cased = function(str) { + return caseInsensitive ? str.toLowerCase() : str; + }; + if (cased(this.string).indexOf(cased(pattern), this.pos) == this.pos) { + 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); + } + }; + CodeMirror.StringStream = StringStream; + + function MarkedSpan(from, to, marker) { + this.from = from; + this.to = to; + this.marker = 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; + } + } + + 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; + } + + function markedSpansBefore(old, startCh, endCh) { + 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 || marker.type == "bookmark" && span.from == startCh && span.from != endCh) { + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh); + (nw || (nw = [])).push({ + from: span.from, + to: endsAfter ? null : span.to, + marker: marker + }); + } + } + return nw; + } + + function markedSpansAfter(old, endCh) { + 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 || marker.type == "bookmark" && span.from == endCh) { + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh); + (nw || (nw = [])).push({ + from: startsBefore ? null : span.from - endCh, + to: span.to == null ? null : span.to - endCh, + marker: marker + }); + } + } + return nw; + } + + function updateMarkedSpans(oldFirst, oldLast, startCh, endCh, newText) { + if (!oldFirst && !oldLast) return newText; + var first = markedSpansBefore(oldFirst, startCh); + var last = markedSpansAfter(oldLast, endCh); + var sameLine = newText.length == 1, + offset = lst(newText).length + (sameLine ? startCh : 0); + if (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) { + 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); + } + } + } + var newMarkers = [newHL(newText[0], first)]; + if (!sameLine) { + var gap = newText.length - 2, + gapMarkers; + if (gap > 0 && first) + for (var i = 0; i < first.length; ++i) + if (first[i].to == null) + (gapMarkers || (gapMarkers = [])).push({ + from: null, + to: null, + marker: first[i].marker + }); + for (var i = 0; i < gap; ++i) + newMarkers.push(newHL(newText[i + 1], gapMarkers)); + newMarkers.push(newHL(lst(newText), last)); + } + return newMarkers; + } + + function hlText(val) { + return typeof val == "string" ? val : val.text; + } + + function hlSpans(val) { + if (typeof val == "string") return null; + var spans = val.markedSpans, + out = null; + 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; + } + + function newHL(text, spans) { + return spans ? { + text: text, + markedSpans: spans + } : text; + } + + function detachMarkedSpans(line) { + var spans = line.markedSpans; + if (!spans) return; + for (var i = 0; i < spans.length; ++i) { + var lines = spans[i].marker.lines; + var ix = indexOf(lines, line); + lines.splice(ix, 1); + } + line.markedSpans = null; + } + + function attachMarkedSpans(line, spans) { + if (!spans) return; + for (var i = 0; i < spans.length; ++i) + var marker = spans[i].marker.lines.push(line); + line.markedSpans = spans; + } + var eolSpanContent = " "; + if (gecko || (ie && !ie_lt8)) eolSpanContent = "\u200b"; + else if (opera) eolSpanContent = ""; + + function Line(text, markedSpans) { + this.text = text; + this.height = 1; + attachMarkedSpans(this, markedSpans); + } + Line.prototype = { + update: function(text, markedSpans) { + this.text = text; + this.stateAfter = this.styles = null; + detachMarkedSpans(this); + attachMarkedSpans(this, markedSpans); + }, + highlight: function(mode, state, tabSize) { + var stream = new StringStream(this.text, tabSize), + st = this.styles || (this.styles = []); + var pos = st.length = 0; + if (this.text == "" && mode.blankLine) mode.blankLine(state); + while (!stream.eol()) { + var style = mode.token(stream, state), + substr = stream.current(); + stream.start = stream.pos; + if (pos && st[pos - 1] == style) { + st[pos - 2] += substr; + } else if (substr) { + st[pos++] = substr; + st[pos++] = style; + } + if (stream.pos > 5000) { + st[pos++] = this.text.slice(stream.pos); + st[pos++] = null; + break; + } + } + }, + process: function(mode, state, tabSize) { + var stream = new StringStream(this.text, tabSize); + if (this.text == "" && mode.blankLine) mode.blankLine(state); + while (!stream.eol() && stream.pos <= 5000) { + mode.token(stream, state); + stream.start = stream.pos; + } + }, + getTokenAt: function(mode, state, tabSize, ch) { + var txt = this.text, + stream = new StringStream(txt, tabSize); + while (stream.pos < ch && !stream.eol()) { + stream.start = stream.pos; + var style = mode.token(stream, state); + } + return { + start: stream.start, + end: stream.pos, + string: stream.current(), + className: style || null, + state: state + }; + }, + indentation: function(tabSize) { + return countColumn(this.text, null, tabSize); + }, + getContent: function(tabSize, wrapAt, compensateForWrapping) { + var first = true, + col = 0, + specials = /[\t\u0000-\u0019\u200b\u2028\u2029\uFEFF]/g; + var pre = elt("pre"); + + function span_(html, text, style) { + if (!text) return; + if (first && ie && text.charAt(0) == " ") text = "\u00a0" + text.slice(1); + first = false; + if (!specials.test(text)) { + col += text.length; + var content = document.createTextNode(text); + } else { + var content = document.createDocumentFragment(), + pos = 0; + while (true) { + specials.lastIndex = pos; + var m = specials.exec(text); + var skipped = m ? m.index - pos : text.length - pos; + if (skipped) { + content.appendChild(document.createTextNode(text.slice(pos, pos + skipped))); + col += skipped; + } + if (!m) break; + pos += skipped + 1; + if (m[0] == "\t") { + var tabWidth = tabSize - col % tabSize; + content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); + col += tabWidth; + } else { + var token = elt("span", "\u2022", "cm-invalidchar"); + token.title = "\\u" + m[0].charCodeAt(0).toString(16); + content.appendChild(token); + col += 1; + } + } + } + if (style) html.appendChild(elt("span", [content], style)); + else html.appendChild(content); + } + var span = span_; + if (wrapAt != null) { + var outPos = 0, + anchor = pre.anchor = elt("span"); + span = function(html, text, style) { + var l = text.length; + if (wrapAt >= outPos && wrapAt < outPos + l) { + var cut = wrapAt - outPos; + if (cut) { + span_(html, text.slice(0, cut), style); + if (compensateForWrapping) { + var view = text.slice(cut - 1, cut + 1); + if (spanAffectsWrapping.test(view)) html.appendChild(elt("wbr")); + else if (!ie_lt8 && /\w\w/.test(view)) html.appendChild(document.createTextNode("\u200d")); + } + } + html.appendChild(anchor); + span_(anchor, opera ? text.slice(cut, cut + 1) : text.slice(cut), style); + if (opera) span_(html, text.slice(cut + 1), style); + wrapAt--; + outPos += l; + } else { + outPos += l; + span_(html, text, style); + if (outPos == wrapAt && outPos == len) { + setTextContent(anchor, eolSpanContent); + html.appendChild(anchor); + } else if (outPos > wrapAt + 10 && /\s/.test(text)) span = function() {}; + } + }; + } + var st = this.styles, + allText = this.text, + marked = this.markedSpans; + var len = allText.length; + + function styleToClass(style) { + if (!style) return null; + return "cm-" + style.replace(/ +/g, " cm-"); + } + if (!allText && wrapAt == null) { + span(pre, " "); + } else if (!marked || !marked.length) { + for (var i = 0, ch = 0; ch < len; i += 2) { + var str = st[i], + style = st[i + 1], + l = str.length; + if (ch + l > len) str = str.slice(0, len - ch); + ch += l; + span(pre, str, styleToClass(style)); + } + } else { + marked.sort(function(a, b) { + return a.from - b.from; + }); + var pos = 0, + i = 0, + text = "", + style, sg = 0; + var nextChange = marked[0].from || 0, + marks = [], + markpos = 0; + var advanceMarks = function() { + var m; + while (markpos < marked.length && ((m = marked[markpos]).from == pos || m.from == null)) { + if (m.marker.type == "range") marks.push(m); + ++markpos; + } + nextChange = markpos < marked.length ? marked[markpos].from : Infinity; + for (var i = 0; i < marks.length; ++i) { + var to = marks[i].to; + if (to == null) to = Infinity; + if (to == pos) marks.splice(i--, 1); + else nextChange = Math.min(to, nextChange); + } + }; + var m = 0; + while (pos < len) { + if (nextChange == pos) advanceMarks(); + var upto = Math.min(len, nextChange); + while (true) { + if (text) { + var end = pos + text.length; + var appliedStyle = style; + for (var j = 0; j < marks.length; ++j) { + var mark = marks[j]; + appliedStyle = (appliedStyle ? appliedStyle + " " : "") + mark.marker.style; + if (mark.marker.endStyle && mark.to === Math.min(end, upto)) appliedStyle += " " + mark.marker.endStyle; + if (mark.marker.startStyle && mark.from === pos) appliedStyle += " " + mark.marker.startStyle; + } + span(pre, end > upto ? text.slice(0, upto - pos) : text, appliedStyle); + if (end >= upto) { + text = text.slice(upto - pos); + pos = upto; + break; + } + pos = end; + } + text = st[i++]; + style = styleToClass(st[i++]); + } + } + } + return pre; + }, + cleanUp: function() { + this.parent = null; + detachMarkedSpans(this); + } + }; + + function LeafChunk(lines) { + this.lines = lines; + this.parent = null; + for (var i = 0, e = lines.length, height = 0; i < e; ++i) { + lines[i].parent = this; + height += lines[i].height; + } + this.height = height; + } + LeafChunk.prototype = { + chunkSize: function() { + return this.lines.length; + }, + remove: function(at, n, callbacks) { + for (var i = at, e = at + n; i < e; ++i) { + var line = this.lines[i]; + this.height -= line.height; + line.cleanUp(); + if (line.handlers) + for (var j = 0; j < line.handlers.length; ++j) callbacks.push(line.handlers[j]); + } + this.lines.splice(at, n); + }, + collapse: function(lines) { + lines.splice.apply(lines, [lines.length, 0].concat(this.lines)); + }, + insertHeight: 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, e = lines.length; i < e; ++i) lines[i].parent = this; + }, + 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, e = children.length; i < e; ++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; + }, + remove: function(at, n, callbacks) { + 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.remove(at, rm, callbacks); + 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 (this.size - n < 25) { + var lines = []; + this.collapse(lines); + this.children = [new LeafChunk(lines)]; + this.children[0].parent = this; + } + }, + collapse: function(lines) { + for (var i = 0, e = this.children.length; i < e; ++i) this.children[i].collapse(lines); + }, + insert: function(at, lines) { + var height = 0; + for (var i = 0, e = lines.length; i < e; ++i) height += lines[i].height; + this.insertHeight(at, lines, height); + }, + insertHeight: function(at, lines, height) { + this.size += lines.length; + this.height += height; + for (var i = 0, e = this.children.length; i < e; ++i) { + var child = this.children[i], + sz = child.chunkSize(); + if (at <= sz) { + child.insertHeight(at, lines, height); + if (child.lines && child.lines.length > 50) { + while (child.lines.length > 50) { + var spilled = child.lines.splice(child.lines.length - 25, 25); + var newleaf = new LeafChunk(spilled); + child.height -= newleaf.height; + this.children.splice(i + 1, 0, newleaf); + newleaf.parent = this; + } + this.maybeSpill(); + } + break; + } + at -= sz; + } + }, + 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) { + 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(); + }, + iter: function(from, to, op) { + this.iterN(from, to - from, op); + }, + iterN: function(at, n, op) { + for (var i = 0, e = this.children.length; i < e; ++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; + } + } + }; + + function getLineAt(chunk, n) { + 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]; + } + + 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, e = chunk.children.length;; ++i) { + if (chunk.children[i] == cur) break; + no += chunk.children[i].chunkSize(); + } + } + return no; + } + + function lineAtHeight(chunk, h) { + var n = 0; + outer: do { + for (var i = 0, e = chunk.children.length; i < e; ++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, e = chunk.lines.length; i < e; ++i) { + var line = chunk.lines[i], + lh = line.height; + if (h < lh) break; + h -= lh; + } + return n + i; + } + + function heightAtLine(chunk, n) { + var h = 0; + outer: do { + for (var i = 0, e = chunk.children.length; i < e; ++i) { + var child = chunk.children[i], + sz = child.chunkSize(); + if (n < sz) { + chunk = child; + continue outer; + } + n -= sz; + h += child.height; + } + return h; + } while (!chunk.lines); + for (var i = 0; i < n; ++i) h += chunk.lines[i].height; + return h; + } + + function History() { + this.time = 0; + this.done = []; + this.undone = []; + this.compound = 0; + this.closed = false; + } + History.prototype = { + addChange: function(start, added, old) { + this.undone.length = 0; + var time = +new Date, + cur = lst(this.done), + last = cur && lst(cur); + var dtime = time - this.time; + if (cur && !this.closed && this.compound) { + cur.push({ + start: start, + added: added, + old: old + }); + } else if (dtime > 400 || !last || this.closed || last.start > start + old.length || last.start + last.added < start) { + this.done.push([{ + start: start, + added: added, + old: old + }]); + this.closed = false; + } else { + var startBefore = Math.max(0, last.start - start), + endAfter = Math.max(0, (start + old.length) - (last.start + last.added)); + for (var i = startBefore; i > 0; --i) last.old.unshift(old[i - 1]); + for (var i = endAfter; i > 0; --i) last.old.push(old[old.length - i]); + if (startBefore) last.start = start; + last.added += added - (old.length - startBefore - endAfter); + } + this.time = time; + }, + startCompound: function() { + if (!this.compound++) this.closed = true; + }, + endCompound: function() { + if (!--this.compound) this.closed = true; + } + }; + + function stopMethod() { + e_stop(this); + } + + function addStop(event) { + if (!event.stop) event.stop = stopMethod; + return event; + } + + 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_stop(e) { + e_preventDefault(e); + e_stopPropagation(e); + } + CodeMirror.e_stop = e_stop; + CodeMirror.e_preventDefault = e_preventDefault; + CodeMirror.e_stopPropagation = e_stopPropagation; + + 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; + } + + function e_prop(e, prop) { + var overridden = e.override && e.override.hasOwnProperty(prop); + return overridden ? e.override[prop] : e[prop]; + } + + function connect(node, type, handler, disconnect) { + if (typeof node.addEventListener == "function") { + node.addEventListener(type, handler, false); + if (disconnect) return function() { + node.removeEventListener(type, handler, false); + }; + } else { + var wrapHandler = function(event) { + handler(event || window.event); + }; + node.attachEvent("on" + type, wrapHandler); + if (disconnect) return function() { + node.detachEvent("on" + type, wrapHandler); + }; + } + } + CodeMirror.connect = connect; + + function Delayed() { + this.id = null; + } + Delayed.prototype = { + set: function(ms, f) { + clearTimeout(this.id); + this.id = setTimeout(f, ms); + } + }; + var Pass = CodeMirror.Pass = { + toString: function() { + return "CodeMirror.Pass"; + } + }; + var dragAndDrop = function() { + if (ie_lt9) return false; + var div = elt('div'); + return "draggable" in div || "dragDrop" in div; + }(); + var lineSep = function() { + var te = elt("textarea"); + te.value = "foo\nbar"; + if (te.value.indexOf("\r") > -1) return "\r\n"; + return "\n"; + }(); + var spanAffectsWrapping = /^$/; + if (gecko) spanAffectsWrapping = /$'/; + else if (safari) spanAffectsWrapping = /\-[^ \-?]|\?[^ !'\"\),.\-\/:;\?\]\}]/; + else if (chrome) spanAffectsWrapping = /\-[^ \-\.?]|\?[^ \-\.?\]\}:;!'\"\),\/]|[\.!\"#&%\)*+,:;=>\]|\}~][\(\{\[<]|\$'/; + + function countColumn(string, end, tabSize) { + if (end == null) { + end = string.search(/[^\s\u00a0]/); + if (end == -1) end = string.length; + } + for (var i = 0, n = 0; i < end; ++i) { + if (string.charAt(i) == "\t") n += tabSize - (n % tabSize); + else ++n; + } + return n; + } + + function eltOffset(node, screen) { + try { + var box = node.getBoundingClientRect(); + box = { + top: box.top, + left: box.left + }; + } catch (e) { + box = { + top: 0, + left: 0 + }; + } + if (!screen) { + if (window.pageYOffset == null) { + var t = document.documentElement || document.body.parentNode; + if (t.scrollTop == null) t = document.body; + box.top += t.scrollTop; + box.left += t.scrollLeft; + } else { + box.top += window.pageYOffset; + box.left += window.pageXOffset; + } + } + return box; + } + + function eltText(node) { + return node.textContent || node.innerText || node.nodeValue || ""; + } + 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 selectInput(node) { + if (ios) { + node.selectionStart = 0; + node.selectionEnd = node.value.length; + } else node.select(); + } + + function posEq(a, b) { + return a.line == b.line && a.ch == b.ch; + } + + function posLess(a, b) { + return a.line < b.line || (a.line == b.line && a.ch < b.ch); + } + + function copyPos(x) { + return { + line: x.line, + ch: x.ch + }; + } + + 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") setTextContent(e, content); + else if (content) + for (var i = 0; i < content.length; ++i) e.appendChild(content[i]); + return e; + } + + function removeChildren(e) { + e.innerHTML = ""; + return e; + } + + function removeChildrenAndAdd(parent, e) { + removeChildren(parent).appendChild(e); + } + + function setTextContent(e, str) { + if (ie_lt9) { + e.innerHTML = ""; + e.appendChild(document.createTextNode(str)); + } else e.textContent = str; + } + + function editEnd(from, to) { + if (!to) return 0; + if (!from) return to.length; + for (var i = from.length, j = to.length; i >= 0 && j >= 0; --i, --j) + if (from.charAt(i) != to.charAt(j)) break; + return j + 1; + } + + function indexOf(collection, elt) { + if (collection.indexOf) return collection.indexOf(elt); + for (var i = 0, e = collection.length; i < e; ++i) + if (collection[i] == elt) return i; + return -1; + } + var nonASCIISingleCaseWordChar = /[\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc]/; + + function isWordChar(ch) { + return /\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)); + } + var 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/); + }; + CodeMirror.splitLines = splitLines; + 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; + }; + CodeMirror.defineMode("null", function() { + return { + token: function(stream) { + stream.skipToEnd(); + } + }; + }); + CodeMirror.defineMIME("text/plain", "null"); + 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: ";", + 91: "Mod", + 92: "Mod", + 93: "Mod", + 109: "-", + 107: "=", + 127: "Delete", + 186: ";", + 187: "=", + 188: ",", + 189: "-", + 190: ".", + 191: "/", + 192: "`", + 219: "[", + 220: "\\", + 221: "]", + 222: "'", + 63276: "PageUp", + 63277: "PageDown", + 63275: "End", + 63273: "Home", + 63234: "Left", + 63232: "Up", + 63235: "Right", + 63233: "Down", + 63302: "Insert", + 63272: "Delete" + }; + CodeMirror.keyNames = keyNames; + (function() { + for (var i = 0; i < 10; i++) keyNames[i + 48] = String(i); + for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i); + for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i; + })(); + CodeMirror.version = "2.36"; + return CodeMirror; +}) \ No newline at end of file diff --git a/js/lib/codemirror/css.js b/js/lib/codemirror/css.js deleted file mode 100644 index 41100e5..0000000 --- a/js/lib/codemirror/css.js +++ /dev/null @@ -1 +0,0 @@ -define(["./codemirror"],function(e){"use strict";function t(e){for(var t={},r=0;r*\/]/.test(r)?o(null,"select-op"):"."==r&&e.match(/^-?[_a-z][_a-z0-9-]*/i)?o("qualifier","qualifier"):/[:;{}\[\]\(\)]/.test(r)?o(null,r):"u"==r&&e.match(/rl(-prefix)?\(/)||"d"==r&&e.match("omain(")||"r"==r&&e.match("egexp(")?(e.backUp(1),t.tokenize=n,o("property","word")):/[\w\\\-]/.test(r)?(e.eatWhile(/[\w\\\-]/),o("property","word")):o(null,null):/[\d.]/.test(e.peek())?(e.eatWhile(/[\w.%]/),o("number","unit")):e.match(/^-[\w\\\-]+/)?(e.eatWhile(/[\w\\\-]/),e.match(/^\s*:/,!1)?o("variable-2","variable-definition"):o("variable-2","variable")):e.match(/^\w+-/)?o("meta","meta"):void 0}function i(e){return function(t,r){for(var a,i=!1;null!=(a=t.next());){if(a==e&&!i){")"==e&&t.backUp(1);break}i=!i&&"\\"==a}return(a==e||!i&&")"!=e)&&(r.tokenize=null),o("string","string")}}function n(e,t){return e.next(),t.tokenize=e.match(/\s*[\"\')]/,!1)?null:i(")"),o(null,"(")}function l(e,t,r){this.type=e,this.indent=t,this.prev=r}function s(e,t,r,o){return e.context=new l(r,t.indentation()+(o===!1?0:b),e.context),r}function c(e){return e.context.prev&&(e.context=e.context.prev),e.context.type}function d(e,t,r){return _[r.context.type](e,t,r)}function p(e,t,r,o){for(var a=o||1;a>0;a--)r.context=r.context.prev;return d(e,t,r)}function u(e){var t=e.current().toLowerCase();g=j.hasOwnProperty(t)?"atom":K.hasOwnProperty(t)?"keyword":"variable"}var m=r.inline;r.propertyKeywords||(r=e.resolveMode("text/css"));var h,g,b=t.indentUnit,f=r.tokenHooks,y=r.documentTypes||{},w=r.mediaTypes||{},k=r.mediaFeatures||{},v=r.mediaValueKeywords||{},x=r.propertyKeywords||{},z=r.nonStandardPropertyKeywords||{},P=r.fontProperties||{},q=r.counterDescriptors||{},K=r.colorKeywords||{},j=r.valueKeywords||{},B=r.allowNested,C=r.lineComment,T=r.supportsAtComponent===!0,_={};return _.top=function(e,t,r){if("{"==e)return s(r,t,"block");if("}"==e&&r.context.prev)return c(r);if(T&&/@component/.test(e))return s(r,t,"atComponentBlock");if(/^@(-moz-)?document$/.test(e))return s(r,t,"documentTypes");if(/^@(media|supports|(-moz-)?document|import)$/.test(e))return s(r,t,"atBlock");if(/^@(font-face|counter-style)/.test(e))return r.stateArg=e,"restricted_atBlock_before";if(/^@(-(moz|ms|o|webkit)-)?keyframes$/.test(e))return"keyframes";if(e&&"@"==e.charAt(0))return s(r,t,"at");if("hash"==e)g="builtin";else if("word"==e)g="tag";else{if("variable-definition"==e)return"maybeprop";if("interpolation"==e)return s(r,t,"interpolation");if(":"==e)return"pseudo";if(B&&"("==e)return s(r,t,"parens")}return r.context.type},_.block=function(e,t,r){if("word"==e){var o=t.current().toLowerCase();return x.hasOwnProperty(o)?(g="property","maybeprop"):z.hasOwnProperty(o)?(g="string-2","maybeprop"):B?(g=t.match(/^\s*:(?:\s|$)/,!1)?"property":"tag","block"):(g+=" error","maybeprop")}return"meta"==e?"block":B||"hash"!=e&&"qualifier"!=e?_.top(e,t,r):(g="error","block")},_.maybeprop=function(e,t,r){return":"==e?s(r,t,"prop"):d(e,t,r)},_.prop=function(e,t,r){if(";"==e)return c(r);if("{"==e&&B)return s(r,t,"propBlock");if("}"==e||"{"==e)return p(e,t,r);if("("==e)return s(r,t,"parens");if("hash"!=e||/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(t.current())){if("word"==e)u(t);else if("interpolation"==e)return s(r,t,"interpolation")}else g+=" error";return"prop"},_.propBlock=function(e,t,r){return"}"==e?c(r):"word"==e?(g="property","maybeprop"):r.context.type},_.parens=function(e,t,r){return"{"==e||"}"==e?p(e,t,r):")"==e?c(r):"("==e?s(r,t,"parens"):"interpolation"==e?s(r,t,"interpolation"):("word"==e&&u(t),"parens")},_.pseudo=function(e,t,r){return"meta"==e?"pseudo":"word"==e?(g="variable-3",r.context.type):d(e,t,r)},_.documentTypes=function(e,t,r){return"word"==e&&y.hasOwnProperty(t.current())?(g="tag",r.context.type):_.atBlock(e,t,r)},_.atBlock=function(e,t,r){if("("==e)return s(r,t,"atBlock_parens");if("}"==e||";"==e)return p(e,t,r);if("{"==e)return c(r)&&s(r,t,B?"block":"top");if("interpolation"==e)return s(r,t,"interpolation");if("word"==e){var o=t.current().toLowerCase();g="only"==o||"not"==o||"and"==o||"or"==o?"keyword":w.hasOwnProperty(o)?"attribute":k.hasOwnProperty(o)?"property":v.hasOwnProperty(o)?"keyword":x.hasOwnProperty(o)?"property":z.hasOwnProperty(o)?"string-2":j.hasOwnProperty(o)?"atom":K.hasOwnProperty(o)?"keyword":"error"}return r.context.type},_.atComponentBlock=function(e,t,r){return"}"==e?p(e,t,r):"{"==e?c(r)&&s(r,t,B?"block":"top",!1):("word"==e&&(g="error"),r.context.type)},_.atBlock_parens=function(e,t,r){return")"==e?c(r):"{"==e||"}"==e?p(e,t,r,2):_.atBlock(e,t,r)},_.restricted_atBlock_before=function(e,t,r){return"{"==e?s(r,t,"restricted_atBlock"):"word"==e&&"@counter-style"==r.stateArg?(g="variable","restricted_atBlock_before"):d(e,t,r)},_.restricted_atBlock=function(e,t,r){return"}"==e?(r.stateArg=null,c(r)):"word"==e?(g="@font-face"==r.stateArg&&!P.hasOwnProperty(t.current().toLowerCase())||"@counter-style"==r.stateArg&&!q.hasOwnProperty(t.current().toLowerCase())?"error":"property","maybeprop"):"restricted_atBlock"},_.keyframes=function(e,t,r){return"word"==e?(g="variable","keyframes"):"{"==e?s(r,t,"top"):d(e,t,r)},_.at=function(e,t,r){return";"==e?c(r):"{"==e||"}"==e?p(e,t,r):("word"==e?g="tag":"hash"==e&&(g="builtin"),"at")},_.interpolation=function(e,t,r){return"}"==e?c(r):"{"==e||";"==e?p(e,t,r):("word"==e?g="variable":"variable"!=e&&"("!=e&&")"!=e&&(g="error"),"interpolation")},{startState:function(e){return{tokenize:null,state:m?"block":"top",stateArg:null,context:new l(m?"block":"top",e||0,null)}},token:function(e,t){if(!t.tokenize&&e.eatSpace())return null;var r=(t.tokenize||a)(e,t);return r&&"object"==typeof r&&(h=r[1],r=r[0]),g=r,t.state=_[t.state](h,e,t),g},indent:function(e,t){var r=e.context,o=t&&t.charAt(0),a=r.indent;return"prop"!=r.type||"}"!=o&&")"!=o||(r=r.prev),r.prev&&("}"!=o||"block"!=r.type&&"top"!=r.type&&"interpolation"!=r.type&&"restricted_atBlock"!=r.type?(")"==o&&("parens"==r.type||"atBlock_parens"==r.type)||"{"==o&&("at"==r.type||"atBlock"==r.type))&&(a=Math.max(0,r.indent-b),r=r.prev):(r=r.prev,a=r.indent)),a},electricChars:"}",blockCommentStart:"/*",blockCommentEnd:"*/",lineComment:C,fold:"brace"}});var o=["domain","regexp","url","url-prefix"],a=t(o),i=["all","aural","braille","handheld","print","projection","screen","tty","tv","embossed"],n=t(i),l=["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"],s=t(l),c=["landscape","portrait","none","coarse","fine","on-demand","hover","interlace","progressive"],d=t(c),p=["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","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","user-select","vertical-align","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","volume","white-space","widows","width","will-change","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"],u=t(p),m=["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"],h=t(m),g=["font-family","src","unicode-range","font-variant","font-feature-settings","font-stretch","font-weight","font-style"],b=t(g),f=["additive-symbols","fallback","negative","pad","prefix","range","speak-as","suffix","symbols","system"],y=t(f),w=["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"],k=t(w),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","auto-flow","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","contents","content-box","context-menu","continuous","copy","counter","counters","cover","crop","cross","crosshair","currentcolor","cursive","cyclic","darken","dashed","decimal","decimal-leading-zero","default","default-button","dense","destination-atop","destination-in","destination-out","destination-over","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","opacity","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","scroll-position","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","system-ui","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","transform","translate","translate3d","translateX","translateY","translateZ","transparent","ultra-condensed","ultra-expanded","underline","unset","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"],x=t(v),z=o.concat(i).concat(l).concat(c).concat(p).concat(m).concat(w).concat(v);e.registerHelper("hintWords","css",z),e.defineMIME("text/css",{documentTypes:a,mediaTypes:n,mediaFeatures:s,mediaValueKeywords:d,propertyKeywords:u,nonStandardPropertyKeywords:h,fontProperties:b,counterDescriptors:y,colorKeywords:k,valueKeywords:x,tokenHooks:{"/":function(e,t){return e.eat("*")?(t.tokenize=r,r(e,t)):!1}},name:"css"}),e.defineMIME("text/x-scss",{mediaTypes:n,mediaFeatures:s,mediaValueKeywords:d,propertyKeywords:u,nonStandardPropertyKeywords:h,colorKeywords:k,valueKeywords:x,fontProperties:b,allowNested:!0,lineComment:"//",tokenHooks:{"/":function(e,t){return e.eat("/")?(e.skipToEnd(),["comment","comment"]):e.eat("*")?(t.tokenize=r,r(e,t)):["operator","operator"]},":":function(e){return e.match(/\s*\{/)?[null,"{"]:!1},$:function(e){return e.match(/^[\w-]+/),e.match(/^\s*:/,!1)?["variable-2","variable-definition"]:["variable-2","variable"]},"#":function(e){return e.eat("{")?[null,"interpolation"]:!1}},name:"css",helperType:"scss"}),e.defineMIME("text/x-less",{mediaTypes:n,mediaFeatures:s,mediaValueKeywords:d,propertyKeywords:u,nonStandardPropertyKeywords:h,colorKeywords:k,valueKeywords:x,fontProperties:b,allowNested:!0,lineComment:"//",tokenHooks:{"/":function(e,t){return e.eat("/")?(e.skipToEnd(),["comment","comment"]):e.eat("*")?(t.tokenize=r,r(e,t)):["operator","operator"]},"@":function(e){return e.eat("{")?[null,"interpolation"]:e.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/,!1)?!1:(e.eatWhile(/[\w\\\-]/),e.match(/^\s*:/,!1)?["variable-2","variable-definition"]:["variable-2","variable"])},"&":function(){return["atom","atom"]}},name:"css",helperType:"less"}),e.defineMIME("text/x-gss",{documentTypes:a,mediaTypes:n,mediaFeatures:s,propertyKeywords:u,nonStandardPropertyKeywords:h,fontProperties:b,counterDescriptors:y,colorKeywords:k,valueKeywords:x,supportsAtComponent:!0,tokenHooks:{"/":function(e,t){return e.eat("*")?(t.tokenize=r,r(e,t)):!1}},name:"css",helperType:"gss"})}); \ No newline at end of file diff --git a/js/lib/codemirror/htmlmixed.js b/js/lib/codemirror/htmlmixed.js index 27e5c28..85238d9 100644 --- a/js/lib/codemirror/htmlmixed.js +++ b/js/lib/codemirror/htmlmixed.js @@ -1 +1,1213 @@ -define(["./codemirror","./xml","./js","./css","css!./codemirror"],function(t){"use strict";function e(t,e,a){var n=t.current(),l=n.search(e);return l>-1?t.backUp(n.length-l):n.match(/<\/?$/)&&(t.backUp(n.length),t.match(e,!1)||t.match(n)),a}function a(t){var e=i[t];return e?e:i[t]=new RegExp("\\s+"+t+"\\s*=\\s*('|\")?([^'\"]+)('|\")?\\s*")}function n(t,e){var n=t.match(a(e));return n?/^\s*(.*?)\s*$/.exec(n[2])[1]:""}function l(t,e){return new RegExp((e?"^":"")+"","i")}function r(t,e){for(var a in t)for(var n=e[a]||(e[a]=[]),l=t[a],r=l.length-1;r>=0;r--)n.unshift(l[r])}function o(t,e){for(var a=0;a\s\/]/.test(n.current())&&(c=r.htmlState.tagName&&r.htmlState.tagName.toLowerCase())&&u.hasOwnProperty(c))r.inTag=c+" ";else if(r.inTag&&d&&/>$/.test(n.current())){var g=/^([\S]+) (.*)/.exec(r.inTag);r.inTag=null;var h=">"==n.current()&&o(u[g[1]],g[2]),f=t.getMode(a,h),p=l(g[1],!0),S=l(g[1],!1);r.token=function(t,a){return t.match(p,!1)?(a.token=i,a.localState=a.localMode=null,null):e(t,S,a.localMode.token(t,a.localState))},r.localMode=f,r.localState=t.startState(f,s.indent(r.htmlState,""))}else r.inTag&&(r.inTag+=n.current(),n.eol()&&(r.inTag+=" "));return m}var s=t.getMode(a,{name:"xml",htmlMode:!0,multilineTagIndentFactor:n.multilineTagIndentFactor,multilineTagIndentPastTag:n.multilineTagIndentPastTag}),u={},m=n&&n.tags,d=n&&n.scriptTypes;if(r(c,u),m&&r(m,u),d)for(var g=d.length-1;g>=0;g--)u.script.unshift(["type",d[g].matches,d[g].mode]);return{startState:function(){var e=t.startState(s);return{token:i,inTag:null,localMode:null,localState:null,htmlState:e}},copyState:function(e){var a;return e.localState&&(a=t.copyState(e.localMode,e.localState)),{token:e.token,inTag:e.inTag,localMode:e.localMode,localState:a,htmlState:t.copyState(s,e.htmlState)}},token:function(t,e){return e.token(t,e)},indent:function(e,a){return!e.localMode||/^\s*<\//.test(a)?s.indent(e.htmlState,a):e.localMode.indent?e.localMode.indent(e.localState,a):t.Pass},innerMode:function(t){return{state:t.localState||t.htmlState,mode:t.localMode||s}}}},"xml","javascript","css"),t.defineMIME("text/html","htmlmixed"),t}); \ No newline at end of file +define(["./codemirror", 'css!./codemirror'], function(CodeMirror) { + CodeMirror.defineMode("htmlmixed", function(config) { + var htmlMode = CodeMirror.getMode(config, { + name: "xml", + htmlMode: true + }); + var jsMode = CodeMirror.getMode(config, "javascript"); + var cssMode = CodeMirror.getMode(config, "css"); + + function html(stream, state) { + var style = htmlMode.token(stream, state.htmlState); + if (style == "tag" && stream.current() == ">" && state.htmlState.context) { + if (/^script$/i.test(state.htmlState.context.tagName)) { + state.token = javascript; + state.localState = jsMode.startState(htmlMode.indent(state.htmlState, "")); + } else if (/^style$/i.test(state.htmlState.context.tagName)) { + state.token = css; + state.localState = cssMode.startState(htmlMode.indent(state.htmlState, "")); + } + } + return style; + } + + function maybeBackup(stream, pat, style) { + var cur = stream.current(); + var close = cur.search(pat), + m; + if (close > -1) stream.backUp(cur.length - close); + else if (m = cur.match(/<\/?$/)) { + stream.backUp(cur.length); + if (!stream.match(pat, false)) stream.match(cur[0]); + } + return style; + } + + function javascript(stream, state) { + if (stream.match(/^<\/\s*script\s*>/i, false)) { + state.token = html; + state.localState = null; + return html(stream, state); + } + return maybeBackup(stream, /<\/\s*script\s*>/, jsMode.token(stream, state.localState)); + } + + function css(stream, state) { + if (stream.match(/^<\/\s*style\s*>/i, false)) { + state.token = html; + state.localState = null; + return html(stream, state); + } + return maybeBackup(stream, /<\/\s*style\s*>/, cssMode.token(stream, state.localState)); + } + return { + startState: function() { + var state = htmlMode.startState(); + return { + token: html, + localState: null, + mode: "html", + htmlState: state + }; + }, + copyState: function(state) { + if (state.localState) + var local = CodeMirror.copyState(state.token == css ? cssMode : jsMode, state.localState); + return { + token: state.token, + localState: local, + mode: state.mode, + htmlState: CodeMirror.copyState(htmlMode, state.htmlState) + }; + }, + token: function(stream, state) { + return state.token(stream, state); + }, + indent: function(state, textAfter) { + if (state.token == html || /^\s*<\//.test(textAfter)) + return htmlMode.indent(state.htmlState, textAfter); + else if (state.token == javascript) + return jsMode.indent(state.localState, textAfter); + else + return cssMode.indent(state.localState, textAfter); + }, + electricChars: "/{}:", + innerMode: function(state) { + var mode = state.token == html ? htmlMode : state.token == javascript ? jsMode : cssMode; + return { + state: state.localState || state.htmlState, + mode: mode + }; + } + }; + }, "xml", "javascript", "css"); + CodeMirror.defineMIME("text/html", "htmlmixed"); + + CodeMirror.defineMode("css", function(config) { + var indentUnit = config.indentUnit, + type; + var atMediaTypes = keySet(["all", "aural", "braille", "handheld", "print", "projection", "screen", "tty", "tv", "embossed"]); + var atMediaFeatures = keySet(["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"]); + var propertyKeywords = keySet(["align-content", "align-items", "align-self", "alignment-adjust", "alignment-baseline", "anchor-point", "animation", "animation-delay", "animation-direction", "animation-duration", "animation-iteration-count", "animation-name", "animation-play-state", "animation-timing-function", "appearance", "azimuth", "backface-visibility", "background", "background-attachment", "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", "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-cell", "grid-column", "grid-column-align", "grid-column-sizing", "grid-column-span", "grid-columns", "grid-flow", "grid-row", "grid-row-align", "grid-row-sizing", "grid-row-span", "grid-rows", "grid-template", "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", "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", "rendering-intent", "resize", "rest", "rest-after", "rest-before", "richness", "right", "rotation", "rotation-point", "ruby-align", "ruby-overhang", "ruby-position", "ruby-span", "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-shadow", "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"]); + var colorKeywords = keySet(["black", "silver", "gray", "white", "maroon", "red", "purple", "fuchsia", "green", "lime", "olive", "yellow", "navy", "blue", "teal", "aqua"]); + var valueKeywords = keySet(["above", "absolute", "activeborder", "activecaption", "afar", "after-white-space", "ahead", "alias", "all", "all-scroll", "alternate", "always", "amharic", "amharic-abegede", "antialiased", "appworkspace", "arabic-indic", "armenian", "asterisks", "auto", "avoid", "background", "backwards", "baseline", "below", "bidi-override", "binary", "bengali", "blink", "block", "block-axis", "bold", "bolder", "border", "border-box", "both", "bottom", "break-all", "break-word", "button", "button-bevel", "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "cambodian", "capitalize", "caps-lock-indicator", "caption", "captiontext", "caret", "cell", "center", "checkbox", "circle", "cjk-earthly-branch", "cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote", "col-resize", "collapse", "compact", "condensed", "contain", "content", "content-box", "context-menu", "continuous", "copy", "cover", "crop", "cross", "crosshair", "currentcolor", "cursive", "dashed", "decimal", "decimal-leading-zero", "default", "default-button", "destination-atop", "destination-in", "destination-out", "destination-over", "devanagari", "disc", "discard", "document", "dot-dash", "dot-dot-dash", "dotted", "double", "down", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out", "element", "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", "ew-resize", "expanded", "extra-condensed", "extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "footnotes", "forwards", "from", "geometricPrecision", "georgian", "graytext", "groove", "gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hebrew", "help", "hidden", "hide", "higher", "highlight", "highlighttext", "hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "icon", "ignore", "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite", "infobackground", "infotext", "inherit", "initial", "inline", "inline-axis", "inline-block", "inline-table", "inset", "inside", "intrinsic", "invert", "italic", "justify", "kannada", "katakana", "katakana-iroha", "khmer", "landscape", "lao", "large", "larger", "left", "level", "lighter", "line-through", "linear", "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", "malayalam", "match", "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", "myanmar", "n-resize", "narrower", "navy", "ne-resize", "nesw-resize", "no-close-quote", "no-drop", "no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap", "ns-resize", "nw-resize", "nwse-resize", "oblique", "octal", "open-quote", "optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset", "outside", "overlay", "overline", "padding", "padding-box", "painted", "paused", "persian", "plus-darker", "plus-lighter", "pointer", "portrait", "pre", "pre-line", "pre-wrap", "preserve-3d", "progress", "push-button", "radio", "read-only", "read-write", "read-write-plaintext-only", "relative", "repeat", "repeat-x", "repeat-y", "reset", "reverse", "rgb", "rgba", "ridge", "right", "round", "row-resize", "rtl", "run-in", "running", "s-resize", "sans-serif", "scroll", "scrollbar", "se-resize", "searchfield", "searchfield-cancel-button", "searchfield-decoration", "searchfield-results-button", "searchfield-results-decoration", "semi-condensed", "semi-expanded", "separate", "serif", "show", "sidama", "single", "skip-white-space", "slide", "slider-horizontal", "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow", "small", "small-caps", "small-caption", "smaller", "solid", "somali", "source-atop", "source-in", "source-out", "source-over", "space", "square", "square-button", "start", "static", "status-bar", "stretch", "stroke", "sub", "subpixel-antialiased", "super", "sw-resize", "table", "table-caption", "table-cell", "table-column", "table-column-group", "table-footer-group", "table-header-group", "table-row", "table-row-group", "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", "transparent", "ultra-condensed", "ultra-expanded", "underline", "up", "upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal", "upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url", "vertical", "vertical-text", "visible", "visibleFill", "visiblePainted", "visibleStroke", "visual", "w-resize", "wait", "wave", "white", "wider", "window", "windowframe", "windowtext", "x-large", "x-small", "xor", "xx-large", "xx-small", "yellow"]); + + function keySet(array) { + var keys = {}; + for (var i = 0; i < array.length; ++i) keys[array[i]] = true; + return keys; + } + + function ret(style, tp) { + type = tp; + return style; + } + + function tokenBase(stream, state) { + var ch = stream.next(); + if (ch == "@") { + stream.eatWhile(/[\w\\\-]/); + return ret("def", stream.current()); + } else if (ch == "/" && stream.eat("*")) { + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } else if (ch == "<" && stream.eat("!")) { + state.tokenize = tokenSGMLComment; + return tokenSGMLComment(stream, state); + } else if (ch == "=") ret(null, "compare"); + else if ((ch == "~" || ch == "|") && stream.eat("=")) return ret(null, "compare"); + else if (ch == "\"" || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } else if (ch == "#") { + stream.eatWhile(/[\w\\\-]/); + return ret("atom", "hash"); + } else if (ch == "!") { + stream.match(/^\s*\w*/); + return ret("keyword", "important"); + } else if (/\d/.test(ch)) { + stream.eatWhile(/[\w.%]/); + return ret("number", "unit"); + } else if (ch === "-") { + if (/\d/.test(stream.peek())) { + stream.eatWhile(/[\w.%]/); + return ret("number", "unit"); + } else if (stream.match(/^[^-]+-/)) { + return ret("meta", type); + } + } else if (/[,+>*\/]/.test(ch)) { + return ret(null, "select-op"); + } else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) { + return ret("qualifier", type); + } else if (ch == ":") { + return ret("operator", ch); + } else if (/[;{}\[\]\(\)]/.test(ch)) { + return ret(null, ch); + } else { + stream.eatWhile(/[\w\\\-]/); + return ret("property", "variable"); + } + } + + function tokenCComment(stream, state) { + var maybeEnd = false, + ch; + while ((ch = stream.next()) != null) { + if (maybeEnd && ch == "/") { + state.tokenize = tokenBase; + break; + } + maybeEnd = (ch == "*"); + } + return ret("comment", "comment"); + } + + function tokenSGMLComment(stream, state) { + var dashes = 0, + ch; + while ((ch = stream.next()) != null) { + if (dashes >= 2 && ch == ">") { + state.tokenize = tokenBase; + break; + } + dashes = (ch == "-") ? dashes + 1 : 0; + } + return ret("comment", "comment"); + } + + function tokenString(quote) { + return function(stream, state) { + var escaped = false, + ch; + while ((ch = stream.next()) != null) { + if (ch == quote && !escaped) + break; + escaped = !escaped && ch == "\\"; + } + if (!escaped) state.tokenize = tokenBase; + return ret("string", "string"); + }; + } + return { + startState: function(base) { + return { + tokenize: tokenBase, + baseIndent: base || 0, + stack: [] + }; + }, + token: function(stream, state) { + if (stream.eatSpace()) return null; + var style = state.tokenize(stream, state); + var context = state.stack[state.stack.length - 1]; + if (style == "property") { + if (context == "propertyValue") { + if (valueKeywords[stream.current()]) { + style = "string-2"; + } else if (colorKeywords[stream.current()]) { + style = "keyword"; + } else { + style = "variable-2"; + } + } else if (context == "rule") { + if (!propertyKeywords[stream.current()]) { + style += " error"; + } + } else if (!context || context == "@media{") { + style = "tag"; + } else if (context == "@media") { + if (atMediaTypes[stream.current()]) { + style = "attribute"; + } else if (/^(only|not)$/i.test(stream.current())) { + style = "keyword"; + } else if (stream.current().toLowerCase() == "and") { + style = "error"; + } else if (atMediaFeatures[stream.current()]) { + style = "error"; + } else { + style = "attribute error"; + } + } else if (context == "@mediaType") { + if (atMediaTypes[stream.current()]) { + style = "attribute"; + } else if (stream.current().toLowerCase() == "and") { + style = "operator"; + } else if (/^(only|not)$/i.test(stream.current())) { + style = "error"; + } else if (atMediaFeatures[stream.current()]) { + style = "error"; + } else { + style = "error"; + } + } else if (context == "@mediaType(") { + if (propertyKeywords[stream.current()]) {} else if (atMediaTypes[stream.current()]) { + style = "error"; + } else if (stream.current().toLowerCase() == "and") { + style = "operator"; + } else if (/^(only|not)$/i.test(stream.current())) { + style = "error"; + } else { + style += " error"; + } + } else { + style = "error"; + } + } else if (style == "atom") { + if (!context || context == "@media{") { + style = "builtin"; + } else if (context == "propertyValue") { + if (!/^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/.test(stream.current())) { + style += " error"; + } + } else { + style = "error"; + } + } else if (context == "@media" && type == "{") { + style = "error"; + } + if (type == "{") { + if (context == "@media" || context == "@mediaType") { + state.stack.pop(); + state.stack[state.stack.length - 1] = "@media{"; + } else state.stack.push("rule"); + } else if (type == "}") { + state.stack.pop(); + if (context == "propertyValue") state.stack.pop(); + } else if (type == "@media") state.stack.push("@media"); + else if (context == "@media" && /\b(keyword|attribute)\b/.test(style)) + state.stack.push("@mediaType"); + else if (context == "@mediaType" && stream.current() == ",") state.stack.pop(); + else if (context == "@mediaType" && type == "(") state.stack.push("@mediaType("); + else if (context == "@mediaType(" && type == ")") state.stack.pop(); + else if (context == "rule" && type == ":") state.stack.push("propertyValue"); + else if (context == "propertyValue" && type == ";") state.stack.pop(); + return style; + }, + indent: function(state, textAfter) { + var n = state.stack.length; + if (/^\}/.test(textAfter)) + n -= state.stack[state.stack.length - 1] == "propertyValue" ? 2 : 1; + return state.baseIndent + n * indentUnit; + }, + electricChars: "}" + }; + }); + CodeMirror.defineMIME("text/css", "css"); + + CodeMirror.defineMode("javascript", function(config, parserConfig) { + var indentUnit = config.indentUnit; + var jsonMode = parserConfig.json; + var isTS = parserConfig.typescript; + var keywords = function() { + function kw(type) { + return { + type: type, + style: "keyword" + }; + } + var A = kw("keyword a"), + B = kw("keyword b"), + C = kw("keyword c"); + var operator = kw("operator"), + atom = { + type: "atom", + style: "atom" + }; + var jsKeywords = { + "if": A, + "while": A, + "with": A, + "else": B, + "async": B, + "await": B, + "*": B, + "yield": B, + "do": B, + "try": B, + "finally": B, + "return": C, + "break": C, + "continue": C, + "new": C, + "delete": C, + "throw": C, + "var": kw("var"), + "const": kw("var"), + "let": kw("var"), + "function": kw("function"), + "require": kw("function"), + "interface": kw("interface"), + "class": kw("class"), + "extends": kw("extends"), + "constructor": kw("constructor"), + "public": kw("public"), + "private": kw("private"), + "protected": kw("protected"), + "static": kw("static"), + "super": kw("super"), + "catch": kw("catch"), + "for": kw("for"), + "switch": kw("switch"), + "case": kw("case"), + "default": kw("default"), + "in": operator, + "typeof": operator, + "instanceof": operator, + "true": atom, + "false": atom, + "null": atom, + "undefined": atom, + "NaN": atom, + "Infinity": atom + }; + if (isTS) { + var type = { + type: "variable", + style: "variable-3" + }; + var tsKeywords = { + "interface": kw("interface"), + "class": kw("class"), + "extends": kw("extends"), + "constructor": kw("constructor"), + "public": kw("public"), + "private": kw("private"), + "protected": kw("protected"), + "static": kw("static"), + "super": kw("super"), + "string": type, + "number": type, + "bool": type, + "any": type + }; + for (var attr in tsKeywords) { + jsKeywords[attr] = tsKeywords[attr]; + } + } + return jsKeywords; + }(); + var isOperatorChar = /[+\-*&%=<>!?|]/; + + function chain(stream, state, f) { + state.tokenize = f; + return f(stream, state); + } + + function nextUntilUnescaped(stream, end) { + var escaped = false, + next; + while ((next = stream.next()) != null) { + if (next == end && !escaped) + return false; + escaped = !escaped && next == "\\"; + } + return escaped; + } + var type, content; + + function ret(tp, style, cont) { + type = tp; + content = cont; + return style; + } + + function jsTokenBase(stream, state) { + var ch = stream.next(); + if (ch == '"' || ch == "'") + return chain(stream, state, jsTokenString(ch)); + else if (/[\[\]{}\(\),;\:\.]/.test(ch)) + return ret(ch); + else if (ch == "0" && stream.eat(/x/i)) { + stream.eatWhile(/[\da-f]/i); + return ret("number", "number"); + } else if (/\d/.test(ch) || ch == "-" && stream.eat(/\d/)) { + stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/); + return ret("number", "number"); + } else if (ch == "/") { + if (stream.eat("*")) { + return chain(stream, state, jsTokenComment); + } else if (stream.eat("/")) { + stream.skipToEnd(); + return ret("comment", "comment"); + } else if (state.lastType == "operator" || state.lastType == "keyword c" || /^[\[{}\(,;:]$/.test(state.lastType)) { + nextUntilUnescaped(stream, "/"); + stream.eatWhile(/[gimy]/); + return ret("regexp", "string-2"); + } else { + stream.eatWhile(isOperatorChar); + return ret("operator", null, stream.current()); + } + } else if (ch == "#") { + stream.skipToEnd(); + return ret("error", "error"); + } else if (isOperatorChar.test(ch)) { + stream.eatWhile(isOperatorChar); + return ret("operator", null, stream.current()); + } else { + stream.eatWhile(/[\w\$_]/); + var word = stream.current(), + known = keywords.propertyIsEnumerable(word) && keywords[word]; + return (known && state.lastType != ".") ? ret(known.type, known.style, word) : ret("variable", "variable", word); + } + } + + function jsTokenString(quote) { + return function(stream, state) { + if (!nextUntilUnescaped(stream, quote)) + state.tokenize = jsTokenBase; + return ret("string", "string"); + }; + } + + function jsTokenComment(stream, state) { + var maybeEnd = false, + ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize = jsTokenBase; + break; + } + maybeEnd = (ch == "*"); + } + return ret("comment", "comment"); + } + var atomicTypes = { + "atom": true, + "number": true, + "variable": true, + "string": true, + "regexp": true + }; + + function JSLexical(indented, column, type, align, prev, info) { + this.indented = indented; + this.column = column; + this.type = type; + this.prev = prev; + this.info = info; + if (align != null) this.align = align; + } + + function inScope(state, varname) { + for (var v = state.localVars; v; v = v.next) + if (v.name == varname) return true; + } + + function parseJS(state, style, type, content, stream) { + var cc = state.cc; + cx.state = state; + cx.stream = stream; + cx.marked = null, cx.cc = cc; + if (!state.lexical.hasOwnProperty("align")) + state.lexical.align = true; + while (true) { + var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement; + if (combinator(type, content)) { + while (cc.length && cc[cc.length - 1].lex) + cc.pop()(); + if (cx.marked) return cx.marked; + if (type == "variable" && inScope(state, content)) return "variable-2"; + return style; + } + } + } + var cx = { + state: null, + column: null, + marked: null, + cc: null + }; + + function pass() { + for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]); + } + + function cont() { + pass.apply(null, arguments); + return true; + } + + function register(varname) { + var state = cx.state; + if (state.context) { + cx.marked = "def"; + for (var v = state.localVars; v; v = v.next) + if (v.name == varname) return; + state.localVars = { + name: varname, + next: state.localVars + }; + } + } + var defaultVars = { + name: "this", + next: { + name: "arguments" + } + }; + + function pushcontext() { + cx.state.context = { + prev: cx.state.context, + vars: cx.state.localVars + }; + cx.state.localVars = defaultVars; + } + + function popcontext() { + cx.state.localVars = cx.state.context.vars; + cx.state.context = cx.state.context.prev; + } + + function pushlex(type, info) { + var result = function() { + var state = cx.state; + state.lexical = new JSLexical(state.indented, cx.stream.column(), type, null, state.lexical, info); + }; + result.lex = true; + return result; + } + + function poplex() { + var state = cx.state; + if (state.lexical.prev) { + if (state.lexical.type == ")") + state.indented = state.lexical.indented; + state.lexical = state.lexical.prev; + } + } + poplex.lex = true; + + function expect(wanted) { + return function expecting(type) { + if (type == wanted) return cont(); + else if (wanted == ";") return pass(); + else return cont(arguments.callee); + }; + } + + function statement(type) { + if (type == "var") return cont(pushlex("vardef"), vardef1, expect(";"), poplex); + if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex); + if (type == "keyword b") return cont(pushlex("form"), statement, poplex); + if (type == "{") return cont(pushlex("}"), block, poplex); + if (type == ";") return cont(); + if (type == "function") return cont(functiondef); + if (type == "for") return cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"), poplex, statement, poplex); + if (type == "variable") return cont(pushlex("stat"), maybelabel); + if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"), block, poplex, poplex); + if (type == "case") return cont(expression, expect(":")); + if (type == "default") return cont(expect(":")); + if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"), statement, poplex, popcontext); + return pass(pushlex("stat"), expression, expect(";"), poplex); + } + + function expression(type) { + if (atomicTypes.hasOwnProperty(type)) return cont(maybeoperator); + if (type == "function") return cont(functiondef); + if (type == "keyword c") return cont(maybeexpression); + if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeoperator); + if (type == "operator") return cont(expression); + if (type == "[") return cont(pushlex("]"), commasep(expression, "]"), poplex, maybeoperator); + if (type == "{") return cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeoperator); + return cont(); + } + + function maybeexpression(type) { + if (type.match(/[;\}\)\],]/)) return pass(); + return pass(expression); + } + + function maybeoperator(type, value) { + if (type == "operator" && /\+\+|--/.test(value)) return cont(maybeoperator); + if (type == "operator" && value == "?") return cont(expression, expect(":"), expression); + if (type == ";") return; + if (type == "(") return cont(pushlex(")"), commasep(expression, ")"), poplex, maybeoperator); + if (type == ".") return cont(property, maybeoperator); + if (type == "[") return cont(pushlex("]"), expression, expect("]"), poplex, maybeoperator); + } + + function maybelabel(type) { + if (type == ":") return cont(poplex, statement); + return pass(maybeoperator, expect(";"), poplex); + } + + function property(type) { + if (type == "variable") { + cx.marked = "property"; + return cont(); + } + } + + function objprop(type) { + if (type == "variable") cx.marked = "property"; + if (atomicTypes.hasOwnProperty(type)) return cont(expect(":"), expression); + } + + function commasep(what, end) { + function proceed(type) { + if (type == ",") return cont(what, proceed); + if (type == end) return cont(); + return cont(expect(end)); + } + return function commaSeparated(type) { + if (type == end) return cont(); + else return pass(what, proceed); + }; + } + + function block(type) { + if (type == "}") return cont(); + return pass(statement, block); + } + + function maybetype(type) { + if (type == ":") return cont(typedef); + return pass(); + } + + function typedef(type) { + if (type == "variable") { + cx.marked = "variable-3"; + return cont(); + } + return pass(); + } + + function vardef1(type, value) { + if (type == "variable") { + register(value); + return isTS ? cont(maybetype, vardef2) : cont(vardef2); + } + return pass(); + } + + function vardef2(type, value) { + if (value == "=") return cont(expression, vardef2); + if (type == ",") return cont(vardef1); + } + + function forspec1(type) { + if (type == "var") return cont(vardef1, expect(";"), forspec2); + if (type == ";") return cont(forspec2); + if (type == "variable") return cont(formaybein); + return cont(forspec2); + } + + function formaybein(type, value) { + if (value == "in") return cont(expression); + return cont(maybeoperator, forspec2); + } + + function forspec2(type, value) { + if (type == ";") return cont(forspec3); + if (value == "in") return cont(expression); + return cont(expression, expect(";"), forspec3); + } + + function forspec3(type) { + if (type != ")") cont(expression); + } + + function functiondef(type, value) { + if (type == "variable") { + register(value); + return cont(functiondef); + } + if (type == "(") return cont(pushlex(")"), pushcontext, commasep(funarg, ")"), poplex, statement, popcontext); + } + + function funarg(type, value) { + if (type == "variable") { + register(value); + return isTS ? cont(maybetype) : cont(); + } + } + return { + startState: function(basecolumn) { + return { + tokenize: jsTokenBase, + lastType: null, + cc: [], + lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), + localVars: parserConfig.localVars, + context: parserConfig.localVars && { + vars: parserConfig.localVars + }, + indented: 0 + }; + }, + token: function(stream, state) { + if (stream.sol()) { + if (!state.lexical.hasOwnProperty("align")) + state.lexical.align = false; + state.indented = stream.indentation(); + } + if (stream.eatSpace()) return null; + var style = state.tokenize(stream, state); + if (type == "comment") return style; + state.lastType = type; + return parseJS(state, style, type, content, stream); + }, + indent: function(state, textAfter) { + if (state.tokenize == jsTokenComment) return CodeMirror.Pass; + if (state.tokenize != jsTokenBase) return 0; + var firstChar = textAfter && textAfter.charAt(0), + lexical = state.lexical; + if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev; + var type = lexical.type, + closing = firstChar == type; + if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? 4 : 0); + else if (type == "form" && firstChar == "{") return lexical.indented; + else if (type == "form") return lexical.indented + indentUnit; + else if (type == "stat") + return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? indentUnit : 0); + else if (lexical.info == "switch" && !closing) + return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit); + else if (lexical.align) return lexical.column + (closing ? 0 : 1); + else return lexical.indented + (closing ? 0 : indentUnit); + }, + electricChars: ":{}", + jsonMode: jsonMode + }; + }); + CodeMirror.defineMIME("text/javascript", "javascript"); + CodeMirror.defineMIME("application/json", { + name: "javascript", + json: true + }); + CodeMirror.defineMIME("text/typescript", { + name: "javascript", + typescript: true + }); + CodeMirror.defineMIME("application/typescript", { + name: "javascript", + typescript: true + }); + + CodeMirror.defineMode("xml", function(config, parserConfig) { + var indentUnit = config.indentUnit; + var Kludges = parserConfig.htmlMode ? { + autoSelfClosers: { + 'area': true, + 'base': true, + 'br': true, + 'col': true, + 'command': true, + 'embed': true, + 'frame': true, + 'hr': true, + 'img': true, + 'input': true, + 'keygen': true, + 'link': true, + 'meta': true, + 'param': true, + 'source': true, + 'track': true, + 'wbr': true + }, + implicitlyClosed: { + 'dd': true, + 'li': true, + 'optgroup': true, + 'option': true, + 'p': true, + 'rp': true, + 'rt': true, + 'tbody': true, + 'td': true, + 'tfoot': true, + 'th': true, + 'tr': true + }, + contextGrabbers: { + 'dd': { + 'dd': true, + 'dt': true + }, + 'dt': { + 'dd': true, + 'dt': true + }, + 'li': { + 'li': true + }, + 'option': { + 'option': true, + 'optgroup': true + }, + 'optgroup': { + 'optgroup': true + }, + 'p': { + 'address': true, + 'article': true, + 'aside': true, + 'blockquote': true, + 'dir': true, + 'div': true, + 'dl': true, + 'fieldset': true, + 'footer': true, + 'form': true, + 'h1': true, + 'h2': true, + 'h3': true, + 'h4': true, + 'h5': true, + 'h6': true, + 'header': true, + 'hgroup': true, + 'hr': true, + 'menu': true, + 'nav': true, + 'ol': true, + 'p': true, + 'pre': true, + 'section': true, + 'table': true, + 'ul': true + }, + 'rp': { + 'rp': true, + 'rt': true + }, + 'rt': { + 'rp': true, + 'rt': true + }, + 'tbody': { + 'tbody': true, + 'tfoot': true + }, + 'td': { + 'td': true, + 'th': true + }, + 'tfoot': { + 'tbody': true + }, + 'th': { + 'td': true, + 'th': true + }, + 'thead': { + 'tbody': true, + 'tfoot': true + }, + 'tr': { + 'tr': true + } + }, + doNotIndent: { + "pre": true + }, + allowUnquoted: true, + allowMissing: true + } : { + autoSelfClosers: {}, + implicitlyClosed: {}, + contextGrabbers: {}, + doNotIndent: {}, + allowUnquoted: false, + allowMissing: false + }; + var alignCDATA = parserConfig.alignCDATA; + var tagName, type; + + function inText(stream, state) { + function chain(parser) { + state.tokenize = parser; + return parser(stream, state); + } + var ch = stream.next(); + if (ch == "<") { + if (stream.eat("!")) { + if (stream.eat("[")) { + if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>")); + else return null; + } else if (stream.match("--")) return chain(inBlock("comment", "-->")); + else if (stream.match("DOCTYPE", true, true)) { + stream.eatWhile(/[\w\._\-]/); + return chain(doctype(1)); + } else return null; + } else if (stream.eat("?")) { + stream.eatWhile(/[\w\._\-]/); + state.tokenize = inBlock("meta", "?>"); + return "meta"; + } else { + var isClose = stream.eat("/"); + tagName = ""; + var c; + while ((c = stream.eat(/[^\s\u00a0=<>\"\'\/?]/))) tagName += c; + if (!tagName) return "error"; + type = isClose ? "closeTag" : "openTag"; + state.tokenize = inTag; + return "tag"; + } + } else if (ch == "&") { + var ok; + if (stream.eat("#")) { + if (stream.eat("x")) { + ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";"); + } else { + ok = stream.eatWhile(/[\d]/) && stream.eat(";"); + } + } else { + ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";"); + } + return ok ? "atom" : "error"; + } else { + stream.eatWhile(/[^&<]/); + return null; + } + } + + function inTag(stream, state) { + var ch = stream.next(); + if (ch == ">" || (ch == "/" && stream.eat(">"))) { + state.tokenize = inText; + type = ch == ">" ? "endTag" : "selfcloseTag"; + return "tag"; + } else if (ch == "=") { + type = "equals"; + return null; + } else if (/[\'\"]/.test(ch)) { + state.tokenize = inAttribute(ch); + return state.tokenize(stream, state); + } else { + stream.eatWhile(/[^\s\u00a0=<>\"\']/); + return "word"; + } + } + + function inAttribute(quote) { + return function(stream, state) { + while (!stream.eol()) { + if (stream.next() == quote) { + state.tokenize = inTag; + break; + } + } + return "string"; + }; + } + + function inBlock(style, terminator) { + return function(stream, state) { + while (!stream.eol()) { + if (stream.match(terminator)) { + state.tokenize = inText; + break; + } + stream.next(); + } + return style; + }; + } + + function doctype(depth) { + return function(stream, state) { + var ch; + while ((ch = stream.next()) != null) { + if (ch == "<") { + state.tokenize = doctype(depth + 1); + return state.tokenize(stream, state); + } else if (ch == ">") { + if (depth == 1) { + state.tokenize = inText; + break; + } else { + state.tokenize = doctype(depth - 1); + return state.tokenize(stream, state); + } + } + } + return "meta"; + }; + } + var curState, setStyle; + + function pass() { + for (var i = arguments.length - 1; i >= 0; i--) curState.cc.push(arguments[i]); + } + + function cont() { + pass.apply(null, arguments); + return true; + } + + function pushContext(tagName, startOfLine) { + var noIndent = Kludges.doNotIndent.hasOwnProperty(tagName) || (curState.context && curState.context.noIndent); + curState.context = { + prev: curState.context, + tagName: tagName, + indent: curState.indented, + startOfLine: startOfLine, + noIndent: noIndent + }; + } + + function popContext() { + if (curState.context) curState.context = curState.context.prev; + } + + function element(type) { + if (type == "openTag") { + curState.tagName = tagName; + return cont(attributes, endtag(curState.startOfLine)); + } else if (type == "closeTag") { + var err = false; + if (curState.context) { + if (curState.context.tagName != tagName) { + if (Kludges.implicitlyClosed.hasOwnProperty(curState.context.tagName.toLowerCase())) { + popContext(); + } + err = !curState.context || curState.context.tagName != tagName; + } + } else { + err = true; + } + if (err) setStyle = "error"; + return cont(endclosetag(err)); + } + return cont(); + } + + function endtag(startOfLine) { + return function(type) { + if (type == "selfcloseTag" || (type == "endTag" && Kludges.autoSelfClosers.hasOwnProperty(curState.tagName.toLowerCase()))) { + maybePopContext(curState.tagName.toLowerCase()); + return cont(); + } + if (type == "endTag") { + maybePopContext(curState.tagName.toLowerCase()); + pushContext(curState.tagName, startOfLine); + return cont(); + } + return cont(); + }; + } + + function endclosetag(err) { + return function(type) { + if (err) setStyle = "error"; + if (type == "endTag") { + popContext(); + return cont(); + } + setStyle = "error"; + return cont(arguments.callee); + }; + } + + function maybePopContext(nextTagName) { + var parentTagName; + while (true) { + if (!curState.context) { + return; + } + parentTagName = curState.context.tagName.toLowerCase(); + if (!Kludges.contextGrabbers.hasOwnProperty(parentTagName) || !Kludges.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) { + return; + } + popContext(); + } + } + + function attributes(type) { + if (type == "word") { + setStyle = "attribute"; + return cont(attribute, attributes); + } + if (type == "endTag" || type == "selfcloseTag") return pass(); + setStyle = "error"; + return cont(attributes); + } + + function attribute(type) { + if (type == "equals") return cont(attvalue, attributes); + if (!Kludges.allowMissing) setStyle = "error"; + else if (type == "word") setStyle = "attribute"; + return (type == "endTag" || type == "selfcloseTag") ? pass() : cont(); + } + + function attvalue(type) { + if (type == "string") return cont(attvaluemaybe); + if (type == "word" && Kludges.allowUnquoted) { + setStyle = "string"; + return cont(); + } + setStyle = "error"; + return (type == "endTag" || type == "selfCloseTag") ? pass() : cont(); + } + + function attvaluemaybe(type) { + if (type == "string") return cont(attvaluemaybe); + else return pass(); + } + return { + startState: function() { + return { + tokenize: inText, + cc: [], + indented: 0, + startOfLine: true, + tagName: null, + context: null + }; + }, + token: function(stream, state) { + if (stream.sol()) { + state.startOfLine = true; + state.indented = stream.indentation(); + } + if (stream.eatSpace()) return null; + setStyle = type = tagName = null; + var style = state.tokenize(stream, state); + state.type = type; + if ((style || type) && style != "comment") { + curState = state; + while (true) { + var comb = state.cc.pop() || element; + if (comb(type || style)) break; + } + } + state.startOfLine = false; + return setStyle || style; + }, + indent: function(state, textAfter, fullLine) { + var context = state.context; + if ((state.tokenize != inTag && state.tokenize != inText) || context && context.noIndent) + return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0; + if (alignCDATA && /)$/.test(t.lastType)||"quasi"==t.lastType&&/\{\s*$/.test(e.string.slice(0,e.pos-(r||0)))}e.defineMode("javascript",function(r,n){function a(e){for(var t,r=!1,n=!1;null!=(t=e.next());){if(!r){if("/"==t&&!n)return;"["==t?n=!0:n&&"]"==t&&(n=!1)}r=!r&&"\\"==t}}function i(e,t,r){return Vt=e,Et=r,t}function o(e,r){var n=e.next();if('"'==n||"'"==n)return r.tokenize=c(n),r.tokenize(e,r);if("."==n&&e.match(/^\d+(?:[eE][+\-]?\d+)?/))return i("number","number");if("."==n&&e.match(".."))return i("spread","meta");if(/[\[\]{}\(\),;\:\.]/.test(n))return i(n);if("="==n&&e.eat(">"))return i("=>","operator");if("0"==n&&e.eat(/x/i))return e.eatWhile(/[\da-f]/i),i("number","number");if("0"==n&&e.eat(/o/i))return e.eatWhile(/[0-7]/i),i("number","number");if("0"==n&&e.eat(/b/i))return e.eatWhile(/[01]/i),i("number","number");if(/\d/.test(n))return e.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/),i("number","number");if("/"==n)return e.eat("*")?(r.tokenize=u,u(e,r)):e.eat("/")?(e.skipToEnd(),i("comment","comment")):t(e,r,1)?(a(e),e.match(/^\b(([gimyu])(?![gimyu]*\2))+\b/),i("regexp","string-2")):(e.eatWhile(qt),i("operator","operator",e.current()));if("`"==n)return r.tokenize=s,s(e,r);if("#"==n)return e.skipToEnd(),i("error","error");if(qt.test(n))return">"==n&&r.lexical&&">"==r.lexical.type||e.eatWhile(qt),i("operator","operator",e.current());if(Ot.test(n)){e.eatWhile(Ot);var o=e.current(),l=Wt.propertyIsEnumerable(o)&&Wt[o];return l&&"."!=r.lastType?i(l.type,l.style,o):i("variable","variable",o)}}function c(e){return function(t,r){var n,a=!1;if(At&&"@"==t.peek()&&t.match(Ct))return r.tokenize=o,i("jsonld-keyword","meta");for(;null!=(n=t.next())&&(n!=e||a);)a=!a&&"\\"==n;return a||(r.tokenize=o),i("string","string")}}function u(e,t){for(var r,n=!1;r=e.next();){if("/"==r&&n){t.tokenize=o;break}n="*"==r}return i("comment","comment")}function s(e,t){for(var r,n=!1;null!=(r=e.next());){if(!n&&("`"==r||"$"==r&&e.eat("{"))){t.tokenize=o;break}n=!n&&"\\"==r}return i("quasi","string-2",e.current())}function l(e,t){t.fatArrowAt&&(t.fatArrowAt=null);var r=e.string.indexOf("=>",e.start);if(!(0>r)){if($t){var n=/:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(e.string.slice(e.start,r));n&&(r=n.index)}for(var a=0,i=!1,o=r-1;o>=0;--o){var c=e.string.charAt(o),u=Pt.indexOf(c);if(u>=0&&3>u){if(!a){++o;break}if(0==--a){"("==c&&(i=!0);break}}else if(u>=3&&6>u)++a;else if(Ot.test(c))i=!0;else{if(/["'\/]/.test(c))return;if(i&&!a){++o;break}}}i&&!a&&(t.fatArrowAt=o)}}function f(e,t,r,n,a,i){this.indented=e,this.column=t,this.type=r,this.prev=a,this.info=i,null!=n&&(this.align=n)}function d(e,t){for(var r=e.localVars;r;r=r.next)if(r.name==t)return!0;for(var n=e.context;n;n=n.prev)for(var r=n.vars;r;r=r.next)if(r.name==t)return!0}function p(e,t,r,n,a){var i=e.cc;for(Nt.state=e,Nt.stream=a,Nt.marked=null,Nt.cc=i,Nt.style=t,e.lexical.hasOwnProperty("align")||(e.lexical.align=!0);;){var o=i.length?i.pop():Tt?j:w;if(o(r,n)){for(;i.length&&i[i.length-1].lex;)i.pop()();return Nt.marked?Nt.marked:"variable"==r&&d(e,n)?"variable-2":t}}}function m(){for(var e=arguments.length-1;e>=0;e--)Nt.cc.push(arguments[e])}function v(){return m.apply(null,arguments),!0}function y(e){function t(t){for(var r=t;r;r=r.next)if(r.name==e)return!0;return!1}var r=Nt.state;if(Nt.marked="def",r.context){if(t(r.localVars))return;r.localVars={name:e,next:r.localVars}}else{if(t(r.globalVars))return;n.globalVars&&(r.globalVars={name:e,next:r.globalVars})}}function k(){Nt.state.context={prev:Nt.state.context,vars:Nt.state.localVars},Nt.state.localVars=Bt}function b(){Nt.state.localVars=Nt.state.context.vars,Nt.state.context=Nt.state.context.prev}function x(e,t){var r=function(){var r=Nt.state,n=r.indented;if("stat"==r.lexical.type)n=r.lexical.indented;else for(var a=r.lexical;a&&")"==a.type&&a.align;a=a.prev)n=a.indented;r.lexical=new f(n,Nt.stream.column(),e,null,r.lexical,t)};return r.lex=!0,r}function h(){var e=Nt.state;e.lexical.prev&&(")"==e.lexical.type&&(e.indented=e.lexical.indented),e.lexical=e.lexical.prev)}function g(e){function t(r){return r==e?v():";"==e?m():v(t)}return t}function w(e,t){return"var"==e?v(x("vardef",t.length),Z,g(";"),h):"keyword a"==e?v(x("form"),V,w,h):"keyword b"==e?v(x("form"),w,h):"{"==e?v(x("}"),J,h):";"==e?v():"if"==e?("else"==Nt.state.lexical.info&&Nt.state.cc[Nt.state.cc.length-1]==h&&Nt.state.cc.pop()(),v(x("form"),V,w,h,nt)):"function"==e?v(st):"for"==e?v(x("form"),at,w,h):"variable"==e?v(x("stat"),N):"switch"==e?v(x("form"),V,x("}","switch"),g("{"),J,h,h):"case"==e?v(j,g(":")):"default"==e?v(g(":")):"catch"==e?v(x("form"),k,g("("),lt,g(")"),w,h,b):"class"==e?v(x("form"),dt,h):"export"==e?v(x("stat"),yt,h):"import"==e?v(x("stat"),bt,h):"module"==e?v(x("form"),_,x("}"),g("{"),J,h,h):"type"==e?v(L,g("operator"),L,g(";")):"async"==e?v(w):m(x("stat"),j,g(";"),h)}function j(e){return E(e,!1)}function M(e){return E(e,!0)}function V(e){return"("!=e?m():v(x(")"),j,g(")"),h)}function E(e,t){if(Nt.state.fatArrowAt==Nt.stream.start){var r=t?q:W;if("("==e)return v(k,x(")"),F(_,")"),h,g("=>"),r,b);if("variable"==e)return m(k,_,g("=>"),r,b)}var n=t?T:A;return St.hasOwnProperty(e)?v(n):"function"==e?v(st,n):"class"==e?v(x("form"),ft,h):"keyword c"==e||"async"==e?v(t?z:I):"("==e?v(x(")"),I,g(")"),h,n):"operator"==e||"spread"==e?v(t?M:j):"["==e?v(x("]"),jt,h,n):"{"==e?G(H,"}",null,n):"quasi"==e?m($,n):"new"==e?v(C(t)):v()}function I(e){return e.match(/[;\}\)\],]/)?m():m(j)}function z(e){return e.match(/[;\}\)\],]/)?m():m(M)}function A(e,t){return","==e?v(j):T(e,t,!1)}function T(e,t,r){var n=0==r?A:T,a=0==r?j:M;return"=>"==e?v(k,r?q:W,b):"operator"==e?/\+\+|--/.test(t)?v(n):"?"==t?v(j,g(":"),a):v(a):"quasi"==e?m($,n):";"!=e?"("==e?G(M,")","call",n):"."==e?v(B,n):"["==e?v(x("]"),I,g("]"),h,n):void 0:void 0}function $(e,t){return"quasi"!=e?m():"${"!=t.slice(t.length-2)?v($):v(j,O)}function O(e){return"}"==e?(Nt.marked="string-2",Nt.state.tokenize=s,v($)):void 0}function W(e){return l(Nt.stream,Nt.state),m("{"==e?w:j)}function q(e){return l(Nt.stream,Nt.state),m("{"==e?w:M)}function C(e){return function(t){return"."==t?v(e?S:P):m(e?M:j)}}function P(e,t){return"target"==t?(Nt.marked="keyword",v(A)):void 0}function S(e,t){return"target"==t?(Nt.marked="keyword",v(T)):void 0}function N(e){return":"==e?v(h,w):m(A,g(";"),h)}function B(e){return"variable"==e?(Nt.marked="property",v()):void 0}function H(e,t){return"async"==e?(Nt.marked="property",v(H)):"variable"==e||"keyword"==Nt.style?(Nt.marked="property",v("get"==t||"set"==t?U:D)):"number"==e||"string"==e?(Nt.marked=At?"property":Nt.style+" property",v(D)):"jsonld-keyword"==e?v(D):"modifier"==e?v(H):"["==e?v(j,g("]"),D):"spread"==e?v(j):":"==e?m(D):void 0}function U(e){return"variable"!=e?m(D):(Nt.marked="property",v(st))}function D(e){return":"==e?v(M):"("==e?m(st):void 0}function F(e,t,r){function n(a,i){if(r?r.indexOf(a)>-1:","==a){var o=Nt.state.lexical;return"call"==o.info&&(o.pos=(o.pos||0)+1),v(function(r,n){return r==t||n==t?m():m(e)},n)}return a==t||i==t?v():v(g(t))}return function(r,a){return r==t||a==t?v():m(e,n)}}function G(e,t,r){for(var n=3;n"==e?v(L):void 0}function R(e,t){return"variable"==e||"keyword"==Nt.style?(Nt.marked="property",v(R)):"?"==t?v(R):":"==e?v(L):void 0}function X(e){return"variable"==e?v(X):":"==e?v(L):void 0}function Y(e,t){return"<"==t?v(x(">"),F(L,">"),h,Y):"|"==t||"."==e?v(L):"["==e?v(g("]"),Y):void 0}function Z(){return m(_,K,tt,rt)}function _(e,t){return"modifier"==e?v(_):"variable"==e?(y(t),v()):"spread"==e?v(_):"["==e?G(_,"]"):"{"==e?G(et,"}"):void 0}function et(e,t){return"variable"!=e||Nt.stream.match(/^\s*:/,!1)?("variable"==e&&(Nt.marked="property"),"spread"==e?v(_):"}"==e?m():v(g(":"),_,tt)):(y(t),v(tt))}function tt(e,t){return"="==t?v(M):void 0}function rt(e){return","==e?v(Z):void 0}function nt(e,t){return"keyword b"==e&&"else"==t?v(x("form","else"),w,h):void 0}function at(e){return"("==e?v(x(")"),it,g(")"),h):void 0}function it(e){return"var"==e?v(Z,g(";"),ct):";"==e?v(ct):"variable"==e?v(ot):m(j,g(";"),ct)}function ot(e,t){return"in"==t||"of"==t?(Nt.marked="keyword",v(j)):v(A,ct)}function ct(e,t){return";"==e?v(ut):"in"==t||"of"==t?(Nt.marked="keyword",v(j)):m(j,g(";"),ut)}function ut(e){")"!=e&&v(j)}function st(e,t){return"*"==t?(Nt.marked="keyword",v(st)):"variable"==e?(y(t),v(st)):"("==e?v(k,x(")"),F(lt,")"),h,K,w,b):void 0}function lt(e){return"spread"==e?v(lt):m(_,K,tt)}function ft(e,t){return"variable"==e?dt(e,t):pt(e,t)}function dt(e,t){return"variable"==e?(y(t),v(pt)):void 0}function pt(e,t){return"<"==t?v(x(">"),F(L,">"),h,pt):"extends"==t||"implements"==t||$t&&","==e?v($t?L:j,pt):"{"==e?v(x("}"),mt,h):void 0}function mt(e,t){return"variable"==e||"keyword"==Nt.style?("async"==t||"static"==t||"get"==t||"set"==t||$t&&("public"==t||"private"==t||"protected"==t||"readonly"==t||"abstract"==t))&&Nt.stream.match(/^\s+[\w$\xa1-\uffff]/,!1)?(Nt.marked="keyword",v(mt)):(Nt.marked="property",v($t?vt:st,mt)):"["==e?v(j,g("]"),$t?vt:st,mt):"*"==t?(Nt.marked="keyword",v(mt)):";"==e?v(mt):"}"==e?v():void 0}function vt(e,t){return"?"==t?v(vt):":"==e?v(L,tt):"="==t?v(M):m(st)}function yt(e,t){return"*"==t?(Nt.marked="keyword",v(wt,g(";"))):"default"==t?(Nt.marked="keyword",v(j,g(";"))):"{"==e?v(F(kt,"}"),wt,g(";")):m(w)}function kt(e,t){return"as"==t?(Nt.marked="keyword",v(g("variable"))):"variable"==e?m(M,kt):void 0}function bt(e){return"string"==e?v():m(xt,ht,wt)}function xt(e,t){return"{"==e?G(xt,"}"):("variable"==e&&y(t),"*"==t&&(Nt.marked="keyword"),v(gt))}function ht(e){return","==e?v(xt,ht):void 0}function gt(e,t){return"as"==t?(Nt.marked="keyword",v(xt)):void 0}function wt(e,t){return"from"==t?(Nt.marked="keyword",v(j)):void 0}function jt(e){return"]"==e?v():m(F(M,"]"))}function Mt(e,t){return"operator"==e.lastType||","==e.lastType||qt.test(t.charAt(0))||/[,.]/.test(t.charAt(0))}var Vt,Et,It=r.indentUnit,zt=n.statementIndent,At=n.jsonld,Tt=n.json||At,$t=n.typescript,Ot=n.wordCharacters||/[\w$\xa1-\uffff]/,Wt=function(){function e(e){return{type:e,style:"keyword"}}var t=e("keyword a"),r=e("keyword b"),n=e("keyword c"),a=e("operator"),i={type:"atom",style:"atom"},o={"if":e("if"),"while":t,"with":t,"else":r,"do":r,"try":r,"finally":r,"return":n,"break":n,"continue":n,"new":e("new"),"delete":n,"throw":n,"debugger":n,"var":e("var"),"const":e("var"),let:e("var"),"function":e("function"),"catch":e("catch"),"for":e("for"),"switch":e("switch"),"case":e("case"),"default":e("default"),"in":a,"typeof":a,"instanceof":a,"true":i,"false":i,"null":i,undefined:i,NaN:i,Infinity:i,"this":e("this"),"class":e("class"),"super":e("atom"),"yield":n,"export":e("export"),"import":e("import"),"extends":n,await:n,async:e("async")};if($t){var c={type:"variable",style:"variable-3"},u={"interface":e("class"),"implements":n,namespace:n,module:e("module"),"enum":e("module"),type:e("type"),"public":e("modifier"),"private":e("modifier"),"protected":e("modifier"),"abstract":e("modifier"),as:a,string:c,number:c,"boolean":c,any:c};for(var s in u)o[s]=u[s]}return o}(),qt=/[+\-*&%=<>!?|~^]/,Ct=/^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/,Pt="([{}])",St={atom:!0,number:!0,variable:!0,string:!0,regexp:!0,"this":!0,"jsonld-keyword":!0},Nt={state:null,column:null,marked:null,cc:null},Bt={name:"this",next:{name:"arguments"}};return h.lex=!0,{startState:function(e){var t={tokenize:o,lastType:"sof",cc:[],lexical:new f((e||0)-It,0,"block",!1),localVars:n.localVars,context:n.localVars&&{vars:n.localVars},indented:e||0};return n.globalVars&&"object"==typeof n.globalVars&&(t.globalVars=n.globalVars),t},token:function(e,t){if(e.sol()&&(t.lexical.hasOwnProperty("align")||(t.lexical.align=!1),t.indented=e.indentation(),l(e,t)),t.tokenize!=u&&e.eatSpace())return null;var r=t.tokenize(e,t);return"comment"==Vt?r:(t.lastType="operator"!=Vt||"++"!=Et&&"--"!=Et?Vt:"incdec",p(t,r,Vt,Et,e))},indent:function(t,r){if(t.tokenize==u)return e.Pass;if(t.tokenize!=o)return 0;var a,i=r&&r.charAt(0),c=t.lexical;if(!/^\s*else\b/.test(r))for(var s=t.cc.length-1;s>=0;--s){var l=t.cc[s];if(l==h)c=c.prev;else if(l!=nt)break}for(;!("stat"!=c.type&&"form"!=c.type||"}"!=i&&(!(a=t.cc[t.cc.length-1])||a!=A&&a!=T||/^[,\.=+\-*:?[\(]/.test(r)));)c=c.prev;zt&&")"==c.type&&"stat"==c.prev.type&&(c=c.prev);var f=c.type,d=i==f;return"vardef"==f?c.indented+("operator"==t.lastType||","==t.lastType?c.info+1:0):"form"==f&&"{"==i?c.indented:"form"==f?c.indented+It:"stat"==f?c.indented+(Mt(t,r)?zt||It:0):"switch"!=c.info||d||0==n.doubleIndentSwitch?c.align?c.column+(d?0:1):c.indented+(d?0:It):c.indented+(/^(?:case|default)\b/.test(r)?It:2*It)},electricInput:/^\s*(?:case .*?:|default:|\{|\})$/,blockCommentStart:Tt?null:"/*",blockCommentEnd:Tt?null:"*/",lineComment:Tt?null:"//",fold:"brace",closeBrackets:"()[]{}''\"\"``",helperType:Tt?"json":"javascript",jsonldMode:At,jsonMode:Tt,expressionAllowed:t,skipExpression:function(e){var t=e.cc[e.cc.length-1];(t==j||t==M)&&e.cc.pop()}}}),e.registerHelper("wordChars","javascript",/[\w$]/),e.defineMIME("text/javascript","javascript"),e.defineMIME("text/ecmascript","javascript"),e.defineMIME("application/javascript","javascript"),e.defineMIME("application/x-javascript","javascript"),e.defineMIME("application/ecmascript","javascript"),e.defineMIME("application/json",{name:"javascript",json:!0}),e.defineMIME("application/x-json",{name:"javascript",json:!0}),e.defineMIME("application/ld+json",{name:"javascript",jsonld:!0}),e.defineMIME("text/typescript",{name:"javascript",typescript:!0}),e.defineMIME("application/typescript",{name:"javascript",typescript:!0})}); \ No newline at end of file diff --git a/js/lib/codemirror/xml.js b/js/lib/codemirror/xml.js deleted file mode 100644 index 6c5e137..0000000 --- a/js/lib/codemirror/xml.js +++ /dev/null @@ -1 +0,0 @@ -define(["./codemirror"],function(t){"use strict";var e={autoSelfClosers:{area:!0,base:!0,br:!0,col:!0,command:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0,menuitem:!0},implicitlyClosed:{dd:!0,li:!0,optgroup:!0,option:!0,p:!0,rp:!0,rt:!0,tbody:!0,td:!0,tfoot:!0,th:!0,tr:!0},contextGrabbers:{dd:{dd:!0,dt:!0},dt:{dd:!0,dt:!0},li:{li:!0},option:{option:!0,optgroup:!0},optgroup:{optgroup:!0},p:{address:!0,article:!0,aside:!0,blockquote:!0,dir:!0,div:!0,dl:!0,fieldset:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,menu:!0,nav:!0,ol:!0,p:!0,pre:!0,section:!0,table:!0,ul:!0},rp:{rp:!0,rt:!0},rt:{rp:!0,rt:!0},tbody:{tbody:!0,tfoot:!0},td:{td:!0,th:!0},tfoot:{tbody:!0},th:{td:!0,th:!0},thead:{tbody:!0,tfoot:!0},tr:{tr:!0}},doNotIndent:{pre:!0},allowUnquoted:!0,allowMissing:!0,caseFold:!0},n={autoSelfClosers:{},implicitlyClosed:{},contextGrabbers:{},doNotIndent:{},allowUnquoted:!1,allowMissing:!1,caseFold:!1};t.defineMode("xml",function(r,o){function a(t,e){function n(n){return e.tokenize=n,n(t,e)}var r=t.next();if("<"==r)return t.eat("!")?t.eat("[")?t.match("CDATA[")?n(u("atom","]]>")):null:t.match("--")?n(u("comment","-->")):t.match("DOCTYPE",!0,!0)?(t.eatWhile(/[\w\._\-]/),n(d(1))):null:t.eat("?")?(t.eatWhile(/[\w\._\-]/),e.tokenize=u("meta","?>"),"meta"):(I=t.eat("/")?"closeTag":"openTag",e.tokenize=i,"tag bracket");if("&"==r){var o;return o=t.eat("#")?t.eat("x")?t.eatWhile(/[a-fA-F\d]/)&&t.eat(";"):t.eatWhile(/[\d]/)&&t.eat(";"):t.eatWhile(/[\w\.\-:]/)&&t.eat(";"),o?"atom":"error"}return t.eatWhile(/[^&<]/),null}function i(t,e){var n=t.next();if(">"==n||"/"==n&&t.eat(">"))return e.tokenize=a,I=">"==n?"endTag":"selfcloseTag","tag bracket";if("="==n)return I="equals",null;if("<"==n){e.tokenize=a,e.state=m,e.tagName=e.tagStart=null;var r=e.tokenize(t,e);return r?r+" tag error":"tag error"}return/[\'\"]/.test(n)?(e.tokenize=l(n),e.stringStartCol=t.column(),e.tokenize(t,e)):(t.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/),"word")}function l(t){var e=function(e,n){for(;!e.eol();)if(e.next()==t){n.tokenize=i;break}return"string"};return e.isInAttribute=!0,e}function u(t,e){return function(n,r){for(;!n.eol();){if(n.match(e)){r.tokenize=a;break}n.next()}return t}}function d(t){return function(e,n){for(var r;null!=(r=e.next());){if("<"==r)return n.tokenize=d(t+1),n.tokenize(e,n);if(">"==r){if(1==t){n.tokenize=a;break}return n.tokenize=d(t-1),n.tokenize(e,n)}}return"meta"}}function c(t,e,n){this.prev=t.context,this.tagName=e,this.indent=t.indented,this.startOfLine=n,(y.doNotIndent.hasOwnProperty(e)||t.context&&t.context.noIndent)&&(this.noIndent=!0)}function s(t){t.context&&(t.context=t.context.prev)}function f(t,e){for(var n;;){if(!t.context)return;if(n=t.context.tagName,!y.contextGrabbers.hasOwnProperty(n)||!y.contextGrabbers[n].hasOwnProperty(e))return;s(t)}}function m(t,e,n){return"openTag"==t?(n.tagStart=e.column(),g):"closeTag"==t?h:m}function g(t,e,n){return"word"==t?(n.tagName=e.current(),C="tag",b):(C="error",g)}function h(t,e,n){if("word"==t){var r=e.current();return n.context&&n.context.tagName!=r&&y.implicitlyClosed.hasOwnProperty(n.context.tagName)&&s(n),n.context&&n.context.tagName==r||y.matchClosing===!1?(C="tag",p):(C="tag error",x)}return C="error",x}function p(t,e,n){return"endTag"!=t?(C="error",p):(s(n),m)}function x(t,e,n){return C="error",p(t,e,n)}function b(t,e,n){if("word"==t)return C="attribute",k;if("endTag"==t||"selfcloseTag"==t){var r=n.tagName,o=n.tagStart;return n.tagName=n.tagStart=null,"selfcloseTag"==t||y.autoSelfClosers.hasOwnProperty(r)?f(n,r):(f(n,r),n.context=new c(n,r,o==n.indented)),m}return C="error",b}function k(t,e,n){return"equals"==t?v:(y.allowMissing||(C="error"),b(t,e,n))}function v(t,e,n){return"string"==t?w:"word"==t&&y.allowUnquoted?(C="string",b):(C="error",b(t,e,n))}function w(t,e,n){return"string"==t?w:b(t,e,n)}var z=r.indentUnit,y={},N=o.htmlMode?e:n;for(var T in N)y[T]=N[T];for(var T in o)y[T]=o[T];var I,C;return a.isInText=!0,{startState:function(t){var e={tokenize:a,state:m,indented:t||0,tagName:null,tagStart:null,context:null};return null!=t&&(e.baseIndent=t),e},token:function(t,e){if(!e.tagName&&t.sol()&&(e.indented=t.indentation()),t.eatSpace())return null;I=null;var n=e.tokenize(t,e);return(n||I)&&"comment"!=n&&(C=null,e.state=e.state(I||n,t,e),C&&(n="error"==C?n+" error":C)),n},indent:function(e,n,r){var o=e.context;if(e.tokenize.isInAttribute)return e.tagStart==e.indented?e.stringStartCol+1:e.indented+z;if(o&&o.noIndent)return t.Pass;if(e.tokenize!=i&&e.tokenize!=a)return r?r.match(/^(\s*)/)[0].length:0;if(e.tagName)return y.multilineTagIndentPastTag!==!1?e.tagStart+e.tagName.length+2:e.tagStart+z*(y.multilineTagIndentFactor||1);if(y.alignCDATA&&/$/,blockCommentStart:"",configuration:y.htmlMode?"html":"xml",helperType:y.htmlMode?"html":"xml",skipAttribute:function(t){t.state==v&&(t.state=b)}}}),t.defineMIME("text/xml","xml"),t.defineMIME("application/xml","xml"),t.mimeModes.hasOwnProperty("text/html")||t.defineMIME("text/html",{name:"xml",htmlMode:!0})}); \ No newline at end of file diff --git a/js/lib/drag/drag.js b/js/lib/drag/drag.js index 927b06c..bb82598 100644 --- a/js/lib/drag/drag.js +++ b/js/lib/drag/drag.js @@ -35,8 +35,8 @@ define(['yua'], function(){ // 拖拽结束,且释放鼠标 binding.dragged = getBindingCallback(binding.element, 'data-dragged', binding.vmodels) - //获取是否允许溢出可视区 - binding.overflow = !!binding.element.dataset.overflow + //默认允许溢出可视区 + binding.overflow = true //方向,x轴, y轴, xy轴 binding.axis = 'xy' @@ -49,15 +49,11 @@ define(['yua'], function(){ binding.limit = false if(!!binding.element.dataset.limit) { binding.limit = binding.element.dataset.limit + //这里,只要不为空,除parent外,其他值都默认为window, 故"可溢出"为false + binding.overflow = false delete binding.element.dataset.limit } - // 如果不限制,则允许溢出 - if(binding.limit === false) { - binding.overflow = true - } - - delete binding.element.dataset.overflow delete binding.element.dataset.beforedrag delete binding.element.dataset.dragging delete binding.element.dataset.dragged @@ -68,7 +64,7 @@ define(['yua'], function(){ $drag = yua(this.element), $doc = yua(document), $target = null, - parent = null; + parentElem = null; // val值不为空时, 获取真正的拖动元素 // 仅从父级上找 @@ -82,7 +78,7 @@ define(['yua'], function(){ $target = yua(target); // 限制范围为parent时,获取父级元素 if(this.limit === 'parent'){ - parent = target.parentNode + parentElem = target.parentNode } @@ -129,16 +125,16 @@ define(['yua'], function(){ var limit = [0, wh - th, 0, ww - tw] if(_this.limit === 'parent') { - var pgcs = getComputedStyle(parent), + var pgcs = getComputedStyle(parentElem), pcst = pgcs.transform.replace(/matrix\((.*)\)/, '$1'), - poffset = yua(parent).offset(); + poffset = yua(parentElem).offset(); pcst = pcst !== 'none' ? pcst.split(', ') : [1,0,0,1,0,0] var pox = poffset.left - pcst[4] - bsl, poy = poffset.top - pcst[5] - bst; - limit = [poy, poy + parent.clientHeight - th, pox, pox + parent.clientWidth - tw] + limit = [poy, poy + parentElem.clientHeight - th, pox, pox + parentElem.clientWidth - tw] } var mvfn = $doc.bind('mousemove', function(ev){ diff --git a/js/lib/layer/layer-base.js b/js/lib/layer/layer-base.js new file mode 100644 index 0000000..f09d0ad --- /dev/null +++ b/js/lib/layer/layer-base.js @@ -0,0 +1,578 @@ +/** + * + * @authors yutent (yutent@doui.cc) + * @date 2016-09-21 01:36:29 + * + */ + +"use strict"; + + +define(['yua', 'lib/drag', 'css!./skin/def'], function(yua){ + + if(window.layer){ + return window.layer + } + var layerDom = {}, + layerObj = {}, + unique = null, //储存当前打开的1/2/3类型的弹窗 + lid = 0, + defconf = { + type: 1, // 弹窗类型 + skin: 'def', //默认主题 + icon: 1, //图标类型 + background: '#fff', + shade: true, //遮罩 + shadeClose: false, //遮罩点击关闭弹窗 + radius: '0px', //弹窗圆角半径 + area: ['auto', 'auto'], + title: '', //弹窗主标题(在工具栏上的) + menubar: true, //是否显示菜单栏 + content: '', // 弹窗的内容 + fixed: false, //是否固定不可拖拽 + offset: null, //弹窗出来时的坐标, 为数组,可有4个值,依次是 上右下左 + btns: ['确定', '取消'], //弹窗的2个按钮的文字 + yes: close, //确定按钮对应的回调 + no: close, //取消按钮对应的回调 + success: null //弹窗初始化完成时的回调 + }; + + function uuid(){ + return 'layer-' + (++lid) + } + + + function close(id){ + if(typeof id !== 'string' && typeof id !== 'number'){ + return console.error(new Error('要关闭的layer实例不存在')) + } + if(/^\$wrap\-/.test(id) || layerObj['$wrap-' + id]){ + + try { + id = (layerObj['$wrap-' + id] ? '$wrap-' : '') + id; + //未显示过,忽略 + if(!layerObj[id].show){ + return + } + layerObj[id].parentElem.replaceChild(layerObj[id].wrap, layerDom[id][1]) + unique = null + }catch(err){} + }else{ + try { + document.body.removeChild(layerDom[id][1]) + document.body.removeChild(layerDom[id][0]) + unique = null + }catch(err){} + + delete layerDom[id] + delete yua.vmodels[id] + } + + } + + function reapeat(str, num){ + var idx = 0, + result = '' + while(idx < num){ + result += str + idx++ + } + return result + } + + function fixOffset(val){ + if(!val && val !== 0){ + return 'auto' + }else{ + return val + } + } + + var __constructor = function(conf){ + if(conf){ + this.ready(conf).append().show() + } + }, + __layer = { + alert: function(msg, conf){ + if(typeof conf === 'function'){ + conf = {yes: conf} + }else if(typeof conf === 'object'){ + conf = conf + }else{ + conf = {} + } + conf.icon = 6 + conf.content = msg + return __layer.open(conf) + }, + confirm: function(msg, conf){ + if(typeof conf === 'function'){ + conf = {yes: conf} + }else if(typeof conf === 'object'){ + conf = conf + }else{ + conf = {} + } + conf.type = 2 + conf.icon = 8 + conf.content = msg + return __layer.open(conf) + }, + msg: function(msg, conf){ + if(typeof conf !== 'object'){ + var tmp = conf + conf = {timeout: 2500} + if(typeof tmp === 'number'){ + conf.icon = tmp + } + } + + if(!conf.hasOwnProperty('timeout')){ + conf.timeout = 2500 + } + + conf.specialMode = true;//特殊模式 + conf.content = '

' + msg + '

' + conf.type = 7 + conf.fixed = true + conf.shade = false + conf.menubar = false + conf.radius = '5px' + return __layer.open(conf) + }, + loading: function(style, time, cb){ + style = style >>> 0 + + if(typeof time === 'function'){ + cb = time; + time = 0 + } else{ + time = time >>> 0 + if(typeof cb !== 'function'){ + cb = yua.noop + } + } + return __layer.open({type: 6, load: style, yes: cb, timeout: time, menubar: false, background: 'none', fixed: true}) + }, + tips: function(msg, elem, conf){ + if(!(elem instanceof HTMLElement)){ + return console.error(new Error('tips类型必须指定一个目标容器')) + } + if(typeof conf !== 'object'){ + var tmp = conf + conf = {timeout: 2500} + if(typeof tmp === 'number'){ + conf.icon = tmp + } + } + if(!conf.hasOwnProperty('timeout')){ + conf.timeout = 2500 + } + if(!conf.background){ + conf.background = 'rgba(0,0,0,.5)' + } + if(!conf.color){ + conf.color = '#fff' + } + conf.$elem = elem + conf.content = msg + conf.type = 5; + conf.icon = 0; + conf.fixed = true; + conf.shade = false; + conf.menubar = false; + return __layer.open(conf) + }, + prompt: function(msg, callback){ + if(typeof callback !== 'function'){ + return console.error('argument [callback] requires a function, but ' + (typeof callback) + ' given') + } + var conf = { + type: 3, + icon: 7, + prompt: '', + title: msg, + content: '', + yes: function(id){ + callback(id, yua.vmodels[id].prompt) + } + } + return __layer.open(conf) + }, + use: function(skin, callback){ + require(['css!./skin/' + skin], callback) + }, + close: close, + open: function(conf){ + if(typeof conf === 'string'){ + conf = '$wrap-' + conf + if(!layerObj[conf]){ + throw new Error('layer实例不存在') + }else{ + //只能显示一个实例 + if(layerObj[conf].show){ + return + } + layerObj[conf].show = true + + if(!yua.vmodels[conf]){ + yua.define(layerObj[conf].obj.init) + } + + yua.scan(layerDom[conf][1]) + layerObj[conf].obj.show() + + layerObj[conf].parentElem.appendChild(layerDom[conf][1]) + layerObj[conf].parentElem.replaceChild(layerDom[conf][1], layerObj[conf].wrap) + } + }else{ + return new __constructor(conf).init.$id + } + }, + version: '0.0.1-base' + }; + + /*type: { // 弹窗类型对应的id值 + 1: 'alert', + 2: 'confirm', + 3: 'prompt', + 4: 'iframe', + 5: 'tips', + 6: 'loading', + 7: 'msg', + }*/ + __constructor.prototype = { + dot: { //loading的子元素数量 + 0: 4, + 1: 9, + 2: 2, + 3: 3, + 4: 2, + 5: 5, + 6: 5, + 7: 5 + }, + timeout: null, + create: function(){ + var layBox = document.createElement('div'), + coverBox = document.createElement('div'); + + coverBox.className = 'do-layer-cover type-' + this.init.type + // 允许点击遮罩关闭弹层时, 添加控制器 + if(this.init.shadeClose){ + coverBox.setAttribute(':controller', this.cInit.$id) + coverBox.setAttribute(':click', 'close(\'' + this.init.$id + '\')') + } + + layBox.className = 'do-layer skin-' + + this.init.skin + + (this.init.type === 5 && ' active' || '') + + ' type-' + + ((!this.init.specialMode && this.init.type === 7) ? 'unspecial' : this.init.type); + + //暂时隐藏,避免修正定位时,能看到闪一下 + layBox.style.visibility = 'hidden' + layBox.style.borderRadius = this.init.radius + + layBox.setAttribute(':controller', this.init.$id) + + //没有菜单栏, 且未禁止拖拽,则加上可拖拽属性 + if(!this.init.menubar && !this.init.fixed){ + layBox.setAttribute(':drag', '') + layBox.setAttribute('data-limit', 'window') + } + + //弹窗的宽高 + var boxcss = '' + if(this.init.area[0] !== 'auto'){ + boxcss += 'width: ' + this.init.area[0] + ';' + } + if(this.init.area[1] !== 'auto'){ + boxcss += 'height: ' + this.init.area[1] + ';' + } + + layBox.innerHTML = this.getMenubar() + + '
' + + this.getCont() + + '
' + + this.getBtns() + + (this.init.type === 5 && '' || '') + + return [this.init.shade ? coverBox : null, layBox] + }, + getCont: function(){ + if(this.init.type === 6){ + return this.getLoading(this.init.load) + }else{ + return this.getIcon() + + '
' + } + }, + getLoading: function(style){ + return '
' + + '' + + reapeat('', this.dot[style]) + + '' + + '
' + }, + //获取窗口导航条 + getMenubar: function(){ + var html = '' + if(this.init.menubar){ + html += '
' + + '
' + } + return html + }, + //获取窗口内容的图标 + getIcon: function(){ + if(this.init.icon === 0){ + return '' + } + if(this.init.type < 4 || this.init.type === 5 || this.init.specialMode){ + return '' + } + return '' + }, + // 获取窗口按钮 + getBtns: function(){ + if(this.init.type > 3){ + return '' + }else{ + var html = '
'; + if(this.init.type > 1){ + html += '' + + '' + }else{ + html += '' + } + html += '
' + + return html + } + }, + append: function(){ + //如果有已经打开的弹窗,则关闭 + if(unique){ + __layer.close(unique) + } + if(this.init.type < 4){ + unique = this.init.$id + } + layerDom[this.init.$id] = this.create() + if(layerDom[this.init.$id][0]){ + document.body.appendChild(layerDom[this.init.$id][0]) + //仅在允许点击遮罩时,初始化控制器,减少资源消耗 + if(this.init.shadeClose){ + yua.define(this.cInit) + yua.scan(layerDom[this.init.$id][0]) + } + } + + document.body.appendChild(layerDom[this.init.$id][1]) + yua.define(this.init) + yua.scan(layerDom[this.init.$id][1]) + return this + }, + show: function(){ + var _this = this; + + setTimeout(function(){ + var style = {visibility: '', background: _this.init.background}, + css = getComputedStyle(layerDom[_this.init.$id][1]); + + if(_this.init.type === 5){ + style.color = _this.init.color + + var $elem = yua(_this.init.$elem), + ew = $elem.innerWidth(), + ol = $elem.offset().left - document.body.scrollLeft, + ot = $elem.offset().top - document.body.scrollTop; + + style.left = ol + (ew * 0.7) + style.top = ot - parseInt(css.height) - 8 + + }else{ + if(_this.init.offset){ + style.top = fixOffset(_this.init.offset[0]) + style.right = fixOffset(_this.init.offset[1]) + style.bottom = fixOffset(_this.init.offset[2]) + style.left = fixOffset(_this.init.offset[3]) + }else{ + style = yua.mix(style, { + marginLeft: -parseInt(css.width) / 2, + marginTop: -parseInt(css.height) / 2, + }) + } + } + + yua(layerDom[_this.init.$id][1]).css(style) + + }, 4) + + + if(this.init.success && typeof this.init.success === 'function'){ + //弹窗成功的回调 + this.init.success(this.init.$id) + } + // loading类型,回调需要自动触发 + if(this.init.type > 3) { + //大于0自动触发超时关闭 + if(this.init.timeout > 0){ + clearTimeout(this.timeout) + this.timeout = setTimeout(function(){ + + clearTimeout(_this.timeout) + __layer.close(_this.init.$id) + + // 为loading类型时,自动关闭同时触发回调 + if(_this.init.type === 6){ + _this.init.yes(_this.init.$id) + } + + }, this.init.timeout) + + } else if(this.init.type === 6) { + // loading类型, 非自动关闭时, 主动触发回调 + this.init.yes(this.init.$id) + } + + } + + }, + ready: function(conf){ + this.init = yua.mix({}, defconf, conf) + if(!this.init.$id){ + this.init.$id = uuid(); + } + if(this.init.icon > 17){ + this.icon.icon = 17 + } + //base版没有iframe类型 + if(this.init.type === 4){ + this.icon.type = 7 + } + this.cInit = { + $id: this.init.$id + '-c', + close: this.init.shadeClose ? close : yua.noop + }; + return this + } + } + + + yua.directive('layer', { + priority: 1400, + init: function(binding){ + if(!binding.param){ + binding.element.style.display = 'none' + } + }, + update: function(val){ + if(!val){ + return console.error(new Error(':layer指令格式不正确或无效属性. [' + this.name + '="' + this.expr) + '"]') + } + + var _this = this, + init = Object.assign({}, this.element.dataset); + + if(!this.param){ + init.type = 7; + init.$id = '$wrap-' + val; + if(!init.hasOwnProperty('menubar')){ + init.menubar = false; + } + + var tmp = new __constructor().ready(init); + + tmp.init.content = this.element.cloneNode(true); + + layerObj[tmp.init.$id] = {obj: tmp, parentElem: this.element.parentNode, wrap: this.element, show: false}; + layerDom[tmp.init.$id] = tmp.create(); + }else if(this.param === 'tips'){ + var $elem = yua(this.element), + ew = $elem.innerWidth(), + ol = $elem.offset().left - document.body.scrollLeft, + ot = $elem.offset().top - document.body.scrollTop, + tipsBox = document.createElement('div'), + tipsArrow = document.createElement('i'), + tipsCont = document.createElement('div'); + + + tipsBox.className = 'do-layer skin-def type-5' + tipsBox.style.left = ol + (ew * 0.7) + 'px' + if(init.background){ + tipsBox.style.background = init.background + tipsArrow.style.borderTopColor = init.background + } + if(init.color){ + tipsBox.style.color = init.color + } + tipsCont.className = 'layer-content' + tipsCont.textContent = val + tipsArrow.className = 'arrow' + tipsBox.appendChild(tipsCont) + tipsBox.appendChild(tipsArrow) + + + + yua(document).bind('scroll', function(){ + ol = $elem.offset().left - document.body.scrollLeft; + ot = $elem.offset().top - document.body.scrollTop; + + tipsBox.style.left = ol + (ew * 0.7) + 'px' + tipsBox.style.top = (ot - tipsBox.offsetHeight - 8) + 'px' + }) + + $elem.bind('mouseenter', function(ev){ + _this.element.parentNode.appendChild(tipsBox) + clearTimeout(_this.showTime) + clearTimeout(_this.hideTime) + _this.showTime = setTimeout(function(){ + tipsBox.style.top = (ot - tipsBox.offsetHeight - 8) + 'px' + tipsBox.classList.add('active') + + }, 4) + + }) + $elem.bind('mouseleave', function(){ + _this.hideTime = setTimeout(function(){ + clearTimeout(_this.hideTime) + try{ + _this.element.parentNode.removeChild(tipsBox) + }catch(err){} + }, 150) + }) + } + } + }) + + + + window.layer = __layer + + return __layer + +}) \ No newline at end of file diff --git a/js/lib/layer/layer-full.js b/js/lib/layer/layer-full.js new file mode 100644 index 0000000..480e185 --- /dev/null +++ b/js/lib/layer/layer-full.js @@ -0,0 +1,578 @@ +/** + * + * @authors yutent (yutent@doui.cc) + * @date 2016-09-21 01:36:29 + * + */ + +"use strict"; + + +define(['yua', 'lib/drag', 'css!./skin/def'], function(yua){ + + + var layerDom = {}, + layerObj = {}, + unique = null, //储存当前打开的1/2/3类型的弹窗 + lid = 0, + defconf = { + type: 1, // 弹窗类型 + skin: 'def', //默认主题 + icon: 1, //图标类型 + background: '#fff', + shade: true, //遮罩 + shadeClose: false, //遮罩点击关闭弹窗 + radius: '0px', //弹窗圆角半径 + area: ['auto', 'auto'], + title: '', //弹窗主标题(在工具栏上的) + menubar: true, //是否显示菜单栏 + content: '', // 弹窗的内容 + fixed: false, //是否固定不可拖拽 + offset: null, //弹窗出来时的坐标, 为数组,可有4个值,依次是 上右下左 + btns: ['确定', '取消'], //弹窗的2个按钮的文字 + yes: close, //确定按钮对应的回调 + no: close, //取消按钮对应的回调 + success: null //弹窗初始化完成时的回调 + }; + + function uuid(){ + return 'layer-' + (++lid) + } + + + function close(id){ + if(typeof id !== 'string' && typeof id !== 'number'){ + return console.error(new Error('要关闭的layer实例不存在')) + } + if(/^\$wrap\-/.test(id) || layerObj['$wrap-' + id]){ + + try { + id = (layerObj['$wrap-' + id] ? '$wrap-' : '') + id; + //未显示过,忽略 + if(!layerObj[id].show){ + return + } + layerObj[id].parentElem.replaceChild(layerObj[id].wrap, layerDom[id][1]) + unique = null + }catch(err){} + }else{ + try { + document.body.removeChild(layerDom[id][1]) + document.body.removeChild(layerDom[id][0]) + unique = null + }catch(err){} + + delete layerDom[id] + delete yua.vmodels[id] + } + + } + + function reapeat(str, num){ + var idx = 0, + result = '' + while(idx < num){ + result += str + idx++ + } + return result + } + + function fixOffset(val){ + if(!val && val !== 0){ + return 'auto' + }else{ + return val + } + } + + var __constructor = function(conf){ + if(conf){ + this.ready(conf).append().show() + } + }, + __layer = { + alert: function(msg, conf){ + if(typeof conf === 'function'){ + conf = {yes: conf} + }else if(typeof conf === 'object'){ + conf = conf + }else{ + conf = {} + } + conf.icon = 6 + conf.content = msg + return __layer.open(conf) + }, + confirm: function(msg, conf){ + if(typeof conf === 'function'){ + conf = {yes: conf} + }else if(typeof conf === 'object'){ + conf = conf + }else{ + conf = {} + } + conf.type = 2 + conf.icon = 8 + conf.content = msg + return __layer.open(conf) + }, + msg: function(msg, conf){ + if(typeof conf !== 'object'){ + var tmp = conf + conf = {timeout: 2500} + if(typeof tmp === 'number'){ + conf.icon = tmp + } + } + + if(!conf.hasOwnProperty('timeout')){ + conf.timeout = 2500 + } + + conf.specialMode = true;//特殊模式 + conf.content = '

' + msg + '

' + conf.type = 7 + conf.fixed = true + conf.shade = false + conf.menubar = false + conf.radius = '5px' + return __layer.open(conf) + }, + loading: function(style, time, cb){ + style = style >>> 0 + + if(typeof time === 'function'){ + cb = time; + time = 0 + } else{ + time = time >>> 0 + if(typeof cb !== 'function'){ + cb = yua.noop + } + } + return __layer.open({type: 6, load: style, yes: cb, timeout: time, menubar: false, background: 'none', fixed: true}) + }, + tips: function(msg, elem, conf){ + if(!(elem instanceof HTMLElement)){ + return console.error(new Error('tips类型必须指定一个目标容器')) + } + if(typeof conf !== 'object'){ + var tmp = conf + conf = {timeout: 2500} + if(typeof tmp === 'number'){ + conf.icon = tmp + } + } + if(!conf.hasOwnProperty('timeout')){ + conf.timeout = 2500 + } + if(!conf.background){ + conf.background = 'rgba(0,0,0,.5)' + } + if(!conf.color){ + conf.color = '#fff' + } + conf.$elem = elem + conf.content = msg + conf.type = 5; + conf.icon = 0; + conf.fixed = true; + conf.shade = false; + conf.menubar = false; + return __layer.open(conf) + }, + prompt: function(msg, callback){ + if(typeof callback !== 'function'){ + return console.error('argument [callback] requires a function, but ' + (typeof callback) + ' given') + } + var conf = { + type: 3, + icon: 7, + prompt: '', + title: msg, + content: '', + yes: function(id){ + callback(id, yua.vmodels[id].prompt) + } + } + return __layer.open(conf) + }, + use: function(skin, callback){ + require(['css!./skin/' + skin], callback) + }, + close: close, + open: function(conf){ + if(typeof conf === 'string'){ + conf = '$wrap-' + conf + if(!layerObj[conf]){ + throw new Error('layer实例不存在') + }else{ + //只能显示一个实例 + if(layerObj[conf].show){ + return + } + layerObj[conf].show = true + + if(!yua.vmodels[conf]){ + yua.define(layerObj[conf].obj.init) + } + + yua.scan(layerDom[conf][1]) + layerObj[conf].obj.show() + + layerObj[conf].parentElem.appendChild(layerDom[conf][1]) + layerObj[conf].parentElem.replaceChild(layerDom[conf][1], layerObj[conf].wrap) + } + }else{ + return new __constructor(conf).init.$id + } + }, + version: '0.0.1-base' + }; + + /*type: { // 弹窗类型对应的id值 + 1: 'alert', + 2: 'confirm', + 3: 'prompt', + 4: 'iframe', + 5: 'tips', + 6: 'loading', + 7: 'msg', + }*/ + __constructor.prototype = { + dot: { //loading的子元素数量 + 0: 4, + 1: 9, + 2: 2, + 3: 3, + 4: 2, + 5: 5, + 6: 5, + 7: 5 + }, + timeout: null, + create: function(){ + var layBox = document.createElement('div'), + coverBox = document.createElement('div'); + + coverBox.className = 'do-layer-cover type-' + this.init.type + // 允许点击遮罩关闭弹层时, 添加控制器 + if(this.init.shadeClose){ + coverBox.setAttribute(':controller', this.cInit.$id) + coverBox.setAttribute(':click', 'close(\'' + this.init.$id + '\')') + } + + layBox.className = 'do-layer skin-' + + this.init.skin + + (this.init.type === 5 && ' active' || '') + + ' type-' + + ((!this.init.specialMode && this.init.type === 7) ? 'unspecial' : this.init.type); + + //暂时隐藏,避免修正定位时,能看到闪一下 + layBox.style.visibility = 'hidden' + layBox.style.borderRadius = this.init.radius + + layBox.setAttribute(':controller', this.init.$id) + + //没有菜单栏, 且未禁止拖拽,则加上可拖拽属性 + if(!this.init.menubar && !this.init.fixed){ + layBox.setAttribute(':drag', '') + layBox.setAttribute('data-limit', 'window') + } + + //弹窗的宽高 + var boxcss = '' + if(this.init.area[0] !== 'auto'){ + boxcss += 'width: ' + this.init.area[0] + ';' + } + if(this.init.area[1] !== 'auto'){ + boxcss += 'height: ' + this.init.area[1] + ';' + } + + layBox.innerHTML = this.getMenubar() + + '
' + + this.getCont() + + '
' + + this.getBtns() + + (this.init.type === 5 && '' || '') + + return [this.init.shade ? coverBox : null, layBox] + }, + getCont: function(){ + if(this.init.type === 6){ + return this.getLoading(this.init.load) + }else{ + return this.getIcon() + + '
' + } + }, + getLoading: function(style){ + return '
' + + '' + + reapeat('', this.dot[style]) + + '' + + '
' + }, + //获取窗口导航条 + getMenubar: function(){ + var html = '' + if(this.init.menubar){ + html += '
' + + '
' + } + return html + }, + //获取窗口内容的图标 + getIcon: function(){ + if(this.init.icon === 0){ + return '' + } + if(this.init.type < 4 || this.init.type === 5 || this.init.specialMode){ + return '' + } + return '' + }, + // 获取窗口按钮 + getBtns: function(){ + if(this.init.type > 3){ + return '' + }else{ + var html = '
'; + if(this.init.type > 1){ + html += '' + + '' + }else{ + html += '' + } + html += '
' + + return html + } + }, + append: function(){ + //如果有已经打开的弹窗,则关闭 + if(unique){ + __layer.close(unique) + } + if(this.init.type < 4){ + unique = this.init.$id + } + layerDom[this.init.$id] = this.create() + if(layerDom[this.init.$id][0]){ + document.body.appendChild(layerDom[this.init.$id][0]) + //仅在允许点击遮罩时,初始化控制器,减少资源消耗 + if(this.init.shadeClose){ + yua.define(this.cInit) + yua.scan(layerDom[this.init.$id][0]) + } + } + + document.body.appendChild(layerDom[this.init.$id][1]) + yua.define(this.init) + yua.scan(layerDom[this.init.$id][1]) + return this + }, + show: function(){ + var _this = this; + + setTimeout(function(){ + var style = {visibility: '', background: _this.init.background}, + css = getComputedStyle(layerDom[_this.init.$id][1]); + + if(_this.init.type === 5){ + style.color = _this.init.color + + var $elem = yua(_this.init.$elem), + ew = $elem.innerWidth(), + ol = $elem.offset().left - document.body.scrollLeft, + ot = $elem.offset().top - document.body.scrollTop; + + style.left = ol + (ew * 0.7) + style.top = ot - parseInt(css.height) - 8 + + }else{ + if(_this.init.offset){ + style.top = fixOffset(_this.init.offset[0]) + style.right = fixOffset(_this.init.offset[1]) + style.bottom = fixOffset(_this.init.offset[2]) + style.left = fixOffset(_this.init.offset[3]) + }else{ + style = yua.mix(style, { + marginLeft: -parseInt(css.width) / 2, + marginTop: -parseInt(css.height) / 2, + }) + } + } + + yua(layerDom[_this.init.$id][1]).css(style) + + }, 4) + + + if(this.init.success && typeof this.init.success === 'function'){ + //弹窗成功的回调 + this.init.success(this.init.$id) + } + // loading类型,回调需要自动触发 + if(this.init.type > 3) { + //大于0自动触发超时关闭 + if(this.init.timeout > 0){ + clearTimeout(this.timeout) + this.timeout = setTimeout(function(){ + + clearTimeout(_this.timeout) + __layer.close(_this.init.$id) + + // 为loading类型时,自动关闭同时触发回调 + if(_this.init.type === 6){ + _this.init.yes(_this.init.$id) + } + + }, this.init.timeout) + + } else if(this.init.type === 6) { + // loading类型, 非自动关闭时, 主动触发回调 + this.init.yes(this.init.$id) + } + + } + + }, + ready: function(conf){ + this.init = yua.mix({}, defconf, conf) + if(!this.init.$id){ + this.init.$id = uuid(); + } + if(this.init.icon > 17){ + this.icon.icon = 17 + } + //base版没有iframe类型 + if(this.init.type === 4){ + this.icon.type = 7 + } + this.cInit = { + $id: this.init.$id + '-c', + close: this.init.shadeClose ? close : yua.noop + }; + return this + } + } + + + yua.directive('layer', { + priority: 1400, + init: function(binding){ + if(!binding.param){ + binding.element.style.display = 'none' + } + }, + update: function(val){ + if(!val){ + return console.error(new Error(':layer指令格式不正确或无效属性. [' + this.name + '="' + this.expr) + '"]') + } + + var _this = this, + init = Object.assign({}, this.element.dataset); + + if(!this.param){ + init.type = 7; + init.$id = '$wrap-' + val; + if(!init.hasOwnProperty('menubar')){ + init.menubar = false; + } + + var tmp = new __constructor().ready(init); + + tmp.init.content = this.element.cloneNode(true); + + layerObj[tmp.init.$id] = {obj: tmp, parentElem: this.element.parentNode, wrap: this.element, show: false}; + layerDom[tmp.init.$id] = tmp.create(); + }else if(this.param === 'tips'){ + var $elem = yua(this.element), + ew = $elem.innerWidth(), + ol = $elem.offset().left - document.body.scrollLeft, + ot = $elem.offset().top - document.body.scrollTop, + tipsBox = document.createElement('div'), + tipsArrow = document.createElement('i'), + tipsCont = document.createElement('div'); + + + tipsBox.className = 'do-layer skin-def type-5' + tipsBox.style.left = ol + (ew * 0.7) + 'px' + if(init.background){ + tipsBox.style.background = init.background + tipsArrow.style.borderTopColor = init.background + } + if(init.color){ + tipsBox.style.color = init.color + } + tipsCont.className = 'layer-content' + tipsCont.textContent = val + tipsArrow.className = 'arrow' + tipsBox.appendChild(tipsCont) + tipsBox.appendChild(tipsArrow) + + + + yua(document).bind('scroll', function(){ + ol = $elem.offset().left - document.body.scrollLeft; + ot = $elem.offset().top - document.body.scrollTop; + + tipsBox.style.left = ol + (ew * 0.7) + 'px' + tipsBox.style.top = (ot - tipsBox.offsetHeight - 8) + 'px' + }) + + $elem.bind('mouseenter', function(ev){ + _this.element.parentNode.appendChild(tipsBox) + clearTimeout(_this.showTime) + clearTimeout(_this.hideTime) + _this.showTime = setTimeout(function(){ + tipsBox.style.top = (ot - tipsBox.offsetHeight - 8) + 'px' + tipsBox.classList.add('active') + + }, 4) + + }) + $elem.bind('mouseleave', function(){ + _this.hideTime = setTimeout(function(){ + clearTimeout(_this.hideTime) + try{ + _this.element.parentNode.removeChild(tipsBox) + }catch(err){} + }, 150) + }) + } + } + }) + + + + if(!window.layer) + window.layer = __layer + + + return __layer + +}) \ No newline at end of file diff --git a/js/lib/layer/layer-mobile.js b/js/lib/layer/layer-mobile.js new file mode 100644 index 0000000..480e185 --- /dev/null +++ b/js/lib/layer/layer-mobile.js @@ -0,0 +1,578 @@ +/** + * + * @authors yutent (yutent@doui.cc) + * @date 2016-09-21 01:36:29 + * + */ + +"use strict"; + + +define(['yua', 'lib/drag', 'css!./skin/def'], function(yua){ + + + var layerDom = {}, + layerObj = {}, + unique = null, //储存当前打开的1/2/3类型的弹窗 + lid = 0, + defconf = { + type: 1, // 弹窗类型 + skin: 'def', //默认主题 + icon: 1, //图标类型 + background: '#fff', + shade: true, //遮罩 + shadeClose: false, //遮罩点击关闭弹窗 + radius: '0px', //弹窗圆角半径 + area: ['auto', 'auto'], + title: '', //弹窗主标题(在工具栏上的) + menubar: true, //是否显示菜单栏 + content: '', // 弹窗的内容 + fixed: false, //是否固定不可拖拽 + offset: null, //弹窗出来时的坐标, 为数组,可有4个值,依次是 上右下左 + btns: ['确定', '取消'], //弹窗的2个按钮的文字 + yes: close, //确定按钮对应的回调 + no: close, //取消按钮对应的回调 + success: null //弹窗初始化完成时的回调 + }; + + function uuid(){ + return 'layer-' + (++lid) + } + + + function close(id){ + if(typeof id !== 'string' && typeof id !== 'number'){ + return console.error(new Error('要关闭的layer实例不存在')) + } + if(/^\$wrap\-/.test(id) || layerObj['$wrap-' + id]){ + + try { + id = (layerObj['$wrap-' + id] ? '$wrap-' : '') + id; + //未显示过,忽略 + if(!layerObj[id].show){ + return + } + layerObj[id].parentElem.replaceChild(layerObj[id].wrap, layerDom[id][1]) + unique = null + }catch(err){} + }else{ + try { + document.body.removeChild(layerDom[id][1]) + document.body.removeChild(layerDom[id][0]) + unique = null + }catch(err){} + + delete layerDom[id] + delete yua.vmodels[id] + } + + } + + function reapeat(str, num){ + var idx = 0, + result = '' + while(idx < num){ + result += str + idx++ + } + return result + } + + function fixOffset(val){ + if(!val && val !== 0){ + return 'auto' + }else{ + return val + } + } + + var __constructor = function(conf){ + if(conf){ + this.ready(conf).append().show() + } + }, + __layer = { + alert: function(msg, conf){ + if(typeof conf === 'function'){ + conf = {yes: conf} + }else if(typeof conf === 'object'){ + conf = conf + }else{ + conf = {} + } + conf.icon = 6 + conf.content = msg + return __layer.open(conf) + }, + confirm: function(msg, conf){ + if(typeof conf === 'function'){ + conf = {yes: conf} + }else if(typeof conf === 'object'){ + conf = conf + }else{ + conf = {} + } + conf.type = 2 + conf.icon = 8 + conf.content = msg + return __layer.open(conf) + }, + msg: function(msg, conf){ + if(typeof conf !== 'object'){ + var tmp = conf + conf = {timeout: 2500} + if(typeof tmp === 'number'){ + conf.icon = tmp + } + } + + if(!conf.hasOwnProperty('timeout')){ + conf.timeout = 2500 + } + + conf.specialMode = true;//特殊模式 + conf.content = '

' + msg + '

' + conf.type = 7 + conf.fixed = true + conf.shade = false + conf.menubar = false + conf.radius = '5px' + return __layer.open(conf) + }, + loading: function(style, time, cb){ + style = style >>> 0 + + if(typeof time === 'function'){ + cb = time; + time = 0 + } else{ + time = time >>> 0 + if(typeof cb !== 'function'){ + cb = yua.noop + } + } + return __layer.open({type: 6, load: style, yes: cb, timeout: time, menubar: false, background: 'none', fixed: true}) + }, + tips: function(msg, elem, conf){ + if(!(elem instanceof HTMLElement)){ + return console.error(new Error('tips类型必须指定一个目标容器')) + } + if(typeof conf !== 'object'){ + var tmp = conf + conf = {timeout: 2500} + if(typeof tmp === 'number'){ + conf.icon = tmp + } + } + if(!conf.hasOwnProperty('timeout')){ + conf.timeout = 2500 + } + if(!conf.background){ + conf.background = 'rgba(0,0,0,.5)' + } + if(!conf.color){ + conf.color = '#fff' + } + conf.$elem = elem + conf.content = msg + conf.type = 5; + conf.icon = 0; + conf.fixed = true; + conf.shade = false; + conf.menubar = false; + return __layer.open(conf) + }, + prompt: function(msg, callback){ + if(typeof callback !== 'function'){ + return console.error('argument [callback] requires a function, but ' + (typeof callback) + ' given') + } + var conf = { + type: 3, + icon: 7, + prompt: '', + title: msg, + content: '', + yes: function(id){ + callback(id, yua.vmodels[id].prompt) + } + } + return __layer.open(conf) + }, + use: function(skin, callback){ + require(['css!./skin/' + skin], callback) + }, + close: close, + open: function(conf){ + if(typeof conf === 'string'){ + conf = '$wrap-' + conf + if(!layerObj[conf]){ + throw new Error('layer实例不存在') + }else{ + //只能显示一个实例 + if(layerObj[conf].show){ + return + } + layerObj[conf].show = true + + if(!yua.vmodels[conf]){ + yua.define(layerObj[conf].obj.init) + } + + yua.scan(layerDom[conf][1]) + layerObj[conf].obj.show() + + layerObj[conf].parentElem.appendChild(layerDom[conf][1]) + layerObj[conf].parentElem.replaceChild(layerDom[conf][1], layerObj[conf].wrap) + } + }else{ + return new __constructor(conf).init.$id + } + }, + version: '0.0.1-base' + }; + + /*type: { // 弹窗类型对应的id值 + 1: 'alert', + 2: 'confirm', + 3: 'prompt', + 4: 'iframe', + 5: 'tips', + 6: 'loading', + 7: 'msg', + }*/ + __constructor.prototype = { + dot: { //loading的子元素数量 + 0: 4, + 1: 9, + 2: 2, + 3: 3, + 4: 2, + 5: 5, + 6: 5, + 7: 5 + }, + timeout: null, + create: function(){ + var layBox = document.createElement('div'), + coverBox = document.createElement('div'); + + coverBox.className = 'do-layer-cover type-' + this.init.type + // 允许点击遮罩关闭弹层时, 添加控制器 + if(this.init.shadeClose){ + coverBox.setAttribute(':controller', this.cInit.$id) + coverBox.setAttribute(':click', 'close(\'' + this.init.$id + '\')') + } + + layBox.className = 'do-layer skin-' + + this.init.skin + + (this.init.type === 5 && ' active' || '') + + ' type-' + + ((!this.init.specialMode && this.init.type === 7) ? 'unspecial' : this.init.type); + + //暂时隐藏,避免修正定位时,能看到闪一下 + layBox.style.visibility = 'hidden' + layBox.style.borderRadius = this.init.radius + + layBox.setAttribute(':controller', this.init.$id) + + //没有菜单栏, 且未禁止拖拽,则加上可拖拽属性 + if(!this.init.menubar && !this.init.fixed){ + layBox.setAttribute(':drag', '') + layBox.setAttribute('data-limit', 'window') + } + + //弹窗的宽高 + var boxcss = '' + if(this.init.area[0] !== 'auto'){ + boxcss += 'width: ' + this.init.area[0] + ';' + } + if(this.init.area[1] !== 'auto'){ + boxcss += 'height: ' + this.init.area[1] + ';' + } + + layBox.innerHTML = this.getMenubar() + + '
' + + this.getCont() + + '
' + + this.getBtns() + + (this.init.type === 5 && '' || '') + + return [this.init.shade ? coverBox : null, layBox] + }, + getCont: function(){ + if(this.init.type === 6){ + return this.getLoading(this.init.load) + }else{ + return this.getIcon() + + '
' + } + }, + getLoading: function(style){ + return '
' + + '' + + reapeat('', this.dot[style]) + + '' + + '
' + }, + //获取窗口导航条 + getMenubar: function(){ + var html = '' + if(this.init.menubar){ + html += '
' + + '
' + } + return html + }, + //获取窗口内容的图标 + getIcon: function(){ + if(this.init.icon === 0){ + return '' + } + if(this.init.type < 4 || this.init.type === 5 || this.init.specialMode){ + return '' + } + return '' + }, + // 获取窗口按钮 + getBtns: function(){ + if(this.init.type > 3){ + return '' + }else{ + var html = '
'; + if(this.init.type > 1){ + html += '' + + '' + }else{ + html += '' + } + html += '
' + + return html + } + }, + append: function(){ + //如果有已经打开的弹窗,则关闭 + if(unique){ + __layer.close(unique) + } + if(this.init.type < 4){ + unique = this.init.$id + } + layerDom[this.init.$id] = this.create() + if(layerDom[this.init.$id][0]){ + document.body.appendChild(layerDom[this.init.$id][0]) + //仅在允许点击遮罩时,初始化控制器,减少资源消耗 + if(this.init.shadeClose){ + yua.define(this.cInit) + yua.scan(layerDom[this.init.$id][0]) + } + } + + document.body.appendChild(layerDom[this.init.$id][1]) + yua.define(this.init) + yua.scan(layerDom[this.init.$id][1]) + return this + }, + show: function(){ + var _this = this; + + setTimeout(function(){ + var style = {visibility: '', background: _this.init.background}, + css = getComputedStyle(layerDom[_this.init.$id][1]); + + if(_this.init.type === 5){ + style.color = _this.init.color + + var $elem = yua(_this.init.$elem), + ew = $elem.innerWidth(), + ol = $elem.offset().left - document.body.scrollLeft, + ot = $elem.offset().top - document.body.scrollTop; + + style.left = ol + (ew * 0.7) + style.top = ot - parseInt(css.height) - 8 + + }else{ + if(_this.init.offset){ + style.top = fixOffset(_this.init.offset[0]) + style.right = fixOffset(_this.init.offset[1]) + style.bottom = fixOffset(_this.init.offset[2]) + style.left = fixOffset(_this.init.offset[3]) + }else{ + style = yua.mix(style, { + marginLeft: -parseInt(css.width) / 2, + marginTop: -parseInt(css.height) / 2, + }) + } + } + + yua(layerDom[_this.init.$id][1]).css(style) + + }, 4) + + + if(this.init.success && typeof this.init.success === 'function'){ + //弹窗成功的回调 + this.init.success(this.init.$id) + } + // loading类型,回调需要自动触发 + if(this.init.type > 3) { + //大于0自动触发超时关闭 + if(this.init.timeout > 0){ + clearTimeout(this.timeout) + this.timeout = setTimeout(function(){ + + clearTimeout(_this.timeout) + __layer.close(_this.init.$id) + + // 为loading类型时,自动关闭同时触发回调 + if(_this.init.type === 6){ + _this.init.yes(_this.init.$id) + } + + }, this.init.timeout) + + } else if(this.init.type === 6) { + // loading类型, 非自动关闭时, 主动触发回调 + this.init.yes(this.init.$id) + } + + } + + }, + ready: function(conf){ + this.init = yua.mix({}, defconf, conf) + if(!this.init.$id){ + this.init.$id = uuid(); + } + if(this.init.icon > 17){ + this.icon.icon = 17 + } + //base版没有iframe类型 + if(this.init.type === 4){ + this.icon.type = 7 + } + this.cInit = { + $id: this.init.$id + '-c', + close: this.init.shadeClose ? close : yua.noop + }; + return this + } + } + + + yua.directive('layer', { + priority: 1400, + init: function(binding){ + if(!binding.param){ + binding.element.style.display = 'none' + } + }, + update: function(val){ + if(!val){ + return console.error(new Error(':layer指令格式不正确或无效属性. [' + this.name + '="' + this.expr) + '"]') + } + + var _this = this, + init = Object.assign({}, this.element.dataset); + + if(!this.param){ + init.type = 7; + init.$id = '$wrap-' + val; + if(!init.hasOwnProperty('menubar')){ + init.menubar = false; + } + + var tmp = new __constructor().ready(init); + + tmp.init.content = this.element.cloneNode(true); + + layerObj[tmp.init.$id] = {obj: tmp, parentElem: this.element.parentNode, wrap: this.element, show: false}; + layerDom[tmp.init.$id] = tmp.create(); + }else if(this.param === 'tips'){ + var $elem = yua(this.element), + ew = $elem.innerWidth(), + ol = $elem.offset().left - document.body.scrollLeft, + ot = $elem.offset().top - document.body.scrollTop, + tipsBox = document.createElement('div'), + tipsArrow = document.createElement('i'), + tipsCont = document.createElement('div'); + + + tipsBox.className = 'do-layer skin-def type-5' + tipsBox.style.left = ol + (ew * 0.7) + 'px' + if(init.background){ + tipsBox.style.background = init.background + tipsArrow.style.borderTopColor = init.background + } + if(init.color){ + tipsBox.style.color = init.color + } + tipsCont.className = 'layer-content' + tipsCont.textContent = val + tipsArrow.className = 'arrow' + tipsBox.appendChild(tipsCont) + tipsBox.appendChild(tipsArrow) + + + + yua(document).bind('scroll', function(){ + ol = $elem.offset().left - document.body.scrollLeft; + ot = $elem.offset().top - document.body.scrollTop; + + tipsBox.style.left = ol + (ew * 0.7) + 'px' + tipsBox.style.top = (ot - tipsBox.offsetHeight - 8) + 'px' + }) + + $elem.bind('mouseenter', function(ev){ + _this.element.parentNode.appendChild(tipsBox) + clearTimeout(_this.showTime) + clearTimeout(_this.hideTime) + _this.showTime = setTimeout(function(){ + tipsBox.style.top = (ot - tipsBox.offsetHeight - 8) + 'px' + tipsBox.classList.add('active') + + }, 4) + + }) + $elem.bind('mouseleave', function(){ + _this.hideTime = setTimeout(function(){ + clearTimeout(_this.hideTime) + try{ + _this.element.parentNode.removeChild(tipsBox) + }catch(err){} + }, 150) + }) + } + } + }) + + + + if(!window.layer) + window.layer = __layer + + + return __layer + +}) \ No newline at end of file diff --git a/js/lib/layer/layer.js b/js/lib/layer/layer.js deleted file mode 100644 index d81e8b2..0000000 --- a/js/lib/layer/layer.js +++ /dev/null @@ -1,135 +0,0 @@ -/** - * - * @authors yutent (yutent@doui.cc) - * @date 2016-09-21 01:36:29 - * - */ - -"use strict"; - - -define(['avalon', 'css!./skin/def'], function(av){ - - - - var prep = { - type: { - 1: 'alert', - 2: 'confirm', - 3: 'msg', - 4: 'loading', - 5: 'iframe', - 6: 'tips', - 7: 'prompt' - }, - init: { - type: 1, - shade: true, - shadeClose: false, - move: '.do-ui-layer-move', - title: '温馨提示', - content: '', - offset: {x: '300px', y: '200px'}, - btns: ['确定', '取消'], - yes: av.noop, - no: av.noop, - success: av.noop - } - } - - function uuid(type){ - type = type || 1 - return prep.type[type] + Math.round(Date.now()/1000).toString(16) + Math.random().toString(16).slice(2, 6) - } - - - - var layer = { - alert: function(msg, conf){ - conf = conf || {} - return layer.open(av.mix({content: msg}, conf)) - }, - confirm: function(msg, conf){ - conf = conf || {} - return layer.open(av.mix({content: msg}, conf)) - }, - msg: function(msg, conf){ - av.log(msg) - }, - loading: function(msg, conf){ - av.log(msg) - }, - iframe: function(url, conf){ - av.log(url) - }, - tips: function(msg, conf){ - av.log(msg) - }, - prompt: function(callback){ - av.log('23456') - }, - use: function(conf, callback){ - require(['css!./skin/' + conf.skin], callback) - } - } - - - var FN = function(conf){ - this.ready(conf) - } - - - FN.prototype = { - init: {}, - create: function(){ - var layBox = document.createElement('div') - layBox.className = 'do-ui-layer skin-def' - layBox.style.left = this.init.offset.x - layBox.style.top = this.init.offset.y - layBox.setAttribute('ms-controller', this.init.$id) - layBox.innerHTML = '
{{title}}
' + - '
' + - '' + - '
' + - '
' + - '
' + - '' + - '' + - '
' - return layBox - }, - show: function(){ - - var layBox = this.create() - document.body.appendChild(layBox) - - av.define(this.init) - av.scan(layBox) - }, - ready: function(conf){ - this.init = av.mix({$id: uuid()}, prep.init, conf) - this.show() - }, - close: function(){ - - } - } - - - - - layer.open = function(conf){ - av.log(conf) - return new FN(conf).init - } - - - if(!window.layer) - window.layer = layer - - - - return layer - - -}) \ No newline at end of file diff --git a/js/lib/layer/skin/def.css b/js/lib/layer/skin/def.css index c30092c..5cbe97a 100644 --- a/js/lib/layer/skin/def.css +++ b/js/lib/layer/skin/def.css @@ -6,44 +6,229 @@ * */ -.do-ui-layer, .do-ui-layer * {margin: 0;padding: 0;vertical-align: baseline;box-sizing:border-box;} -.do-ui-layer a {text-decoration:none;} +.do-fn-cl { *zoom: 1; } +.do-fn-cl:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; overflow:hidden;} +.do-layer, .do-layer * {margin: 0;padding: 0;vertical-align: baseline;box-sizing:border-box;} +.do-layer a {text-decoration:none;} @font-face {font-family: "deficon"; - src: url('def.eot?t=1474609176'); /* IE9*/ - src: url('def.woff?t=1474609176') format('woff'), /* chrome, firefox */ - url('def.ttf?t=1474609176') format('truetype'); /* chrome, firefox, opera, Safari, Android, iOS 4.2+*/ + src: url('def.eot'); /* IE9*/ + src: url('def.ttf') format('truetype'); /* chrome, firefox, opera, Safari, Android, iOS 4.2+*/ } -.do-ui-layer-shade {position:fixed;left:0;top:0;z-index:65534;width:100%;height:100%;background:rgba(255,255,255,.05);} -.do-ui-layer {position:fixed;left:50%;top:230px;z-index:65535;width:auto;height:auto;} +.do-layer-cover {position:fixed;left:0;top:0;z-index:65534;width:100%;height:100%;background:rgba(255,255,255,.05);} +.do-layer {position:fixed;left:50%;top:50%;z-index:65535;width:auto;height:auto;} +.do-layer:active {z-index:65536;} -.do-ui-layer.skin-def {min-width:300px;background:#fff;color:#666;font-size:13px;box-shadow:0 0 10px rgba(0,0,0,.3);} -.do-ui-layer.skin-def .deficon {display: inline-block;font-family:"deficon" !important;font-style:normal;-webkit-font-smoothing: antialiased;-webkit-text-stroke-width: 0.2px;-moz-osx-font-smoothing: grayscale;} -.do-ui-layer.skin-def .icon-1:before {content:"\e605";color:#11b330;} -.do-ui-layer.skin-def .icon-2:before {content:"\e602";color:#f30;} -.do-ui-layer.skin-def .icon-3:before {content:"\e603";color:#f30;} -.do-ui-layer.skin-def .icon-4:before {content:"\e604";color:#f30;} -.do-ui-layer.skin-def .icon-5:before {content:"\e608";color:#09f;} -.do-ui-layer.skin-def .icon-6:before {content:"\e609";color:#ee0} -.do-ui-layer.skin-def .icon-7:before {content:"\e60a";color:#63e2c2} -.do-ui-layer.skin-def .icon-8:before {content:"\e606";color:#ee0} -.do-ui-layer.skin-def .icon-9:before {content:"\e607";color:#f30;} +/*默认皮肤样式*/ +.do-layer.skin-def {color:#666;font-size:14px;box-shadow:0 0 10px rgba(0,0,0,.3);} +.do-layer.skin-def .deficon {display: inline-block;font-family:"deficon" !important;font-style:normal;-webkit-font-smoothing: antialiased;-webkit-text-stroke-width: 0.2px;-moz-osx-font-smoothing: grayscale;} +.do-layer.skin-def .icon-1:before {content:"\e6f1";color:#11b330;}/*discover*/ +.do-layer.skin-def .icon-2:before {content:"\e6fa";color:#f30;}/*position*/ +.do-layer.skin-def .icon-3:before {content:"\e6f0";color:#f30;}/*del*/ +.do-layer.skin-def .icon-4:before {content:"\e604";color:#f30;}/*fire*/ +.do-layer.skin-def .icon-5:before {content:"\e6f9";color:#09f;}/*pilot*/ +.do-layer.skin-def .icon-6:before {content:"\e700";color:#f7b824}/*message*/ +.do-layer.skin-def .icon-7:before {content:"\e6fc";color:#63e2c2}/*talk*/ +.do-layer.skin-def .icon-8:before {content:"\e6f6";color:#f7b824}/*warn*/ +.do-layer.skin-def .icon-9:before {content:"\e6fb";color:#f60;}/*star*/ +.do-layer.skin-def .icon-10:before {content:"\e6f8";color:#48d0f7;}/*happy*/ +.do-layer.skin-def .icon-11:before {content:"\e6fd";color:#f90;}/*sad*/ +.do-layer.skin-def .icon-12:before {content:"\e631";color:#09a;}/*share*/ +.do-layer.skin-def .icon-13:before {content:"\e6f3";color:#f60;}/*search*/ +.do-layer.skin-def .icon-14:before {content:"\e6f4";color:#09a;}/*user*/ +.do-layer.skin-def .icon-15:before {content:"\e701";color:#f30;}/*minus*/ +.do-layer.skin-def .icon-16:before {content:"\e703";color:#f7b824;}/*wait*/ +.do-layer.skin-def .icon-17:before {content:"\e704";color:#11b330;}/*right*/ -.do-ui-layer.skin-def .layer-title {width:100%;height:40px;padding:0 8px;line-height:40px;background:#f3f3f3;font-size:14px;color:#454545;} -.do-ui-layer.skin-def .layer-min,.do-ui-layer.skin-def .layer-close {position:absolute;display:block;top:10px;width:20px;height:20px;line-height:20px;border:0;text-align:center;cursor:pointer;} -.do-ui-layer.skin-def .layer-min {right:40px;} -.do-ui-layer.skin-def .layer-close {right:10px;} -.do-ui-layer.skin-def .layer-close:hover,.do-ui-layer.skin-def .layer-min:hover {border: 1px solid #ddd;line-height: 18px;} -.do-ui-layer.skin-def .layer-min:before {content:"\e600";} -.do-ui-layer.skin-def .layer-close:before {content:"\e601";} +.do-layer.skin-def .layer-title {width:100%;height:40px;padding:0 8px;line-height:40px;background:#f3f3f3;font-size:14px;color:#454545;} +.do-layer.skin-def .action-min,.do-layer.skin-def .action-close {position:absolute;display:block;top:10px;width:20px;height:20px;line-height:20px;border:0;text-align:center;cursor:pointer;color:#666;} +.do-layer.skin-def .action-min {right:40px;} +.do-layer.skin-def .action-close {right:10px;} +.do-layer.skin-def .action-close:hover,.do-layer.skin-def .action-min:hover {border: 1px solid #ddd;line-height: 18px;color:#049789;} +.do-layer.skin-def .action-min:before {content:"\e600";} +.do-layer.skin-def .action-close:before {content:"\e659";} -.do-ui-layer.skin-def .layer-content {width:100%;height:auto;min-height:100px;padding:10px;} -.do-ui-layer.skin-def .layer-content .deficon {float:left;width:60px;height:100%;line-height:50px;font-size:40px;text-align:center;} -.do-ui-layer.skin-def .layer-content .detail {float:left;width:auto;height:100%;margin-top:10px;padding:5px 15px;word-break:break-all;word-wrap: break-word;} +.do-layer.skin-def .layer-content {position:relative;width:100%;height:auto;min-height:50px;padding:10px;} +.do-layer.skin-def .layer-content .deficon {position:absolute;left:10px;top:10px;width:50px;height:auto;line-height:40px;font-size:40px;text-align:center;} +.do-layer.skin-def .layer-content .detail {width:auto;height:100%;margin:auto auto auto 60px;padding:5px 15px;word-break:break-all;word-wrap: break-word;} +.do-layer.skin-def .layer-content.none-icon .detail {margin:0 auto;} +.do-layer.skin-def .layer-content .detail .prompt-value {width: 230px;height: 30px;padding: 0 8px;border: 1px solid #ddd;border-radius: 3px;} +.do-layer.skin-def .layer-content .detail .msg-box {line-height:30px;} + + +.do-layer.skin-def .layer-btns {width:100%;height:40px;padding:0 5px;line-height:28px;font-size:14px;color:#454545;text-align:right;} +.do-layer.skin-def .layer-btns a {display:inline-block;width:auto;min-width:60px;height:30px;margin:0 5px;padding:0 10px;line-height:28px;border:1px solid #ddd;color:#454545;text-align:center;background:#f3f3f3;} + +.do-layer.type-5 {visibility:hidden;min-width:75px;max-width:600px;line-height:1.5;color:#fff;background:rgba(0,0,0,.5);opacity:0;box-shadow:none;-webkit-transition:opacity .3s ease-in-out;transition:opacity .3s ease-in-out;} +.do-layer.type-5.active {visibility:visible;opacity:1;} +.do-layer.type-5 i.arrow {position:absolute;left:5px;bottom:-14px;width:0;height:0;border:6px solid transparent;border-top:8px solid rgba(0,0,0,.5);content: ""} +.do-layer.type-5 .layer-content .detail {margin:0;padding:0} + + +/******** 额外的弹窗类型样式 ******/ +.do-layer.type-1,.do-layer.type-2,.do-layer.type-3 {max-width:600px;min-width:230px;} +.do-layer.type-1 .layer-content,.do-layer.type-2 .layer-content,.do-layer.type-3 .layer-content{max-width:600px;} + +/*loading类型,背景色要去掉, 并且遮罩颜色改为黑色半透明*/ +.do-layer.type-6 {box-shadow:none;background:transparent;} +.do-layer-cover.type-6 {background:rgba(0,0,0,.3);} + +/*special模式类型,调小宽高限制,内外边距取消*/ +.do-layer.type-unspecial {min-width:100px;background:transparent;} +.do-layer.type-unspecial .layer-content {min-height:60px;padding:0} +.do-layer.type-unspecial .layer-content .detail {margin:0;padding:0} + +/*--------几种loading动画-------*/ +.do-ui-load {position:relative;width:100px;height:100px;margin:auto;} + +/* style 0 */ +.do-ui-load.load-style-0 .dot-box {position:absolute;display:block;width:70%;height:70%;margin:15%;-webkit-animation: circle 2s infinite linear;animation: circle 2s infinite linear;} +.do-ui-load.load-style-0 .dot-box i {position:absolute;display:block;width:40%;height:40%;border-radius:50%;background:#03998c;-webkit-animation: fadein 2s infinite linear;animation: fadein 2s infinite linear;-webkit-transform: scale(.5);transform: scale(.5);opacity:.3} +.do-ui-load.load-style-0 .dot-box i:nth-child(1) {left:2.5%;top:2.5%;} +.do-ui-load.load-style-0 .dot-box i:nth-child(2) {right:2.5%;top:2.5%;-webkit-animation-delay:.4s;animation-delay:.4s;} +.do-ui-load.load-style-0 .dot-box i:nth-child(3) {left:2.5%;bottom:2.5%;-webkit-animation-delay:.8s;animation-delay:.8s;} +.do-ui-load.load-style-0 .dot-box i:nth-child(4) {right:2.5%;bottom:2.5%;-webkit-animation-delay:1.2s;animation-delay:1.2s;} + +/* style 1 */ +.do-ui-load.load-style-1 .dot-box {position:absolute;display:block;width:90%;height:90%;margin:5%;} +.do-ui-load.load-style-1 .dot-box i {float:left;display:block;width:30px;height:30px;background:#03998c;-webkit-animation: grid 1.5s infinite linear;animation: grid 1.5s infinite linear;} +.do-ui-load.load-style-1 .dot-box i:nth-child(4), +.do-ui-load.load-style-1 .dot-box i:nth-child(8) {-webkit-animation-delay:.2s;animation-delay:.2s;} +.do-ui-load.load-style-1 .dot-box i:nth-child(1), +.do-ui-load.load-style-1 .dot-box i:nth-child(5), +.do-ui-load.load-style-1 .dot-box i:nth-child(9) {-webkit-animation-delay:.3s;animation-delay:.3s;} + +.do-ui-load.load-style-1 .dot-box i:nth-child(2), +.do-ui-load.load-style-1 .dot-box i:nth-child(6) {-webkit-animation-delay:.4s;animation-delay:.4s;} + +.do-ui-load.load-style-1 .dot-box i:nth-child(3) {-webkit-animation-delay:.5s;animation-delay:.5s;} + + +/* style 2 */ +.do-ui-load.load-style-2 .dot-box {position:absolute;display:block;width:90%;height:90%;margin:5%;-webkit-animation: circle 2s infinite linear;animation: circle 2s infinite linear;} +.do-ui-load.load-style-2 .dot-box i {position:absolute;display:block;width:40px;height:40px;background:#03998c;border-radius:50%;-webkit-animation: bounce 1.5s infinite linear;animation: bounce 1.5s infinite linear;-webkit-transform: scale(.1);transform: scale(.1);} +.do-ui-load.load-style-2 .dot-box i:nth-child(1) {left:5px;top:0;} +.do-ui-load.load-style-2 .dot-box i:nth-child(2) {right:5px;top:0;-webkit-animation-delay:.5s;animation-delay:.5s;} + + +/* style 3 */ +.do-ui-load.load-style-3 .dot-box {position:absolute;display:block;width:100%;height:100%;} +.do-ui-load.load-style-3 .dot-box i {position:absolute;display:block;width:100%;height:100%;border-top:5px solid #ff0;border-radius:50%;-webkit-animation: circle .9s infinite ease-in-out;animation: circle .9s infinite ease-in-out;} +.do-ui-load.load-style-3 .dot-box i:nth-child(1) {border-color:#03998c;} +.do-ui-load.load-style-3 .dot-box i:nth-child(2) {border-color:#f30;-webkit-animation-delay:.3s;animation-delay:.3s;} +.do-ui-load.load-style-3 .dot-box i:nth-child(3) {-webkit-animation-delay:.6s;animation-delay:.6s;} + + +/* style 4 */ +.do-ui-load.load-style-4 .dot-box {position:absolute;display:block;width:100%;height:100%;-webkit-animation: circle 1s infinite linear;animation: circle 1s infinite linear;} +.do-ui-load.load-style-4 .dot-box i {position:absolute;display:block;width:100%;height:100%;border-radius:50%;} +.do-ui-load.load-style-4 .dot-box i:nth-child(1) {border-top: 50px solid #fff;} +.do-ui-load.load-style-4 .dot-box i:nth-child(2) {border-bottom: 50px solid #000;} +.do-ui-load.load-style-4 .dot-box i:nth-child(1)::before {position:absolute;top:-50%;width:50%;height:50%;border-top: 25px solid #000;border-radius:50%;content:""} +.do-ui-load.load-style-4 .dot-box i:nth-child(1)::after {position:absolute;top:-20%;left:20%;width:10px;height:10px;border-radius:50%;background:#fff;content:""} +.do-ui-load.load-style-4 .dot-box i:nth-child(2)::before {position:absolute;bottom:-50%;right:0;width:50%;height:50%;border-bottom: 25px solid #fff;border-radius:50%;content:""} +.do-ui-load.load-style-4 .dot-box i:nth-child(2)::after {position:absolute;bottom:-20%;right:20%;width:10px;height:10px;border-radius:50%;background:#000;content:""} + + +/* style 5 */ +.do-ui-load.load-style-5 {width:100px;height:50px;} +.do-ui-load.load-style-5 .dot-box {position:absolute;display:block;width:100%;height:100%;} +.do-ui-load.load-style-5 .dot-box i {float:left;display:block;width:10px;height:100%;margin:0 5px;background:#03998c;-webkit-animation: bounce2 1s infinite ease-in-out;animation: bounce2 1s infinite ease-in-out;-webkit-transform:scaleY(.6);transform:scaleY(.6);} +.do-ui-load.load-style-5 .dot-box i:nth-child(2) {-webkit-animation-delay:.1s;animation-delay:.1s;} +.do-ui-load.load-style-5 .dot-box i:nth-child(3) {-webkit-animation-delay:.2s;animation-delay:.2s;} +.do-ui-load.load-style-5 .dot-box i:nth-child(4) {-webkit-animation-delay:.3s;animation-delay:.3s;} +.do-ui-load.load-style-5 .dot-box i:nth-child(5) {-webkit-animation-delay:.4s;animation-delay:.4s;} + +/* style 6 */ +.do-ui-load.load-style-6 {width:300px;height:50px;} +.do-ui-load.load-style-6 .dot-box {position:absolute;display:block;width:100%;height:100%;} +.do-ui-load.load-style-6 .dot-box i {position:absolute;display:block;width:10px;height:10px;background:#03998c;-webkit-animation: spring 3s infinite ease-in-out;animation: spring 3s infinite ease-in-out;} +.do-ui-load.load-style-6 .dot-box i:nth-child(2) {-webkit-animation-delay:.2s;animation-delay:.1s;} +.do-ui-load.load-style-6 .dot-box i:nth-child(3) {-webkit-animation-delay:.4s;animation-delay:.2s;} +.do-ui-load.load-style-6 .dot-box i:nth-child(4) {-webkit-animation-delay:.6s;animation-delay:.3s;} +.do-ui-load.load-style-6 .dot-box i:nth-child(5) {-webkit-animation-delay:.8s;animation-delay:.4s;} + +/* style 7 */ +.do-ui-load.load-style-7 .dot-box {position:absolute;display:block;width:60%;height:60%;margin:20%;} +.do-ui-load.load-style-7 .dot-box i {position:absolute;display:block;width:60px;height:60px;-webkit-animation: circle3 2s infinite ease-in-out;animation: circle3 2s infinite ease-in-out;-webkit-transform: rotate(45deg);transform: rotate(45deg);} +.do-ui-load.load-style-7 .dot-box i::before {display:block;width:8px;height:8px;background:#03998c;border-radius:50%;content:""} +.do-ui-load.load-style-7 .dot-box i:nth-child(2) {-webkit-animation-delay:.1s;animation-delay:.1s;} +.do-ui-load.load-style-7 .dot-box i:nth-child(3) {-webkit-animation-delay:.2s;animation-delay:.2s;} +.do-ui-load.load-style-7 .dot-box i:nth-child(4) {-webkit-animation-delay:.3s;animation-delay:.3s;} +.do-ui-load.load-style-7 .dot-box i:nth-child(5) {-webkit-animation-delay:.4s;animation-delay:.4s;} + + + +@-webkit-keyframes circle { + to {-webkit-transform: rotate(360deg);} +} +@keyframes circle { + to {transform: rotate(360deg)} +} +@-webkit-keyframes circle2 { + to {-webkit-transform: rotate(-360deg);} +} +@keyframes circle2 { + to {transform: rotate(-360deg)} +} +@-webkit-keyframes circle3 { + 70%,to {-webkit-transform: rotate(405deg);} +} +@keyframes circle3 { + 70%,to {transform: rotate(405deg);} +} + +@-webkit-keyframes fadein { + + 50% {-webkit-transform: scale(1);opacity:1} + to {-webkit-transform: scale(.5);opacity:.3} +} +@keyframes fadein { + + 50% {transform: scale(1);opacity:1} + to {transform: scale(.5);opacity:.3} +} + +@-webkit-keyframes grid { + + 36% {-webkit-transform: scale(.1);opacity:.3} + 60% {-webkit-transform: scale(1);opacity:1} +} +@keyframes grid { + + 36% {transform: scale(.1);opacity:.3} + 60% {transform: scale(1);opacity:1} +} + +@-webkit-keyframes bounce { + 70% {-webkit-transform: scale(1);} + to {-webkit-transform: scale(.1);} +} +@keyframes bounce { + 70% {transform: scale(1);} + to {transform: scale(.1);} +} + + +@-webkit-keyframes bounce2 { + 25% {-webkit-transform: scaleY(1.3);} + 50% {-webkit-transform: scaleY(.6);} +} +@keyframes bounce2 { + 25% {transform: scaleY(1.3);} + 50% {transform: scaleY(.6);} +} + +@-webkit-keyframes spring { + 30%,50% {-webkit-transform: translateX(200px);} + 80%,to {-webkit-transform: translateX(0);} +} +@keyframes spring { + 30%,50%{transform: translateX(200px);} + 80%,to {transform: translateX(0);} +} -.do-ui-layer.skin-def .layer-btns {width:100%;height:40px;padding:0 5px;line-height:28px;font-size:14px;color:#454545;text-align:right;} -.do-ui-layer.skin-def .layer-btns a {display:inline-block;width:auto;min-width:60px;height:30px;margin:0 5px;padding:0 10px;line-height:28px;border:1px solid #ddd;color:#454545;text-align:center;background:#f3f3f3;} \ No newline at end of file diff --git a/js/lib/layer/skin/def.eot b/js/lib/layer/skin/def.eot index 0e43397..c4a2f5e 100644 Binary files a/js/lib/layer/skin/def.eot and b/js/lib/layer/skin/def.eot differ diff --git a/js/lib/layer/skin/def.ttf b/js/lib/layer/skin/def.ttf index a8735ab..c63ae22 100644 Binary files a/js/lib/layer/skin/def.ttf and b/js/lib/layer/skin/def.ttf differ diff --git a/js/lib/layer/skin/def.woff b/js/lib/layer/skin/def.woff deleted file mode 100644 index 75922e1..0000000 Binary files a/js/lib/layer/skin/def.woff and /dev/null differ diff --git a/js/lib/request/ajax.js b/js/lib/request/ajax.js deleted file mode 100644 index 4aec5d9..0000000 --- a/js/lib/request/ajax.js +++ /dev/null @@ -1,1051 +0,0 @@ -//========================================= -// 数据交互模块 by 司徒正美 -// 版本: 1.0.0 -// 最近更新: 2015/4/30 -//========================================== -avalon.Promise = Promise; -define(["avalon"], function(avalon) { - var global = window - var DOC = global.document - var encode = encodeURIComponent - var decode = decodeURIComponent - - var rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/ - var rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg - var rnoContent = /^(?:GET|HEAD)$/ - var rprotocol = /^\/\// - var rhash = /#.*$/ - var rquery = /\?/ - var rjsonp = /(=)\?(?=&|$)|\?\?/ - var r20 = /%20/g - var radd = /\+/g - var r5b5d = /%5B(.*?)%5D$/; - - var originAnchor = document.createElement("a") - originAnchor.href = location.href - //告诉WEB服务器自己接受什么介质类型,*/* 表示任何类型,type/* 表示该类型下的所有子类型,type/sub-type。 - var accepts = { - xml: "application/xml, text/xml", - html: "text/html", - text: "text/plain", - json: "application/json, text/javascript", - script: "text/javascript, application/javascript", - "*": ["*/"] + ["*"] //避免被压缩掉 - } - - function IE() { - if (window.VBArray) { - var mode = document.documentMode - return mode ? mode : window.XMLHttpRequest ? 7 : 6 - } else { - return 0 - } - } - var useOnload = IE() === 0 || IE() > 8 - - function parseJS(code) { - var indirect = eval - code = code.trim() - if (code) { - if (code.indexOf("use strict") === 1) { - var script = document.createElement("script") - script.text = code; - head.appendChild(script).parentNode.removeChild(script) - } else { - indirect(code) - } - } - } - - if (!String.prototype.startsWith) { - String.prototype.startsWith = function(searchString, position) { - position = position || 0; - return this.lastIndexOf(searchString, position) === position; - } - } - - var head = DOC.getElementsByTagName("head")[0] //HEAD元素 - var isLocal = false - try { - //在IE下如果重置了document.domain,直接访问window.location会抛错,但用document.URL就ok了 - //http://www.cnblogs.com/WuQiang/archive/2012/09/21/2697474.html - isLocal = rlocalProtocol.test(location.protocol) - } catch (e) { - } - - new function() { - //http://www.cnblogs.com/rubylouvre/archive/2010/04/20/1716486.html - var s = ["XMLHttpRequest", - "ActiveXObject('MSXML2.XMLHTTP.6.0')", - "ActiveXObject('MSXML2.XMLHTTP.3.0')", - "ActiveXObject('MSXML2.XMLHTTP')", - "ActiveXObject('Microsoft.XMLHTTP')" - ] - s[0] = IE() < 8 && IE() !== 0 && isLocal ? "!" : s[0] //IE下只能使用ActiveXObject - for (var i = 0, axo; axo = s[i++];) { - try { - if (eval("new " + axo)) { - avalon.xhr = new Function("return new " + axo) - break; - } - } catch (e) { - } - }} - var supportCors = "withCredentials" in avalon.xhr() - - - - - function parseXML(data, xml, tmp) { - try { - var mode = document.documentMode - if (window.DOMParser && (!mode || mode > 8)) { // Standard - tmp = new DOMParser() - xml = tmp.parseFromString(data, "text/xml") - } else { // IE - xml = new ActiveXObject("Microsoft.XMLDOM") //"Microsoft.XMLDOM" - xml.async = "false"; - xml.loadXML(data) - } - } catch (e) { - xml = void 0 - } - if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) { - avalon.error("Invalid XML: " + data) - } - return xml - } - - //ajaxExtend是一个非常重要的内部方法,负责将用法参数进行规整化 - //1. data转换为字符串 - //2. type转换为大写 - //3. url正常化,加querystring, 加时间戮 - //4. 判定有没有跨域 - //5. 添加hasContent参数 - var defaults = { - type: "GET", - contentType: "application/x-www-form-urlencoded; charset=UTF-8", - async: true, - jsonp: "callback" - } - function ajaxExtend(opts) { - opts = avalon.mix({}, defaults, opts) - opts.type = opts.type.toUpperCase() - var querystring = typeof opts.data === "string" ? opts.data : avalon.param(opts.data) - opts.querystring = querystring || "" - opts.url = opts.url.replace(rhash, "").replace(rprotocol, location.protocol + "//") - - if (typeof opts.crossDomain !== "boolean") { //判定是否跨域 - var urlAnchor = document.createElement("a"); - // Support: IE6-11+ - // IE throws exception if url is malformed, e.g. http://example.com:80x/ - try { - urlAnchor.href = opts.url; - // in IE7-, get the absolute path - var absUrl = !"1"[0] ? urlAnchor.getAttribute("href", 4) : urlAnchor.href; - urlAnchor.href = absUrl - opts.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== urlAnchor.protocol + "//" + urlAnchor.host; - } catch (e) { - opts.crossDomain = true; - } - } - opts.hasContent = !rnoContent.test(opts.type) //是否为post请求 - if (!opts.hasContent) { - if (querystring) { //如果为GET请求,则参数依附于url上 - opts.url += (rquery.test(opts.url) ? "&" : "?") + querystring; - } - if (opts.cache === false) { //添加时间截 - opts.url += (rquery.test(opts.url) ? "&" : "?") + "_time=" + (new Date() - 0) - } - } - return opts; - } - /** - * 伪XMLHttpRequest类,用于屏蔽浏览器差异性 - * var ajax = new(self.XMLHttpRequest||ActiveXObject)("Microsoft.XMLHTTP") - * ajax.onreadystatechange = function(){ - * if (ajax.readyState==4 && ajax.status==200){ - * alert(ajax.responseText) - * } - * } - * ajax.open("POST", url, true) - * ajax.send("key=val&key1=val2") - */ - var XHRMethods = { - setRequestHeader: function(name, value) { - this.requestHeaders[name] = value; - return this; - }, - getAllResponseHeaders: function() { - return this.readyState === 4 ? this.responseHeadersString : null; - }, - getResponseHeader: function(name, match) { - if (this.readyState === 4) { - while ((match = rheaders.exec(this.responseHeadersString))) { - this.responseHeaders[match[1]] = match[2]; - } - match = this.responseHeaders[name]; - } - return match === undefined ? null : match; - }, - overrideMimeType: function(type) { - this.mimeType = type; - return this; - }, - // 中止请求 - abort: function(statusText) { - statusText = statusText || "abort"; - if (this.transport) { - this.respond(0, statusText) - } - return this; - }, - /** - * 用于派发success,error,complete等回调 - * http://www.cnblogs.com/rubylouvre/archive/2011/05/18/2049989.html - * @param {Number} status 状态码 - * @param {String} statusText 对应的扼要描述 - */ - dispatch: function(status, nativeStatusText) { - var statusText = nativeStatusText - // 只能执行一次,防止重复执行 - if (!this.transport) { //2:已执行回调 - return - } - this.readyState = 4 - var isSuccess = status >= 200 && status < 300 || status === 304 - if (isSuccess) { - if (status === 204) { - statusText = "nocontent" - } else if (status === 304) { - statusText = "notmodified" - } else { - //如果浏览器能直接返回转换好的数据就最好不过,否则需要手动转换 - if (typeof this.response === "undefined") { - var dataType = this.options.dataType || this.options.mimeType - if (!dataType && this.responseText || this.responseXML) { //如果没有指定dataType,则根据mimeType或Content-Type进行揣测 - dataType = this.getResponseHeader("Content-Type") || "" - dataType = dataType.match(/json|xml|script|html/i) || ["text"] - dataType = dataType[0].toLowerCase() - } - var responseText = this.responseText || '', - responseXML = this.responseXML || '' - try { - this.response = avalon.ajaxConverters[dataType].call(this, responseText, responseXML) - } catch (e) { - isSuccess = false - this.error = e - statusText = "parsererror" - } - } - } - } - this.status = status; - this.statusText = statusText + "" - if (this.timeoutID) { - clearTimeout(this.timeoutID) - delete this.timeoutID - } - this._transport = this.transport - - /** - * global event handler - */ - var that = this - - // 到这要么成功,调用success, 要么失败,调用 error, 最终都会调用 complete - if (isSuccess) { - this._resolve([this.response, statusText, this]) - /** - * global event handler - */ - window.setTimeout(function() { - avalon.ajaxGlobalEvents.success(that, that.options, that.response) - }, 0) - } else { - this._reject([this, statusText, this.error]) - /** - * global event handler - */ - window.setTimeout(function() { - avalon.ajaxGlobalEvents.error(that, that.options, statusText) - }, 0) - } - delete this.transport - - /** - * global event handler - */ - ajaxActive-- - - window.setTimeout(function() { - avalon.ajaxGlobalEvents.complete(that, that.options) - }, 0) - - if (ajaxActive === 0) { - // 最后一个 - window.setTimeout(function() { - avalon.ajaxGlobalEvents.stop() - }, 0) - } - - } - } - /** - * global event handler - */ - // 记录当前活跃的 ajax 数 - var ajaxActive = 0 - - //ajax主函数 - avalon.ajax = function(opts, promise) { - if (!opts || !opts.url) { - avalon.error("参数必须为Object并且拥有url属性") - } - opts = ajaxExtend(opts) //处理用户参数,比如生成querystring, type大写化 - //创建一个伪XMLHttpRequest,能处理complete,success,error等多投事件 - var XHRProperties = { - responseHeadersString: "", - responseHeaders: {}, - requestHeaders: {}, - querystring: opts.querystring, - readyState: 0, - uniqueID: ("" + Math.random()).replace(/0\./, ""), - status: 0 - } - var _reject, _resolve - var promise = new avalon.Promise(function(resolve, reject) { - _resolve = resolve - _reject = reject - }) - - promise.options = opts - promise._reject = _reject - promise._resolve = _resolve - - var doneList = [], - failList = [] - - Array("done", "fail", "always").forEach(function(method) { - promise[method] = function(fn) { - if (typeof fn === "function") { - if (method !== "fail") - doneList.push(fn) - if (method !== "done") - failList.push(fn) - } - return this - } - }) - - var isSync = opts.async === false - if (isSync) { - avalon.log("warnning:与jquery1.8一样,async:false这配置已经被废弃") - promise.async = false - } - - - avalon.mix(promise, XHRProperties, XHRMethods) - - promise.then(function(value) { - value = Array.isArray(value) ? value : value === void 0 ? [] : [value] - for (var i = 0, fn; fn = doneList[i++];) { - fn.apply(promise, value) - } - return value - }, function(value) { - value = Array.isArray(value) ? value : value === void 0 ? [] : [value] - for (var i = 0, fn; fn = failList[i++];) { - fn.apply(promise, value) - } - return value - }) - - - promise.done(opts.success).fail(opts.error).always(opts.complete) - - var dataType = opts.dataType //目标返回数据类型 - var transports = avalon.ajaxTransports - - if ((opts.crossDomain && !supportCors || rjsonp.test(opts.url)) && dataType === "json" && opts.type === "GET") { - dataType = opts.dataType = "jsonp" - } - var name = opts.form ? "upload" : dataType - var transport = transports[name] || transports.xhr - avalon.mix(promise, transport) //取得传送器的request, respond, preproccess - if (promise.preproccess) { //这用于jsonp upload传送器 - dataType = promise.preproccess() || dataType - } - //设置首部 1、Content-Type首部 - if (opts.contentType) { - promise.setRequestHeader("Content-Type", opts.contentType) - } - //2.处理Accept首部 - promise.setRequestHeader("Accept", accepts[dataType] ? accepts[dataType] + ", */*; q=0.01" : accepts["*"]) - for (var i in opts.headers) { //3. 处理headers里面的首部 - promise.setRequestHeader(i, opts.headers[i]) - } - // 4.处理超时 - if (opts.async && opts.timeout > 0) { - promise.timeoutID = setTimeout(function() { - promise.abort("timeout") - promise.dispatch(0, "timeout") - }, opts.timeout) - } - - /** - * global event handler - */ - if (ajaxActive === 0) { - // 第一个 - avalon.ajaxGlobalEvents.start() - } - avalon.ajaxGlobalEvents.send(promise, opts) - ajaxActive++ - - - - promise.request() - return promise - }; - "get,post".replace(avalon.rword, function(method) { - avalon[method] = function(url, data, callback, type) { - if (typeof data === "function") { - type = type || callback - callback = data - data = void 0 - } - return avalon.ajax({ - type: method, - url: url, - data: data, - success: callback, - dataType: type - }) - }; - }) - function ok(val) { - return val - } - function ng(e) { - throw e - } - avalon.getScript = function(url, callback) { - return avalon.get(url, null, callback, "script") - } - avalon.getJSON = function(url, data, callback) { - return avalon.get(url, data, callback, "json") - } - avalon.upload = function(url, form, data, callback, dataType) { - if (typeof data === "function") { - dataType = callback; - callback = data; - data = void 0; - } - return avalon.ajax({ - url: url, - type: "post", - dataType: dataType, - form: form, - data: data, - success: callback - }); - } - - - /** - * global event handler - */ - avalon.ajaxGlobalEvents = {}; - - ["start", "stop", "complete", "error", "success", "send"].forEach(function(method) { - avalon.ajaxGlobalEvents[method] = avalon.noop - }) - - avalon.ajaxConverters = { //转换器,返回用户想要做的数据 - text: function(text) { - // return text || ""; - return text; - }, - xml: function(text, xml) { - return xml !== void 0 ? xml : parseXML(text) - }, - html: function(text) { - return avalon.parseHTML(text) //一个文档碎片,方便直接插入DOM树 - }, - json: function(text) { - if (!avalon.parseJSON) { - avalon.log("avalon.parseJSON不存在,请升级到最新版") - } - return avalon.parseJSON(text) - }, - script: function(text) { - parseJS(text) - return text; - }, - jsonp: function() { - var json, callbackName; - if (this.jsonpCallback.startsWith('avalon.')) { - callbackName = this.jsonpCallback.replace(/avalon\./, '') - json = avalon[callbackName] - delete avalon[callbackName] - } else { - json = window[this.jsonpCallback] - } - return json; - } - } - - var rbracket = /\[\]$/ - avalon.param = function(obj) { - var prefix, - s = [], - add = function(key, value) { - // If value is a function, invoke it and return its value - value = typeof value === "function" ? value() : (value == null ? "" : value); - s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(value); - } - // 处理数组与类数组的jquery对象 - if (Array.isArray(obj)) { - // Serialize the form elements - avalon.each(obj, add) - - } else { - for (prefix in obj) { - paramInner(prefix, obj[prefix], add); - } - } - - // Return the resulting serialization - return s.join("&").replace(r20, "+"); - } - - function paramInner(prefix, obj, add) { - var name; - if (Array.isArray(obj)) { - // Serialize array item. - avalon.each(obj, function(i, v) { - if (rbracket.test(prefix)) { - // Treat each array item as a scalar. - add(prefix, v); - } else { - // Item is non-scalar (array or object), encode its numeric index. - paramInner( - prefix + "[" + (typeof v === "object" ? i : "") + "]", - v, - add); - } - }); - } else if (avalon.isPlainObject(obj)) { - // Serialize object item. - for (name in obj) { - paramInner(prefix + "[" + name + "]", obj[name], add); - } - - } else { - // Serialize scalar item. - add(prefix, obj); - } - } - //将一个字符串转换为对象 - function tryDecodeURIComponent(value) { - try { - return decodeURIComponent(value); - } catch (e) { - return value - } - } - - - //a%5B0%5D%5Bvalue%5D a%5B1%5D%5B%5D - function addSubObject(host, text, value) { - var match = text.match(r5b5d) - if (!match) { - return true - } - - var steps = [] - var first = true - var step, index, key - while (index = text.lastIndexOf("%5B")) { - if (index === -1) { - break - } - key = text.slice(index).slice(3, -3) - text = text.slice(0, index) - if (key === "") { - steps.unshift({ - action: "pushArrayElement" - }) - } else if ((key >>> 0) + "" === key) { - steps.unshift({ - action: "setSubArray", - value: key - }) - } else { - if (first) { - steps.unshift({ - action: "setObjectProperty", - value: tryDecodeURIComponent(key) - }) - } else { - steps.unshift({ - action: "setSubObjet", - value: tryDecodeURIComponent(key) - }) - } - } - first = false - } - first = true - while (step = steps.shift()) { - var isObject = /Object/.test(step.action) - if (first) { - if (!(text in host)) { - host[text] = isObject ? {} : [] - } - first = false - host = host[text] - } - switch (step.action) { - case "pushArrayElement": - host.push(value) - break - case "setObjectProperty": - host[step.value] = value - break - case "setSubObjet": - if (!(step.value in host)) { - host[step.value] = {} - } - host = host[step.value] - break - case "setSubArray": - if (!(step.value in host)) { - host[step.value] = [] - } - host = host[step.value] - break - } - } - } - // function add - avalon.unparam = function(qs, sep, eq) { - sep = sep || '&'; - eq = eq || '='; - var obj = {}; - if ((typeof qs !== "string") || qs.length === 0) { - return obj; - } - if (qs.indexOf("?") !== -1) { - qs = qs.split("?").pop() - } - var array = qs.split(sep); - for (var i = 0, el; el = array[i++];) { - var arr = el.split("=") - if (arr.length === 1) { //处理只有键名没键值的情况 - obj[arr[0]] = "" - } else { - var key = arr[0].replace(radd, '%20') - var v = tryDecodeURIComponent(arr.slice(1).join("=").replace(radd, ' ')); - if (addSubObject(obj, key, v)) { //处理存在中括号的情况 - var k = tryDecodeURIComponent(key) //处理不存在中括号的简单的情况 - if (!Object.prototype.hasOwnProperty.call(obj, k)) { - obj[k] = v; - } else if (Array.isArray(obj[k])) { - obj[k].push(v); - } else { - obj[k] = [obj[k], v]; - } - } - } - } - - return obj - } - var rinput = /select|input|button|textarea/i - var rcheckbox = /radio|checkbox/ - var rline = /\r?\n/g - function trimLine(val) { - return val.replace(rline, "\r\n") - } - //表单元素变字符串, form为一个元素节点 - avalon.serialize = function(form) { - var json = {}; - // 不直接转换form.elements,防止以下情况:
- Array.prototype.filter.call(form.getElementsByTagName("*"), function(el) { - if (rinput.test(el.nodeName) && el.name && !el.disabled) { - return rcheckbox.test(el.type) ? el.checked : true //只处理拥有name并且没有disabled的表单元素 - } - }).forEach(function(el) { - var val = avalon(el).val() - val = Array.isArray(val) ? val.map(trimLine) : trimLine(val) - var name = el.name - if (name in json) { - if (Array.isArray(val)) { - json[name].push(val) - } else { - json[name] = [json[name], val] - } - } else { - json[name] = val - } - }) - return avalon.param(json, false) // 名值键值对序列化,数组元素名字前不加 [] - } - - var transports = avalon.ajaxTransports = { - xhr: { - //发送请求 - request: function() { - var self = this; - var opts = this.options; - var transport = this.transport = new avalon.xhr; - transport.open(opts.type, opts.url, opts.async, opts.username, opts.password) - if (this.mimeType && transport.overrideMimeType) { - transport.overrideMimeType(this.mimeType) - } - //IE6下,如果transport中没有withCredentials,直接设置会报错 - if (opts.crossDomain && "withCredentials" in transport) { - transport.withCredentials = true - } - - /* - * header 中设置 X-Requested-With 用来给后端做标示: - * 这是一个 ajax 请求。 - * - * 在 Chrome、Firefox 3.5+ 和 Safari 4+ 下, - * 在进行跨域请求时设置自定义 header,会触发 preflighted requests, - * 会预先发送 method 为 OPTIONS 的请求。 - * - * 于是,如果跨域,禁用此功能。 - */ - if (!opts.crossDomain) { - this.requestHeaders["X-Requested-With"] = "XMLHttpRequest" - } - - for (var i in this.requestHeaders) { - transport.setRequestHeader(i, this.requestHeaders[i] + "") - } - - /* - * progress - */ - if (opts.progressCallback) { - // 判断是否 ie6-9 - var isOldIE = document.all && !window.atob; - if (!isOldIE) { - transport.upload.onprogress = opts.progressCallback - } - } - - var dataType = opts.dataType - if ("responseType" in transport && /^(blob|arraybuffer|text)$/.test(dataType)) { - transport.responseType = dataType - this.useResponseType = true - } - //必须要支持 FormData 和 file.fileList 的浏览器 才能用 xhr 发送 - //标准规定的 multipart/form-data 发送必须用 utf-8 格式, 记得 ie 会受到 document.charset 的影响 - transport.send(opts.hasContent && (this.formdata || this.querystring) || null) - //在同步模式中,IE6,7可能会直接从缓存中读取数据而不会发出请求,因此我们需要手动发出请求 - - if (!opts.async || transport.readyState === 4) { - this.respond() - } else { - if (useOnload) { //如果支持onerror, onload新API - transport.onload = transport.onerror = function(e) { - this.readyState = 4 //IE9+ - this.status = e.type === "load" ? 200 : 500 - self.respond() - } - } else { - transport.onreadystatechange = function() { - self.respond() - } - } - } - }, - //用于获取原始的responseXMLresponseText 修正status statusText - //第二个参数为1时中止清求 - respond: function(event, forceAbort) { - var transport = this.transport - if (!transport) { - return - } - // by zilong:避免abort后还继续派发onerror等事件 - if (forceAbort && this.timeoutID) { - clearTimeout(this.timeoutID); - delete this.timeoutID - } - try { - var completed = transport.readyState === 4 - if (forceAbort || completed) { - transport.onreadystatechange = avalon.noop - if (useOnload) { //IE6下对XHR对象设置onerror属性可能报错 - transport.onerror = transport.onload = null - } - if (forceAbort) { - if (!completed && typeof transport.abort === "function") { // 完成以后 abort 不要调用 - transport.abort() - } - } else { - var status = transport.status - //设置responseText - var text = transport.responseText - - this.responseText = typeof text === "string" ? text : void 0 - //设置responseXML - try { - //当responseXML为[Exception: DOMException]时, - //访问它会抛“An attempt was made to use an object that is not, or is no longer, usable”异常 - var xml = transport.responseXML - this.responseXML = xml.documentElement - } catch (e) { - } - //设置response - if (this.useResponseType) { - this.response = transport.response - } - //设置responseHeadersString - this.responseHeadersString = transport.getAllResponseHeaders() - - try { //火狐在跨城请求时访问statusText值会抛出异常 - var statusText = transport.statusText - } catch (e) { - this.error = e - statusText = "firefoxAccessError" - } - //用于处理特殊情况,如果是一个本地请求,只要我们能获取数据就假当它是成功的 - if (!status && isLocal && !this.options.crossDomain) { - status = this.responseText ? 200 : 404 - //IE有时会把204当作为1223 - } else if (status === 1223) { - status = 204 - } - this.dispatch(status, statusText) - } - } - } catch (err) { - // 如果网络问题时访问XHR的属性,在FF会抛异常 - // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) - if (!forceAbort) { - this.dispatch(500, err) - } - } - } - }, - jsonp: { - preproccess: function() { - var opts = this.options; - var name = this.jsonpCallback = opts.jsonpCallback || "avalon.jsonp" + setTimeout("1") - if (rjsonp.test(opts.url)) { - opts.url = opts.url.replace(rjsonp, "$1" + name) - } else { - opts.url = opts.url + (rquery.test(opts.url) ? "&" : "?") + opts.jsonp + "=" + name - } - //将后台返回的json保存在惰性函数中 - if (name.startsWith('avalon.')) { - name = name.replace(/avalon\./, '') - avalon[name] = function(json) { - avalon[name] = json - } - } else { - window[name] = function(json) { - window[name] = json - } - } - return "script" - } - }, - script: { - request: function() { - var opts = this.options; - var node = this.transport = DOC.createElement("script") - if (opts.charset) { - node.charset = opts.charset - } - var self = this; - node.onerror = node[useOnload ? "onload" : "onreadystatechange"] = function() { - self.respond() - }; - node.src = opts.url - head.insertBefore(node, head.firstChild) - }, - respond: function(event, forceAbort) { - var node = this.transport - if (!node) { - return - } - // by zilong:避免abort后还继续派发onerror等事件 - if (forceAbort && this.timeoutID) { - clearTimeout(this.timeoutID); - delete this.timeoutID - } - var execute = /loaded|complete|undefined/i.test(node.readyState) - if (forceAbort || execute) { - node.onerror = node.onload = node.onreadystatechange = null - var parent = node.parentNode; - if (parent) { - parent.removeChild(node) - } - if (!forceAbort) { - var args; - if (this.jsonpCallback) { - var jsonpCallback = this.jsonpCallback.startsWith('avalon.') ? avalon[this.jsonpCallback.replace(/avalon\./, '')] : window[this.jsonpCallback] - args = typeof jsonpCallback === "function" ? [500, "error"] : [200, "success"] - } else { - args = [200, "success"] - } - - this.dispatch.apply(this, args) - } - } - } - }, - upload: { - preproccess: function() { - var opts = this.options, formdata - if (typeof opts.form.append === "function") { //简单判断opts.form是否为FormData - formdata = opts.form; - opts.contentType = ''; - } else { - formdata = new FormData(opts.form) //将二进制什么一下子打包到formdata - } - avalon.each(opts.data, function(key, val) { - formdata.append(key, val) //添加客外数据 - }) - this.formdata = formdata - } - } - } - - - avalon.mix(transports.jsonp, transports.script) - avalon.mix(transports.upload, transports.xhr) - - if (!window.FormData) { - var str = 'Function BinaryToArray(binary)\r\n\ - Dim oDic\r\n\ - Set oDic = CreateObject("scripting.dictionary")\r\n\ - length = LenB(binary) - 1\r\n\ - For i = 1 To length\r\n\ - oDic.add i, AscB(MidB(binary, i, 1))\r\n\ - Next\r\n\ - BinaryToArray = oDic.Items\r\n\ - End Function' - execScript(str, "VBScript"); - avalon.fixAjax = function() { - avalon.ajaxConverters.arraybuffer = function() { - var body = this.tranport && this.tranport.responseBody - if (body) { - return new VBArray(BinaryToArray(body)).toArray(); - } - }; - function createIframe(ID) { - var iframe = avalon.parseHTML("