Esites_Editor - Version 0.6.1

Version Notes

As of this version the JS resources are being loaded via the Magento base URL instead of always from root. This should fix several issues when running Magento from a subfolder.

Also all npm dependencies are updated.

The GitHub repo can be found at: https://github.com/e-sites/magento-advanced-code-editor

Download this release

Release Info

Developer Boye Oomens
Extension Esites_Editor
Version 0.6.1
Comparing to
See all releases


Code changes from version 0.6.0 to 0.6.1

Files changed (47) hide show
  1. app/code/community/Esites/Editor/Model/System/Config/Source/Theme/Values.php +3 -0
  2. app/code/community/Esites/Editor/etc/config.xml +1 -1
  3. app/design/adminhtml/default/default/template/esites_editor/standalone.phtml +3 -4
  4. app/design/frontend/base/default/template/esites_editor/standalone.phtml +2 -2
  5. js/esites_editor/dist/js/app/module/code.js +1 -1
  6. js/esites_editor/dist/js/app/module/editor.js +1 -1
  7. js/esites_editor/dist/js/app/module/standalone.js +1 -1
  8. js/esites_editor/dist/js/app/module/util.js +1 -1
  9. js/esites_editor/dist/js/vendor/codemirror/addon/comment/comment.js +8 -5
  10. js/esites_editor/dist/js/vendor/codemirror/addon/display/rulers.js +13 -25
  11. js/esites_editor/dist/js/vendor/codemirror/addon/edit/closebrackets.js +9 -2
  12. js/esites_editor/dist/js/vendor/codemirror/addon/edit/continuelist.js +3 -3
  13. js/esites_editor/dist/js/vendor/codemirror/addon/edit/matchbrackets.js +3 -1
  14. js/esites_editor/dist/js/vendor/codemirror/addon/fold/brace-fold.js +8 -8
  15. js/esites_editor/dist/js/vendor/codemirror/addon/fold/comment-fold.js +1 -1
  16. js/esites_editor/dist/js/vendor/codemirror/addon/fold/foldcode.js +3 -2
  17. js/esites_editor/dist/js/vendor/codemirror/addon/fold/foldgutter.js +1 -1
  18. js/esites_editor/dist/js/vendor/codemirror/addon/fold/xml-fold.js +5 -5
  19. js/esites_editor/dist/js/vendor/codemirror/addon/hint/javascript-hint.js +10 -1
  20. js/esites_editor/dist/js/vendor/codemirror/addon/hint/show-hint.css +0 -2
  21. js/esites_editor/dist/js/vendor/codemirror/addon/hint/show-hint.js +5 -1
  22. js/esites_editor/dist/js/vendor/codemirror/addon/hint/sql-hint.js +7 -17
  23. js/esites_editor/dist/js/vendor/codemirror/addon/lint/lint.css +2 -2
  24. js/esites_editor/dist/js/vendor/codemirror/addon/lint/lint.js +1 -1
  25. js/esites_editor/dist/js/vendor/codemirror/addon/merge/merge.js +58 -36
  26. js/esites_editor/dist/js/vendor/codemirror/addon/mode/overlay.js +7 -2
  27. js/esites_editor/dist/js/vendor/codemirror/addon/scroll/scrollpastend.js +2 -0
  28. js/esites_editor/dist/js/vendor/codemirror/addon/scroll/simplescrollbars.js +9 -6
  29. js/esites_editor/dist/js/vendor/codemirror/addon/search/match-highlighter.js +22 -3
  30. js/esites_editor/dist/js/vendor/codemirror/addon/search/search.js +26 -5
  31. js/esites_editor/dist/js/vendor/codemirror/addon/selection/active-line.js +11 -13
  32. js/esites_editor/dist/js/vendor/codemirror/addon/wrap/hardwrap.js +3 -1
  33. js/esites_editor/dist/js/vendor/codemirror/keymap/emacs.js +1 -1
  34. js/esites_editor/dist/js/vendor/codemirror/keymap/sublime.js +1 -1
  35. js/esites_editor/dist/js/vendor/codemirror/keymap/vim.js +4 -4
  36. js/esites_editor/dist/js/vendor/codemirror/lib/codemirror.css +1 -1
  37. js/esites_editor/dist/js/vendor/codemirror/lib/codemirror.js +8 -7
  38. js/esites_editor/dist/js/vendor/codemirror/mode/css/css.js +1 -1
  39. js/esites_editor/dist/js/vendor/codemirror/mode/htmlmixed/htmlmixed.js +1 -1
  40. js/esites_editor/dist/js/vendor/codemirror/mode/javascript/javascript.js +1 -1
  41. js/esites_editor/dist/js/vendor/codemirror/theme/dracula.css +1 -1
  42. js/esites_editor/dist/js/vendor/codemirror/theme/duotone-dark.css +1 -0
  43. js/esites_editor/dist/js/vendor/codemirror/theme/duotone-light.css +1 -0
  44. js/esites_editor/dist/js/vendor/codemirror/theme/panda-syntax.css +1 -0
  45. js/esites_editor/dist/js/vendor/codemirror/theme/pastel-on-dark.css +1 -1
  46. js/esites_editor/dist/js/vendor/codemirror/theme/solarized.css +1 -1
  47. js/esites_editor/dist/js/vendor/emmet-codemirror/dist/emmet.js +3 -3
app/code/community/Esites/Editor/Model/System/Config/Source/Theme/Values.php CHANGED
@@ -34,6 +34,8 @@ class Esites_Editor_Model_System_Config_Source_Theme_Values extends Varien_Objec
34
  'cobalt',
35
  'colorforth',
36
  'dracula',
 
 
37
  'eclipse',
38
  'elegant',
39
  'erlang-dark',
@@ -50,6 +52,7 @@ class Esites_Editor_Model_System_Config_Source_Theme_Values extends Varien_Objec
50
  'neat',
51
  'neo',
52
  'night',
 
53
  'paraiso-dark',
54
  'paraiso-light',
55
  'pastel-on-dark',
34
  'cobalt',
35
  'colorforth',
36
  'dracula',
37
+ 'duotone-dark',
38
+ 'duotone-light',
39
  'eclipse',
40
  'elegant',
41
  'erlang-dark',
52
  'neat',
53
  'neo',
54
  'night',
55
+ 'panda-syntax',
56
  'paraiso-dark',
57
  'paraiso-light',
58
  'pastel-on-dark',
app/code/community/Esites/Editor/etc/config.xml CHANGED
@@ -22,7 +22,7 @@
22
  <config>
23
  <modules>
24
  <Esites_Editor>
25
- <version>0.6.0</version>
26
  </Esites_Editor>
27
  </modules>
28
 
22
  <config>
23
  <modules>
24
  <Esites_Editor>
25
+ <version>0.6.1</version>
26
  </Esites_Editor>
27
  </modules>
28
 
app/design/adminhtml/default/default/template/esites_editor/standalone.phtml CHANGED
@@ -19,16 +19,15 @@
19
  */
20
  ?>
21
 
22
- <script src="/js/esites_editor/dist/js/vendor/requirejs/require.js"></script>
23
  <script>
24
  (function (window) {
25
- var doc = window.document,
26
- esites_editor = {
27
  instances: [],
28
  version: '<?php echo Mage::helper('editor')->getExtensionVersion(); ?>',
29
  settings: <?php echo json_encode($this->getEditorConfig()); ?>,
30
  init: function () {
31
- requirejs(['/js/esites_editor/dist/js/app.js']);
32
  }
33
  };
34
 
19
  */
20
  ?>
21
 
22
+ <script src="<?php echo Mage::getBaseUrl('js');?>esites_editor/dist/js/vendor/requirejs/require.js"></script>
23
  <script>
24
  (function (window) {
25
+ var esites_editor = {
 
26
  instances: [],
27
  version: '<?php echo Mage::helper('editor')->getExtensionVersion(); ?>',
28
  settings: <?php echo json_encode($this->getEditorConfig()); ?>,
29
  init: function () {
30
+ requirejs(['<?php echo Mage::getBaseUrl('js');?>esites_editor/dist/js/app.js']);
31
  }
32
  };
33
 
app/design/frontend/base/default/template/esites_editor/standalone.phtml CHANGED
@@ -19,7 +19,7 @@
19
  */
20
  ?>
21
 
22
- <script src="/js/esites_editor/dist/js/vendor/requirejs/require.js"></script>
23
  <script>
24
  (function (window) {
25
  var doc = window.document,
@@ -28,7 +28,7 @@
28
  version: '<?php echo Mage::helper('editor')->getExtensionVersion(); ?>',
29
  settings: <?php echo json_encode($this->getEditorConfig()); ?>,
30
  init: function () {
31
- requirejs(['/js/esites_editor/dist/js/app.js']);
32
  }
33
  };
34
 
19
  */
20
  ?>
21
 
22
+ <script src="<?php echo Mage::getBaseUrl('js');?>js/esites_editor/dist/js/vendor/requirejs/require.js"></script>
23
  <script>
24
  (function (window) {
25
  var doc = window.document,
28
  version: '<?php echo Mage::helper('editor')->getExtensionVersion(); ?>',
29
  settings: <?php echo json_encode($this->getEditorConfig()); ?>,
30
  init: function () {
31
+ requirejs(['<?php echo Mage::getBaseUrl('js');?>js/esites_editor/dist/js/app.js']);
32
  }
33
  };
34
 
js/esites_editor/dist/js/app/module/code.js CHANGED
@@ -1 +1 @@
1
- define(["codemirror/lib/codemirror","js-beautify/js/lib/beautify","js-beautify/js/lib/beautify-html","js-beautify/js/lib/beautify-css","../var/plugin"],function(CodeMirror,jsBeautify,htmlBeautify,cssBeautify,plugin){"use strict";var code={format:function(type,source){var beautifier="html"===type?htmlBeautify:cssBeautify;return beautifier[type+"_beautify"](source,{indent_size:plugin.settings.indentUnit,wrap_line_length:plugin.settings.lineLength||100})},completeAfter:function(cm,pred){(!pred||pred())&&setTimeout(function(){cm.state.completionActive||cm.showHint({completeSingle:!1})},100);return CodeMirror.Pass},completeIfAfterLt:function(cm){return code.completeAfter(cm,function(){var cur=cm.getCursor();return"<"===cm.getRange(CodeMirror.Pos(cur.line,cur.ch-1),cur)})},completeIfInTag:function(cm){return code.completeAfter(cm,function(){var inner,tok=cm.getTokenAt(cm.getCursor());if("string"===tok.type&&(!/['"]/.test(tok.string.charAt(tok.string.length-1))||1===tok.string.length))return!1;inner=CodeMirror.innerMode(cm.getMode(),tok.state).state;return inner.tagName})}};return code});
1
+ define(["codemirror/lib/codemirror","js-beautify/js/lib/beautify","js-beautify/js/lib/beautify-html","js-beautify/js/lib/beautify-css","../var/plugin"],function(CodeMirror,jsBeautify,htmlBeautify,cssBeautify,plugin){"use strict";var code={format:function(type,source){var beautifier="html"===type?htmlBeautify:cssBeautify;return beautifier[type+"_beautify"](source,{indent_size:plugin.settings.indentUnit,wrap_line_length:plugin.settings.lineLength||100})},completeAfter:function(cm,pred){pred&&!pred()||setTimeout(function(){cm.state.completionActive||cm.showHint({completeSingle:!1})},100);return CodeMirror.Pass},completeIfAfterLt:function(cm){return code.completeAfter(cm,function(){var cur=cm.getCursor();return"<"===cm.getRange(CodeMirror.Pos(cur.line,cur.ch-1),cur)})},completeIfInTag:function(cm){return code.completeAfter(cm,function(){var inner,tok=cm.getTokenAt(cm.getCursor());if("string"===tok.type&&(!/['"]/.test(tok.string.charAt(tok.string.length-1))||1===tok.string.length))return!1;inner=CodeMirror.innerMode(cm.getMode(),tok.state).state;return inner.tagName})}};return code});
js/esites_editor/dist/js/app/module/editor.js CHANGED
@@ -1 +1 @@
1
- define(["codemirror/lib/codemirror","../var/plugin","../var/targets","../var/deps","./dialog","./util","./code","./standalone"],function(CodeMirror,plugin,targets,deps,dialog,util,code,standalone){"use strict";var editor={};editor.instances=[];editor.options=null;editor.init=function(){util.forEach(targets,editor.createInstance);"undefined"!=typeof varienGlobalEvents&&varienGlobalEvents.attachEventHandler("showTab",function(){util.forEach(editor.instances,function(cm){cm.refresh()})});editor.instances.length&&editor.instances[0].focus()};editor.createInstance=function(textarea){var cm=CodeMirror.fromTextArea(textarea,editor.options);dialog&&dialog.prepare(cm);plugin.settings.emmet&&editor.initEmmet();editor.isStandAlone()&&"undefined"==typeof tinyMCE&&standalone.init(cm,editor);plugin.instances.push(cm);editor.instances.push(cm)};editor.syncValue=function(cm){cm.getTextArea().value=cm.getValue()};editor.initEmmet=function(cm){requirejs(["emmet"],function(emmetCodeMirror){cm?emmetCodeMirror(cm):util.forEach(editor.instances,function(c){emmetCodeMirror(c)})})};editor.isStandAlone=function(){return-1!==util.inArray("wysiwygtemplate_text",plugin.settings.sections)};editor.insertVariable=function(obj,cm){var attr=obj.getAttribute("onclick"),val=attr.match(/{{(.*?)[\|\|.*?]?}}/)[0],doc=cm.getDoc(),cursor=doc.getCursor();doc.replaceRange(val,cursor)};editor.insertSnippet=function(snippet,cm,cursor){var doc=cm.getDoc();doc.replaceRange(snippet,cursor)};return editor});
1
+ define(["codemirror/lib/codemirror","../var/plugin","../var/targets","../var/deps","./dialog","./util","./standalone"],function(CodeMirror,plugin,targets,deps,dialog,util,standalone){"use strict";var editor={};editor.instances=[];editor.options=null;editor.init=function(){util.forEach(targets,editor.createInstance);"undefined"!=typeof varienGlobalEvents&&varienGlobalEvents.attachEventHandler("showTab",function(){util.forEach(editor.instances,function(cm){cm.refresh()})});editor.instances.length&&editor.instances[0].focus()};editor.createInstance=function(textarea){var cm=CodeMirror.fromTextArea(textarea,editor.options);dialog&&dialog.prepare(cm);plugin.settings.emmet&&editor.initEmmet();editor.isStandAlone()&&standalone.init(cm,editor);plugin.instances.push(cm);editor.instances.push(cm)};editor.syncValue=function(cm){cm.save()};editor.initEmmet=function(cm){requirejs(["emmet"],function(emmetCodeMirror){cm?emmetCodeMirror(cm):util.forEach(editor.instances,function(c){emmetCodeMirror(c)})})};editor.isStandAlone=function(){return util.inArray("wysiwygtemplate_text",plugin.settings.sections)!==-1};editor.insertVariable=function(obj,cm){var attr=obj.getAttribute("onclick"),val=attr.match(/{{(.*?)[\|\|.*?]?}}/)[0],doc=cm.getDoc(),cursor=doc.getCursor();doc.replaceRange(val,cursor)};editor.insertSnippet=function(snippet,cm,cursor){var doc=cm.getDoc();doc.replaceRange(snippet,cursor)};return editor});
js/esites_editor/dist/js/app/module/standalone.js CHANGED
@@ -1 +1 @@
1
- define(["codemirror/lib/codemirror","gator","./code","./util","../var/plugin"],function(CodeMirror,Gator,code,util,plugin){"use strict";function _monitorChanges(){var textarea=this.getTextArea();if(""!==textarea.value){this.setValue(code.format("html",textarea.value));if(stylesEditor){cssCode=stylesEditor.value;plugin.settings.autoFormat&&(cssCode=code.format("css",stylesEditor.value));cmStyles.setValue(cssCode)}clearInterval(timer)}}function _createCssEditor(editor){if(stylesEditor){cmStyles=CodeMirror.fromTextArea(stylesEditor,util.extend(editor.options,{mode:"css"}));cmStyles.on("blur",editor.syncValue);plugin.settings.emmet&&editor.initEmmet(cmStyles)}}function _emptyTextAreas(editor){stylesEditor&&(stylesEditor.value="");util.forEach(editor.instances,function(el){el.getTextArea().value=""})}function _init(cm,editor){var cursor,cm=cm;cm.on("blur",editor.syncValue);_createCssEditor(editor);"undefined"!=typeof Ajax&&Ajax.Responders.register({onComplete:function(){var url,args=arguments;if(args.length>1){url=args[1].request.url;(url.indexOf("onInsert")>-1||url.indexOf("buildWidget")>-1)&&editor.insertSnippet(args[1].responseText,cm,cursor)}}});Gator(document).on("click","#variables-chooser_content a",function(){editor.insertVariable(this,cm)}).on("mousedown",".magento_close",function(){clearInterval(timer)}).on("click","#email_template_load_form button",function(){_emptyTextAreas(editor);timer=setInterval(util.proxy(_monitorChanges,cm),250)}).on("click",".add-image, .add-widget",function(){cursor=cm.getCursor()})}var cmStyles,cssCode,timer=null,stylesEditor=util.getElem("template_styles");return{init:_init}});
1
+ define(["codemirror/lib/codemirror","gator","./code","./util","../var/plugin"],function(CodeMirror,Gator,code,util,plugin){"use strict";function _monitorChanges(){var textarea=this.getTextArea();if(""!==textarea.value){this.setValue(code.format("html",textarea.value));if(stylesEditor){cssCode=stylesEditor.value;plugin.settings.autoFormat&&(cssCode=code.format("css",stylesEditor.value));cmStyles.setValue(cssCode)}clearInterval(timer)}}function _createCssEditor(editor){if(stylesEditor){cmStyles=CodeMirror.fromTextArea(stylesEditor,util.extend(editor.options,{mode:"css"}));cmStyles.on("blur",editor.syncValue);plugin.settings.emmet&&editor.initEmmet(cmStyles)}}function _emptyTextAreas(editor){stylesEditor&&(stylesEditor.value="");util.forEach(editor.instances,function(el){el.getTextArea().value=""})}function _init(cm,editor){var cursor,cm=cm;cm.on("blur",editor.syncValue);cm.on("change",editor.syncValue);_createCssEditor(editor);"undefined"!=typeof Ajax&&Ajax.Responders.register({onComplete:function(){var url,args=arguments;if(args.length>1){url=args[1].request.url;(url.indexOf("onInsert")>-1||url.indexOf("buildWidget")>-1)&&editor.insertSnippet(args[1].responseText,cm,cursor)}}});Gator(document).on("click","#variables-chooser_content a",function(){editor.insertVariable(this,cm)}).on("mousedown",".magento_close",function(){clearInterval(timer)}).on("click","#email_template_load_form button",function(){_emptyTextAreas(editor);timer=setInterval(util.proxy(_monitorChanges,cm),250)}).on("click",".add-image, .add-widget",function(){cursor=cm.getCursor()})}var cmStyles,cssCode,timer=null,stylesEditor=util.getElem("template_styles");return{init:_init}});
js/esites_editor/dist/js/app/module/util.js CHANGED
@@ -1 +1 @@
1
- define(function(undef){"use strict";var util={getElem:function(id){return document.getElementById(id)},inArray:function(elem,arr,i){var len;if(arr){if(arr.indexOf)return arr.indexOf.call(arr,elem,i);len=arr.length;i=i?0>i?Math.max(0,len+i):i:0;for(;len>i;i++)if(i in arr&&arr[i]===elem)return i}return-1},isArray:function(arr){return"[object Array]"===Object.prototype.toString.call(arr)},extend:function(obj,ext){var i,l,name,value,args=arguments;for(i=1,l=args.length;l>i;i++){ext=args[i];for(name in ext)if(ext.hasOwnProperty(name)){value=ext[name];value!==undef&&(obj[name]=value)}}return obj},forEach:function(collection,callback,scope){if("[object Object]"===Object.prototype.toString.call(collection))for(var prop in collection)Object.prototype.hasOwnProperty.call(collection,prop)&&callback.call(scope,collection[prop],prop,collection);else for(var i=0,len=collection.length;len>i;i++)callback.call(scope,collection[i],i,collection)},addCSS:function(css){var head=document.getElementsByTagName("head")[0],s=document.createElement("style");s.styleSheet?s.styleSheet.cssText=css:s.appendChild(document.createTextNode(css));head.appendChild(s)},isFunction:function(obj){return"function"==typeof obj},proxy:function(fn,context){var tmp,args,proxy,slice=[].slice;if("string"==typeof context){tmp=fn[context];context=fn;fn=tmp}if(!util.isFunction(fn))return void 0;args=slice.call(arguments,2);proxy=function(){return fn.apply(context||this,args.concat(slice.call(arguments)))};return proxy}};return util});
1
+ define(function(undef){"use strict";var util={getElem:function(id){return document.getElementById(id)},inArray:function(elem,arr,i){var len;if(arr){if(arr.indexOf)return arr.indexOf.call(arr,elem,i);len=arr.length;i=i?i<0?Math.max(0,len+i):i:0;for(;i<len;i++)if(i in arr&&arr[i]===elem)return i}return-1},isArray:function(arr){return"[object Array]"===Object.prototype.toString.call(arr)},extend:function(obj,ext){var i,l,name,value,args=arguments;for(i=1,l=args.length;i<l;i++){ext=args[i];for(name in ext)if(ext.hasOwnProperty(name)){value=ext[name];value!==undef&&(obj[name]=value)}}return obj},forEach:function(collection,callback,scope){if("[object Object]"===Object.prototype.toString.call(collection))for(var prop in collection)Object.prototype.hasOwnProperty.call(collection,prop)&&callback.call(scope,collection[prop],prop,collection);else for(var i=0,len=collection.length;i<len;i++)callback.call(scope,collection[i],i,collection)},addCSS:function(css){var head=document.getElementsByTagName("head")[0],s=document.createElement("style");s.styleSheet?s.styleSheet.cssText=css:s.appendChild(document.createTextNode(css));head.appendChild(s)},isFunction:function(obj){return"function"==typeof obj},proxy:function(fn,context){var tmp,args,proxy,slice=[].slice;if("string"==typeof context){tmp=fn[context];context=fn;fn=tmp}if(util.isFunction(fn)){args=slice.call(arguments,2);proxy=function(){return fn.apply(context||this,args.concat(slice.call(arguments)))};return proxy}}};return util});
js/esites_editor/dist/js/vendor/codemirror/addon/comment/comment.js CHANGED
@@ -103,6 +103,7 @@
103
  self.lineComment(from, to, options);
104
  return;
105
  }
 
106
 
107
  var end = Math.min(to.line, self.lastLine());
108
  if (end != from.line && to.ch == 0 && nonWS.test(self.getLine(end))) --end;
@@ -140,7 +141,7 @@
140
  var line = self.getLine(i);
141
  var found = line.indexOf(lineString);
142
  if (found > -1 && !/comment/.test(self.getTokenTypeAt(Pos(i, found + 1)))) found = -1;
143
- if (found == -1 && (i != end || i == start) && nonWS.test(line)) break lineComment;
144
  if (found > -1 && nonWS.test(line.slice(0, found))) break lineComment;
145
  lines.push(line);
146
  }
@@ -162,13 +163,15 @@
162
  var endString = options.blockCommentEnd || mode.blockCommentEnd;
163
  if (!startString || !endString) return false;
164
  var lead = options.blockCommentLead || mode.blockCommentLead;
165
- var startLine = self.getLine(start), endLine = end == start ? startLine : self.getLine(end);
166
- var open = startLine.indexOf(startString), close = endLine.lastIndexOf(endString);
 
 
167
  if (close == -1 && start != end) {
168
  endLine = self.getLine(--end);
169
- close = endLine.lastIndexOf(endString);
170
  }
171
- if (open == -1 || close == -1 ||
172
  !/comment/.test(self.getTokenTypeAt(Pos(start, open + 1))) ||
173
  !/comment/.test(self.getTokenTypeAt(Pos(end, close + 1))))
174
  return false;
103
  self.lineComment(from, to, options);
104
  return;
105
  }
106
+ if (/\bcomment\b/.test(self.getTokenTypeAt(Pos(from.line, 0)))) return
107
 
108
  var end = Math.min(to.line, self.lastLine());
109
  if (end != from.line && to.ch == 0 && nonWS.test(self.getLine(end))) --end;
141
  var line = self.getLine(i);
142
  var found = line.indexOf(lineString);
143
  if (found > -1 && !/comment/.test(self.getTokenTypeAt(Pos(i, found + 1)))) found = -1;
144
+ if (found == -1 && nonWS.test(line)) break lineComment;
145
  if (found > -1 && nonWS.test(line.slice(0, found))) break lineComment;
146
  lines.push(line);
147
  }
163
  var endString = options.blockCommentEnd || mode.blockCommentEnd;
164
  if (!startString || !endString) return false;
165
  var lead = options.blockCommentLead || mode.blockCommentLead;
166
+ var startLine = self.getLine(start), open = startLine.indexOf(startString)
167
+ if (open == -1) return false
168
+ var endLine = end == start ? startLine : self.getLine(end)
169
+ var close = endLine.indexOf(endString, end == start ? open + startString.length : 0);
170
  if (close == -1 && start != end) {
171
  endLine = self.getLine(--end);
172
+ close = endLine.indexOf(endString);
173
  }
174
+ if (close == -1 ||
175
  !/comment/.test(self.getTokenTypeAt(Pos(start, open + 1))) ||
176
  !/comment/.test(self.getTokenTypeAt(Pos(end, close + 1))))
177
  return false;
js/esites_editor/dist/js/vendor/codemirror/addon/display/rulers.js CHANGED
@@ -11,30 +11,26 @@
11
  })(function(CodeMirror) {
12
  "use strict";
13
 
14
- CodeMirror.defineOption("rulers", false, function(cm, val, old) {
15
- if (old && old != CodeMirror.Init) {
16
- clearRulers(cm);
17
- cm.off("refresh", refreshRulers);
 
18
  }
19
  if (val && val.length) {
20
- setRulers(cm);
21
- cm.on("refresh", refreshRulers);
 
 
22
  }
23
  });
24
 
25
- function clearRulers(cm) {
26
- for (var i = cm.display.lineSpace.childNodes.length - 1; i >= 0; i--) {
27
- var node = cm.display.lineSpace.childNodes[i];
28
- if (/(^|\s)CodeMirror-ruler($|\s)/.test(node.className))
29
- node.parentNode.removeChild(node);
30
- }
31
- }
32
-
33
- function setRulers(cm) {
34
  var val = cm.getOption("rulers");
35
  var cw = cm.defaultCharWidth();
36
  var left = cm.charCoords(CodeMirror.Pos(cm.firstLine(), 0), "div").left;
37
- var minH = cm.display.scroller.offsetHeight + 30;
38
  for (var i = 0; i < val.length; i++) {
39
  var elt = document.createElement("div");
40
  elt.className = "CodeMirror-ruler";
@@ -49,15 +45,7 @@
49
  if (conf.width) elt.style.borderLeftWidth = conf.width;
50
  }
51
  elt.style.left = (left + col * cw) + "px";
52
- elt.style.top = "-50px";
53
- elt.style.bottom = "-20px";
54
- elt.style.minHeight = minH + "px";
55
- cm.display.lineSpace.insertBefore(elt, cm.display.cursorDiv);
56
  }
57
  }
58
-
59
- function refreshRulers(cm) {
60
- clearRulers(cm);
61
- setRulers(cm);
62
- }
63
  });
11
  })(function(CodeMirror) {
12
  "use strict";
13
 
14
+ CodeMirror.defineOption("rulers", false, function(cm, val) {
15
+ if (cm.state.rulerDiv) {
16
+ cm.state.rulerDiv.parentElement.removeChild(cm.state.rulerDiv)
17
+ cm.state.rulerDiv = null
18
+ cm.off("refresh", drawRulers)
19
  }
20
  if (val && val.length) {
21
+ cm.state.rulerDiv = cm.display.lineSpace.parentElement.insertBefore(document.createElement("div"), cm.display.lineSpace)
22
+ cm.state.rulerDiv.className = "CodeMirror-rulers"
23
+ drawRulers(cm)
24
+ cm.on("refresh", drawRulers)
25
  }
26
  });
27
 
28
+ function drawRulers(cm) {
29
+ cm.state.rulerDiv.textContent = ""
 
 
 
 
 
 
 
30
  var val = cm.getOption("rulers");
31
  var cw = cm.defaultCharWidth();
32
  var left = cm.charCoords(CodeMirror.Pos(cm.firstLine(), 0), "div").left;
33
+ cm.state.rulerDiv.style.minHeight = (cm.display.scroller.offsetHeight + 30) + "px";
34
  for (var i = 0; i < val.length; i++) {
35
  var elt = document.createElement("div");
36
  elt.className = "CodeMirror-ruler";
45
  if (conf.width) elt.style.borderLeftWidth = conf.width;
46
  }
47
  elt.style.left = (left + col * cw) + "px";
48
+ cm.state.rulerDiv.appendChild(elt)
 
 
 
49
  }
50
  }
 
 
 
 
 
51
  });
js/esites_editor/dist/js/vendor/codemirror/addon/edit/closebrackets.js CHANGED
@@ -109,14 +109,16 @@
109
  var ranges = cm.listSelections();
110
  var opening = pos % 2 == 0;
111
 
112
- var type, next;
113
  for (var i = 0; i < ranges.length; i++) {
114
  var range = ranges[i], cur = range.head, curType;
115
  var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1));
116
  if (opening && !range.empty()) {
117
  curType = "surround";
118
  } else if ((identical || !opening) && next == ch) {
119
- if (triples.indexOf(ch) >= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch)
 
 
120
  curType = "skipThree";
121
  else
122
  curType = "skip";
@@ -192,4 +194,9 @@
192
  stream.start = stream.pos;
193
  }
194
  }
 
 
 
 
 
195
  });
109
  var ranges = cm.listSelections();
110
  var opening = pos % 2 == 0;
111
 
112
+ var type;
113
  for (var i = 0; i < ranges.length; i++) {
114
  var range = ranges[i], cur = range.head, curType;
115
  var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1));
116
  if (opening && !range.empty()) {
117
  curType = "surround";
118
  } else if ((identical || !opening) && next == ch) {
119
+ if (identical && stringStartsAfter(cm, cur))
120
+ curType = "both";
121
+ else if (triples.indexOf(ch) >= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch)
122
  curType = "skipThree";
123
  else
124
  curType = "skip";
194
  stream.start = stream.pos;
195
  }
196
  }
197
+
198
+ function stringStartsAfter(cm, pos) {
199
+ var token = cm.getTokenAt(Pos(pos.line, pos.ch + 1))
200
+ return /\bstring/.test(token.type) && token.start == pos.ch
201
+ }
202
  });
js/esites_editor/dist/js/vendor/codemirror/addon/edit/continuelist.js CHANGED
@@ -11,8 +11,8 @@
11
  })(function(CodeMirror) {
12
  "use strict";
13
 
14
- var listRE = /^(\s*)(>[> ]*|[*+-]\s|(\d+)([.)]))(\s*)/,
15
- emptyListRE = /^(\s*)(>[> ]*|[*+-]|(\d+)[.)])(\s*)$/,
16
  unorderedListRE = /[*+-]\s/;
17
 
18
  CodeMirror.commands.newlineAndIndentContinueMarkdownList = function(cm) {
@@ -39,7 +39,7 @@
39
  } else {
40
  var indent = match[1], after = match[5];
41
  var bullet = unorderedListRE.test(match[2]) || match[2].indexOf(">") >= 0
42
- ? match[2]
43
  : (parseInt(match[3], 10) + 1) + match[4];
44
 
45
  replacements[i] = "\n" + indent + bullet + after;
11
  })(function(CodeMirror) {
12
  "use strict";
13
 
14
+ var listRE = /^(\s*)(>[> ]*|- \[[x ]\]\s|[*+-]\s|(\d+)([.)]))(\s*)/,
15
+ emptyListRE = /^(\s*)(>[> ]*|- \[[x ]\]|[*+-]|(\d+)[.)])(\s*)$/,
16
  unorderedListRE = /[*+-]\s/;
17
 
18
  CodeMirror.commands.newlineAndIndentContinueMarkdownList = function(cm) {
39
  } else {
40
  var indent = match[1], after = match[5];
41
  var bullet = unorderedListRE.test(match[2]) || match[2].indexOf(">") >= 0
42
+ ? match[2].replace("x", " ")
43
  : (parseInt(match[3], 10) + 1) + match[4];
44
 
45
  replacements[i] = "\n" + indent + bullet + after;
js/esites_editor/dist/js/vendor/codemirror/addon/edit/matchbrackets.js CHANGED
@@ -102,8 +102,10 @@
102
  }
103
 
104
  CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) {
105
- if (old && old != CodeMirror.Init)
106
  cm.off("cursorActivity", doMatchBrackets);
 
 
107
  if (val) {
108
  cm.state.matchBrackets = typeof val == "object" ? val : {};
109
  cm.on("cursorActivity", doMatchBrackets);
102
  }
103
 
104
  CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) {
105
+ if (old && old != CodeMirror.Init) {
106
  cm.off("cursorActivity", doMatchBrackets);
107
+ if (currentlyHighlighted) {currentlyHighlighted(); currentlyHighlighted = null;}
108
+ }
109
  if (val) {
110
  cm.state.matchBrackets = typeof val == "object" ? val : {};
111
  cm.on("cursorActivity", doMatchBrackets);
js/esites_editor/dist/js/vendor/codemirror/addon/fold/brace-fold.js CHANGED
@@ -13,7 +13,7 @@
13
 
14
  CodeMirror.registerHelper("fold", "brace", function(cm, start) {
15
  var line = start.line, lineText = cm.getLine(line);
16
- var startCh, tokenType;
17
 
18
  function findOpening(openCh) {
19
  for (var at = start.ch, pass = 0;;) {
@@ -72,15 +72,15 @@ CodeMirror.registerHelper("fold", "import", function(cm, start) {
72
  }
73
  }
74
 
75
- var start = start.line, has = hasImport(start), prev;
76
- if (!has || hasImport(start - 1) || ((prev = hasImport(start - 2)) && prev.end.line == start - 1))
77
  return null;
78
  for (var end = has.end;;) {
79
  var next = hasImport(end.line + 1);
80
  if (next == null) break;
81
  end = next.end;
82
  }
83
- return {from: cm.clipPos(CodeMirror.Pos(start, has.startCh + 1)), to: end};
84
  });
85
 
86
  CodeMirror.registerHelper("fold", "include", function(cm, start) {
@@ -91,14 +91,14 @@ CodeMirror.registerHelper("fold", "include", function(cm, start) {
91
  if (start.type == "meta" && start.string.slice(0, 8) == "#include") return start.start + 8;
92
  }
93
 
94
- var start = start.line, has = hasInclude(start);
95
- if (has == null || hasInclude(start - 1) != null) return null;
96
- for (var end = start;;) {
97
  var next = hasInclude(end + 1);
98
  if (next == null) break;
99
  ++end;
100
  }
101
- return {from: CodeMirror.Pos(start, has + 1),
102
  to: cm.clipPos(CodeMirror.Pos(end))};
103
  });
104
 
13
 
14
  CodeMirror.registerHelper("fold", "brace", function(cm, start) {
15
  var line = start.line, lineText = cm.getLine(line);
16
+ var tokenType;
17
 
18
  function findOpening(openCh) {
19
  for (var at = start.ch, pass = 0;;) {
72
  }
73
  }
74
 
75
+ var startLine = start.line, has = hasImport(startLine), prev;
76
+ if (!has || hasImport(startLine - 1) || ((prev = hasImport(startLine - 2)) && prev.end.line == startLine - 1))
77
  return null;
78
  for (var end = has.end;;) {
79
  var next = hasImport(end.line + 1);
80
  if (next == null) break;
81
  end = next.end;
82
  }
83
+ return {from: cm.clipPos(CodeMirror.Pos(startLine, has.startCh + 1)), to: end};
84
  });
85
 
86
  CodeMirror.registerHelper("fold", "include", function(cm, start) {
91
  if (start.type == "meta" && start.string.slice(0, 8) == "#include") return start.start + 8;
92
  }
93
 
94
+ var startLine = start.line, has = hasInclude(startLine);
95
+ if (has == null || hasInclude(startLine - 1) != null) return null;
96
+ for (var end = startLine;;) {
97
  var next = hasInclude(end + 1);
98
  if (next == null) break;
99
  ++end;
100
  }
101
+ return {from: CodeMirror.Pos(startLine, has + 1),
102
  to: cm.clipPos(CodeMirror.Pos(end))};
103
  });
104
 
js/esites_editor/dist/js/vendor/codemirror/addon/fold/comment-fold.js CHANGED
@@ -29,7 +29,7 @@ CodeMirror.registerGlobalHelper("fold", "comment", function(mode) {
29
  }
30
  if (pass == 1 && found < start.ch) return;
31
  if (/comment/.test(cm.getTokenTypeAt(CodeMirror.Pos(line, found + 1))) &&
32
- (lineText.slice(found - endToken.length, found) == endToken ||
33
  !/comment/.test(cm.getTokenTypeAt(CodeMirror.Pos(line, found))))) {
34
  startCh = found + startToken.length;
35
  break;
29
  }
30
  if (pass == 1 && found < start.ch) return;
31
  if (/comment/.test(cm.getTokenTypeAt(CodeMirror.Pos(line, found + 1))) &&
32
+ (found == 0 || lineText.slice(found - endToken.length, found) == endToken ||
33
  !/comment/.test(cm.getTokenTypeAt(CodeMirror.Pos(line, found))))) {
34
  startCh = found + startToken.length;
35
  break;
js/esites_editor/dist/js/vendor/codemirror/addon/fold/foldcode.js CHANGED
@@ -49,7 +49,7 @@
49
  });
50
  var myRange = cm.markText(range.from, range.to, {
51
  replacedWith: myWidget,
52
- clearOnEnter: true,
53
  __isFold: true
54
  });
55
  myRange.on("clear", function(from, to) {
@@ -129,7 +129,8 @@
129
  rangeFinder: CodeMirror.fold.auto,
130
  widget: "\u2194",
131
  minFoldSize: 0,
132
- scanUp: false
 
133
  };
134
 
135
  CodeMirror.defineOption("foldOptions", null);
49
  });
50
  var myRange = cm.markText(range.from, range.to, {
51
  replacedWith: myWidget,
52
+ clearOnEnter: getOption(cm, options, "clearOnEnter"),
53
  __isFold: true
54
  });
55
  myRange.on("clear", function(from, to) {
129
  rangeFinder: CodeMirror.fold.auto,
130
  widget: "\u2194",
131
  minFoldSize: 0,
132
+ scanUp: false,
133
+ clearOnEnter: true
134
  };
135
 
136
  CodeMirror.defineOption("foldOptions", null);
js/esites_editor/dist/js/vendor/codemirror/addon/fold/foldgutter.js CHANGED
@@ -50,7 +50,7 @@
50
  }
51
 
52
  function isFolded(cm, line) {
53
- var marks = cm.findMarksAt(Pos(line));
54
  for (var i = 0; i < marks.length; ++i)
55
  if (marks[i].__isFold && marks[i].find().from.line == line) return marks[i];
56
  }
50
  }
51
 
52
  function isFolded(cm, line) {
53
+ var marks = cm.findMarks(Pos(line, 0), Pos(line + 1, 0));
54
  for (var i = 0; i < marks.length; ++i)
55
  if (marks[i].__isFold && marks[i].find().from.line == line) return marks[i];
56
  }
js/esites_editor/dist/js/vendor/codemirror/addon/fold/xml-fold.js CHANGED
@@ -21,8 +21,8 @@
21
  function Iter(cm, line, ch, range) {
22
  this.line = line; this.ch = ch;
23
  this.cm = cm; this.text = cm.getLine(line);
24
- this.min = range ? range.from : cm.firstLine();
25
- this.max = range ? range.to - 1 : cm.lastLine();
26
  }
27
 
28
  function tagAt(iter, ch) {
@@ -140,9 +140,9 @@
140
  var openTag = toNextTag(iter), end;
141
  if (!openTag || iter.line != start.line || !(end = toTagEnd(iter))) return;
142
  if (!openTag[1] && end != "selfClose") {
143
- var start = Pos(iter.line, iter.ch);
144
- var close = findMatchingClose(iter, openTag[2]);
145
- return close && {from: start, to: close.from};
146
  }
147
  }
148
  });
21
  function Iter(cm, line, ch, range) {
22
  this.line = line; this.ch = ch;
23
  this.cm = cm; this.text = cm.getLine(line);
24
+ this.min = range ? Math.max(range.from, cm.firstLine()) : cm.firstLine();
25
+ this.max = range ? Math.min(range.to - 1, cm.lastLine()) : cm.lastLine();
26
  }
27
 
28
  function tagAt(iter, ch) {
140
  var openTag = toNextTag(iter), end;
141
  if (!openTag || iter.line != start.line || !(end = toTagEnd(iter))) return;
142
  if (!openTag[1] && end != "selfClose") {
143
+ var startPos = Pos(iter.line, iter.ch);
144
+ var endPos = findMatchingClose(iter, openTag[2]);
145
+ return endPos && {from: startPos, to: endPos.from};
146
  }
147
  }
148
  });
js/esites_editor/dist/js/vendor/codemirror/addon/hint/javascript-hint.js CHANGED
@@ -97,6 +97,15 @@
97
  var coffeescriptKeywords = ("and break catch class continue delete do else extends false finally for " +
98
  "if in instanceof isnt new no not null of off on or return switch then throw true try typeof until void while with yes").split(" ");
99
 
 
 
 
 
 
 
 
 
 
100
  function getCompletions(token, context, keywords, options) {
101
  var found = [], start = token.string, global = options && options.globalScope || window;
102
  function maybeAdd(str) {
@@ -106,7 +115,7 @@
106
  if (typeof obj == "string") forEach(stringProps, maybeAdd);
107
  else if (obj instanceof Array) forEach(arrayProps, maybeAdd);
108
  else if (obj instanceof Function) forEach(funcProps, maybeAdd);
109
- for (var name in obj) maybeAdd(name);
110
  }
111
 
112
  if (context && context.length) {
97
  var coffeescriptKeywords = ("and break catch class continue delete do else extends false finally for " +
98
  "if in instanceof isnt new no not null of off on or return switch then throw true try typeof until void while with yes").split(" ");
99
 
100
+ function forAllProps(obj, callback) {
101
+ if (!Object.getOwnPropertyNames || !Object.getPrototypeOf) {
102
+ for (var name in obj) callback(name)
103
+ } else {
104
+ for (var o = obj; o; o = Object.getPrototypeOf(o))
105
+ Object.getOwnPropertyNames(o).forEach(callback)
106
+ }
107
+ }
108
+
109
  function getCompletions(token, context, keywords, options) {
110
  var found = [], start = token.string, global = options && options.globalScope || window;
111
  function maybeAdd(str) {
115
  if (typeof obj == "string") forEach(stringProps, maybeAdd);
116
  else if (obj instanceof Array) forEach(arrayProps, maybeAdd);
117
  else if (obj instanceof Function) forEach(funcProps, maybeAdd);
118
+ forAllProps(obj, maybeAdd)
119
  }
120
 
121
  if (context && context.length) {
js/esites_editor/dist/js/vendor/codemirror/addon/hint/show-hint.css CHANGED
@@ -25,8 +25,6 @@
25
  margin: 0;
26
  padding: 0 4px;
27
  border-radius: 2px;
28
- max-width: 19em;
29
- overflow: hidden;
30
  white-space: pre;
31
  color: black;
32
  cursor: pointer;
25
  margin: 0;
26
  padding: 0 4px;
27
  border-radius: 2px;
 
 
28
  white-space: pre;
29
  color: black;
30
  cursor: pointer;
js/esites_editor/dist/js/vendor/codemirror/addon/hint/show-hint.js CHANGED
@@ -229,6 +229,9 @@
229
  var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight);
230
  (completion.options.container || document.body).appendChild(hints);
231
  var box = hints.getBoundingClientRect(), overlapY = box.bottom - winH;
 
 
 
232
  if (overlapY > 0) {
233
  var height = box.bottom - box.top, curTop = pos.top - (pos.bottom - box.top);
234
  if (curTop - height > 0) { // Fits above cursor
@@ -253,6 +256,8 @@
253
  }
254
  hints.style.left = (left = pos.left - overlapX) + "px";
255
  }
 
 
256
 
257
  cm.addKeyMap(this.keyMap = buildKeyMap(completion, {
258
  moveFocus: function(n, avoidWrap) { widget.changeActive(widget.selectedHint + n, avoidWrap); },
@@ -270,7 +275,6 @@
270
  cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); });
271
  }
272
 
273
- var startScroll = cm.getScrollInfo();
274
  cm.on("scroll", this.onScroll = function() {
275
  var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect();
276
  var newTop = top + startScroll.top - curScroll.top;
229
  var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight);
230
  (completion.options.container || document.body).appendChild(hints);
231
  var box = hints.getBoundingClientRect(), overlapY = box.bottom - winH;
232
+ var scrolls = hints.scrollHeight > hints.clientHeight + 1
233
+ var startScroll = cm.getScrollInfo();
234
+
235
  if (overlapY > 0) {
236
  var height = box.bottom - box.top, curTop = pos.top - (pos.bottom - box.top);
237
  if (curTop - height > 0) { // Fits above cursor
256
  }
257
  hints.style.left = (left = pos.left - overlapX) + "px";
258
  }
259
+ if (scrolls) for (var node = hints.firstChild; node; node = node.nextSibling)
260
+ node.style.paddingRight = cm.display.nativeBarWidth + "px"
261
 
262
  cm.addKeyMap(this.keyMap = buildKeyMap(completion, {
263
  moveFocus: function(n, avoidWrap) { widget.changeActive(widget.selectedHint + n, avoidWrap); },
275
  cm.on("focus", this.onFocus = function() { clearTimeout(closingOnBlur); });
276
  }
277
 
 
278
  cm.on("scroll", this.onScroll = function() {
279
  var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect();
280
  var newTop = top + startScroll.top - curScroll.top;
js/esites_editor/dist/js/vendor/codemirror/addon/hint/sql-hint.js CHANGED
@@ -18,7 +18,7 @@
18
  QUERY_DIV: ";",
19
  ALIAS_KEYWORD: "AS"
20
  };
21
- var Pos = CodeMirror.Pos;
22
 
23
  function isArray(val) { return Object.prototype.toString.call(val) == "[object Array]" }
24
 
@@ -178,15 +178,6 @@
178
  }
179
  }
180
 
181
- function convertCurToNumber(cur) {
182
- // max characters of a line is 999,999.
183
- return cur.line + cur.ch / Math.pow(10, 6);
184
- }
185
-
186
- function convertNumberToCur(num) {
187
- return Pos(Math.floor(num), +num.toString().split('.').pop());
188
- }
189
-
190
  function findTableByAlias(alias, editor) {
191
  var doc = editor.doc;
192
  var fullQuery = doc.getValue();
@@ -209,15 +200,14 @@
209
  separator.push(Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).text.length));
210
 
211
  //find valid range
212
- var prevItem = 0;
213
- var current = convertCurToNumber(editor.getCursor());
214
  for (var i = 0; i < separator.length; i++) {
215
- var _v = convertCurToNumber(separator[i]);
216
- if (current > prevItem && current <= _v) {
217
- validRange = { start: convertNumberToCur(prevItem), end: convertNumberToCur(_v) };
218
  break;
219
  }
220
- prevItem = _v;
221
  }
222
 
223
  var query = doc.getRange(validRange.start, validRange.end, false);
@@ -241,7 +231,7 @@
241
  var defaultTableName = options && options.defaultTable;
242
  var disableKeywords = options && options.disableKeywords;
243
  defaultTable = defaultTableName && getTable(defaultTableName);
244
- keywords = keywords || getKeywords(editor);
245
 
246
  if (defaultTableName && !defaultTable)
247
  defaultTable = findTableByAlias(defaultTableName, editor);
18
  QUERY_DIV: ";",
19
  ALIAS_KEYWORD: "AS"
20
  };
21
+ var Pos = CodeMirror.Pos, cmpPos = CodeMirror.cmpPos;
22
 
23
  function isArray(val) { return Object.prototype.toString.call(val) == "[object Array]" }
24
 
178
  }
179
  }
180
 
 
 
 
 
 
 
 
 
 
181
  function findTableByAlias(alias, editor) {
182
  var doc = editor.doc;
183
  var fullQuery = doc.getValue();
200
  separator.push(Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).text.length));
201
 
202
  //find valid range
203
+ var prevItem = null;
204
+ var current = editor.getCursor()
205
  for (var i = 0; i < separator.length; i++) {
206
+ if ((prevItem == null || cmpPos(current, prevItem) > 0) && cmpPos(current, separator[i]) <= 0) {
207
+ validRange = {start: prevItem, end: separator[i]};
 
208
  break;
209
  }
210
+ prevItem = separator[i];
211
  }
212
 
213
  var query = doc.getRange(validRange.start, validRange.end, false);
231
  var defaultTableName = options && options.defaultTable;
232
  var disableKeywords = options && options.disableKeywords;
233
  defaultTable = defaultTableName && getTable(defaultTableName);
234
+ keywords = getKeywords(editor);
235
 
236
  if (defaultTableName && !defaultTable)
237
  defaultTable = findTableByAlias(defaultTableName, editor);
js/esites_editor/dist/js/vendor/codemirror/addon/lint/lint.css CHANGED
@@ -4,10 +4,10 @@
4
  }
5
 
6
  .CodeMirror-lint-tooltip {
7
- background-color: infobackground;
8
  border: 1px solid black;
9
  border-radius: 4px 4px 4px 4px;
10
- color: infotext;
11
  font-family: monospace;
12
  font-size: 10pt;
13
  overflow: hidden;
4
  }
5
 
6
  .CodeMirror-lint-tooltip {
7
+ background-color: #ffd;
8
  border: 1px solid black;
9
  border-radius: 4px 4px 4px 4px;
10
+ color: black;
11
  font-family: monospace;
12
  font-size: 10pt;
13
  overflow: hidden;
js/esites_editor/dist/js/vendor/codemirror/addon/lint/lint.js CHANGED
@@ -226,7 +226,7 @@
226
  var state = cm.state.lint = new LintState(cm, parseOptions(cm, val), hasLintGutter);
227
  if (state.options.lintOnChange !== false)
228
  cm.on("change", onChange);
229
- if (state.options.tooltips != false)
230
  CodeMirror.on(cm.getWrapperElement(), "mouseover", state.onMouseOver);
231
 
232
  startLinting(cm);
226
  var state = cm.state.lint = new LintState(cm, parseOptions(cm, val), hasLintGutter);
227
  if (state.options.lintOnChange !== false)
228
  cm.on("change", onChange);
229
+ if (state.options.tooltips != false && state.options.tooltips != "gutter")
230
  CodeMirror.on(cm.getWrapperElement(), "mouseover", state.onMouseOver);
231
 
232
  startLinting(cm);
js/esites_editor/dist/js/vendor/codemirror/addon/merge/merge.js CHANGED
@@ -40,12 +40,17 @@
40
  (this.edit.state.diffViews || (this.edit.state.diffViews = [])).push(this);
41
  this.orig = CodeMirror(pane, copyObj({value: orig, readOnly: !this.mv.options.allowEditingOriginals}, copyObj(options)));
42
  this.orig.state.diffViews = [this];
 
 
 
43
 
44
  this.diff = getDiff(asString(orig), asString(options.value));
45
  this.chunks = getChunks(this.diff);
46
  this.diffOutOfDate = this.dealigned = false;
47
 
48
  this.showDifferences = options.showDifferences !== false;
 
 
49
  this.forceUpdate = registerUpdate(this);
50
  setScrollLock(this, true, false);
51
  registerScroll(this);
@@ -88,10 +93,11 @@
88
  updateMarks(dv.edit, dv.diff, edit, DIFF_INSERT, dv.classes);
89
  updateMarks(dv.orig, dv.diff, orig, DIFF_DELETE, dv.classes);
90
  }
91
- makeConnections(dv);
92
 
93
  if (dv.mv.options.connect == "align")
94
  alignChunks(dv);
 
 
95
  updating = false;
96
  }
97
  function setDealign(fast) {
@@ -113,8 +119,14 @@
113
  // Update faster when a line was added/removed
114
  setDealign(change.text.length - 1 != change.to.line - change.from.line);
115
  }
 
 
 
 
116
  dv.edit.on("change", change);
117
  dv.orig.on("change", change);
 
 
118
  dv.edit.on("markerAdded", setDealign);
119
  dv.edit.on("markerCleared", setDealign);
120
  dv.orig.on("markerAdded", setDealign);
@@ -191,16 +203,22 @@
191
 
192
  // Updating the marks for editor content
193
 
 
 
 
 
 
 
 
 
 
194
  function clearMarks(editor, arr, classes) {
195
  for (var i = 0; i < arr.length; ++i) {
196
  var mark = arr[i];
197
- if (mark instanceof CodeMirror.TextMarker) {
198
  mark.clear();
199
- } else if (mark.parent) {
200
- editor.removeLineClass(mark, "background", classes.chunk);
201
- editor.removeLineClass(mark, "background", classes.start);
202
- editor.removeLineClass(mark, "background", classes.end);
203
- }
204
  }
205
  arr.length = 0;
206
  }
@@ -226,24 +244,30 @@
226
  });
227
  }
228
 
 
 
 
 
 
 
 
 
 
 
229
  function markChanges(editor, diff, type, marks, from, to, classes) {
230
  var pos = Pos(0, 0);
231
  var top = Pos(from, 0), bot = editor.clipPos(Pos(to - 1));
232
  var cls = type == DIFF_DELETE ? classes.del : classes.insert;
233
  function markChunk(start, end) {
234
  var bfrom = Math.max(from, start), bto = Math.min(to, end);
235
- for (var i = bfrom; i < bto; ++i) {
236
- var line = editor.addLineClass(i, "background", classes.chunk);
237
- if (i == start) editor.addLineClass(line, "background", classes.start);
238
- if (i == end - 1) editor.addLineClass(line, "background", classes.end);
239
- marks.push(line);
240
- }
241
  // When the chunk is empty, make sure a horizontal line shows up
242
  if (start == end && bfrom == end && bto == end) {
243
  if (bfrom)
244
- marks.push(editor.addLineClass(bfrom - 1, "background", classes.end));
245
  else
246
- marks.push(editor.addLineClass(bfrom, "background", classes.start));
247
  }
248
  }
249
 
@@ -284,7 +308,9 @@
284
  if (dv.copyButtons) clear(dv.copyButtons);
285
 
286
  var vpEdit = dv.edit.getViewport(), vpOrig = dv.orig.getViewport();
287
- var sTopEdit = dv.edit.getScrollInfo().top, sTopOrig = dv.orig.getScrollInfo().top;
 
 
288
  for (var i = 0; i < dv.chunks.length; i++) {
289
  var ch = dv.chunks[i];
290
  if (ch.editFrom <= vpEdit.to && ch.editTo >= vpEdit.from &&
@@ -312,19 +338,14 @@
312
  linesToAlign.push([chunk.origTo, chunk.editTo, other ? getMatchingOrigLine(chunk.editTo, other.chunks) : null]);
313
  }
314
  if (other) {
315
- for (var i = 0; i < other.chunks.length; i++) {
316
  var chunk = other.chunks[i];
317
  for (var j = 0; j < linesToAlign.length; j++) {
318
- var align = linesToAlign[j];
319
- if (align[1] == chunk.editTo) {
320
- j = -1;
321
- break;
322
- } else if (align[1] > chunk.editTo) {
323
- break;
324
- }
325
  }
326
- if (j > -1)
327
- linesToAlign.splice(j - 1, 0, [getMatchingOrigLine(chunk.editTo, dv.chunks), chunk.editTo, chunk.origTo]);
328
  }
329
  }
330
  return linesToAlign;
@@ -390,13 +411,13 @@
390
 
391
  function drawConnectorsForChunk(dv, chunk, sTopOrig, sTopEdit, w) {
392
  var flip = dv.type == "left";
393
- var top = dv.orig.heightAtLine(chunk.origFrom, "local") - sTopOrig;
394
  if (dv.svg) {
395
  var topLpx = top;
396
- var topRpx = dv.edit.heightAtLine(chunk.editFrom, "local") - sTopEdit;
397
  if (flip) { var tmp = topLpx; topLpx = topRpx; topRpx = tmp; }
398
- var botLpx = dv.orig.heightAtLine(chunk.origTo, "local") - sTopOrig;
399
- var botRpx = dv.edit.heightAtLine(chunk.editTo, "local") - sTopEdit;
400
  if (flip) { var tmp = botLpx; botLpx = botRpx; botRpx = tmp; }
401
  var curveTop = " C " + w/2 + " " + topRpx + " " + w/2 + " " + topLpx + " " + (w + 2) + " " + topLpx;
402
  var curveBot = " C " + w/2 + " " + botLpx + " " + w/2 + " " + botRpx + " -1 " + botRpx;
@@ -447,18 +468,18 @@
447
 
448
  if (hasLeft) {
449
  left = this.left = new DiffView(this, "left");
450
- var leftPane = elt("div", null, "CodeMirror-merge-pane");
451
  wrap.push(leftPane);
452
  wrap.push(buildGap(left));
453
  }
454
 
455
- var editPane = elt("div", null, "CodeMirror-merge-pane");
456
  wrap.push(editPane);
457
 
458
  if (hasRight) {
459
  right = this.right = new DiffView(this, "right");
460
  wrap.push(buildGap(right));
461
- var rightPane = elt("div", null, "CodeMirror-merge-pane");
462
  wrap.push(rightPane);
463
  }
464
 
@@ -471,7 +492,6 @@
471
 
472
  if (left) left.init(leftPane, origLeft, options);
473
  if (right) right.init(rightPane, origRight, options);
474
-
475
  if (options.collapseIdentical)
476
  this.editor().operation(function() {
477
  collapseIdenticalStretches(self, options.collapseIdentical);
@@ -480,6 +500,9 @@
480
  this.aligners = [];
481
  alignChunks(this.left || this.right, true);
482
  }
 
 
 
483
 
484
  var onResize = function() {
485
  if (left) makeConnections(left);
@@ -522,7 +545,7 @@
522
  }
523
 
524
  MergeView.prototype = {
525
- constuctor: MergeView,
526
  editor: function() { return this.edit; },
527
  rightOriginal: function() { return this.right && this.right.orig; },
528
  leftOriginal: function() { return this.left && this.left.orig; },
@@ -548,7 +571,6 @@
548
  var dmp = new diff_match_patch();
549
  function getDiff(a, b) {
550
  var diff = dmp.diff_main(a, b);
551
- dmp.diff_cleanupSemantic(diff);
552
  // The library sometimes leaves in empty parts, which confuse the algorithm
553
  for (var i = 0; i < diff.length; ++i) {
554
  var part = diff[i];
40
  (this.edit.state.diffViews || (this.edit.state.diffViews = [])).push(this);
41
  this.orig = CodeMirror(pane, copyObj({value: orig, readOnly: !this.mv.options.allowEditingOriginals}, copyObj(options)));
42
  this.orig.state.diffViews = [this];
43
+ var classLocation = options.chunkClassLocation || "background";
44
+ if (Object.prototype.toString.call(classLocation) != "[object Array]") classLocation = [classLocation]
45
+ this.classes.classLocation = classLocation
46
 
47
  this.diff = getDiff(asString(orig), asString(options.value));
48
  this.chunks = getChunks(this.diff);
49
  this.diffOutOfDate = this.dealigned = false;
50
 
51
  this.showDifferences = options.showDifferences !== false;
52
+ },
53
+ registerEvents: function() {
54
  this.forceUpdate = registerUpdate(this);
55
  setScrollLock(this, true, false);
56
  registerScroll(this);
93
  updateMarks(dv.edit, dv.diff, edit, DIFF_INSERT, dv.classes);
94
  updateMarks(dv.orig, dv.diff, orig, DIFF_DELETE, dv.classes);
95
  }
 
96
 
97
  if (dv.mv.options.connect == "align")
98
  alignChunks(dv);
99
+ makeConnections(dv);
100
+
101
  updating = false;
102
  }
103
  function setDealign(fast) {
119
  // Update faster when a line was added/removed
120
  setDealign(change.text.length - 1 != change.to.line - change.from.line);
121
  }
122
+ function swapDoc() {
123
+ dv.diffOutOfDate = true;
124
+ update("full");
125
+ }
126
  dv.edit.on("change", change);
127
  dv.orig.on("change", change);
128
+ dv.edit.on("swapDoc", swapDoc);
129
+ dv.orig.on("swapDoc", swapDoc);
130
  dv.edit.on("markerAdded", setDealign);
131
  dv.edit.on("markerCleared", setDealign);
132
  dv.orig.on("markerAdded", setDealign);
203
 
204
  // Updating the marks for editor content
205
 
206
+ function removeClass(editor, line, classes) {
207
+ var locs = classes.classLocation
208
+ for (var i = 0; i < locs.length; i++) {
209
+ editor.removeLineClass(line, locs[i], classes.chunk);
210
+ editor.removeLineClass(line, locs[i], classes.start);
211
+ editor.removeLineClass(line, locs[i], classes.end);
212
+ }
213
+ }
214
+
215
  function clearMarks(editor, arr, classes) {
216
  for (var i = 0; i < arr.length; ++i) {
217
  var mark = arr[i];
218
+ if (mark instanceof CodeMirror.TextMarker)
219
  mark.clear();
220
+ else if (mark.parent)
221
+ removeClass(editor, mark, classes);
 
 
 
222
  }
223
  arr.length = 0;
224
  }
244
  });
245
  }
246
 
247
+ function addClass(editor, lineNr, classes, main, start, end) {
248
+ var locs = classes.classLocation, line = editor.getLineHandle(lineNr);
249
+ for (var i = 0; i < locs.length; i++) {
250
+ if (main) editor.addLineClass(line, locs[i], classes.chunk);
251
+ if (start) editor.addLineClass(line, locs[i], classes.start);
252
+ if (end) editor.addLineClass(line, locs[i], classes.end);
253
+ }
254
+ return line;
255
+ }
256
+
257
  function markChanges(editor, diff, type, marks, from, to, classes) {
258
  var pos = Pos(0, 0);
259
  var top = Pos(from, 0), bot = editor.clipPos(Pos(to - 1));
260
  var cls = type == DIFF_DELETE ? classes.del : classes.insert;
261
  function markChunk(start, end) {
262
  var bfrom = Math.max(from, start), bto = Math.min(to, end);
263
+ for (var i = bfrom; i < bto; ++i)
264
+ marks.push(addClass(editor, i, classes, true, i == start, i == end - 1));
 
 
 
 
265
  // When the chunk is empty, make sure a horizontal line shows up
266
  if (start == end && bfrom == end && bto == end) {
267
  if (bfrom)
268
+ marks.push(addClass(editor, bfrom - 1, classes, false, false, true));
269
  else
270
+ marks.push(addClass(editor, bfrom, classes, false, true, false));
271
  }
272
  }
273
 
308
  if (dv.copyButtons) clear(dv.copyButtons);
309
 
310
  var vpEdit = dv.edit.getViewport(), vpOrig = dv.orig.getViewport();
311
+ var outerTop = dv.mv.wrap.getBoundingClientRect().top
312
+ var sTopEdit = outerTop - dv.edit.getScrollerElement().getBoundingClientRect().top + dv.edit.getScrollInfo().top
313
+ var sTopOrig = outerTop - dv.orig.getScrollerElement().getBoundingClientRect().top + dv.orig.getScrollInfo().top;
314
  for (var i = 0; i < dv.chunks.length; i++) {
315
  var ch = dv.chunks[i];
316
  if (ch.editFrom <= vpEdit.to && ch.editTo >= vpEdit.from &&
338
  linesToAlign.push([chunk.origTo, chunk.editTo, other ? getMatchingOrigLine(chunk.editTo, other.chunks) : null]);
339
  }
340
  if (other) {
341
+ chunkLoop: for (var i = 0; i < other.chunks.length; i++) {
342
  var chunk = other.chunks[i];
343
  for (var j = 0; j < linesToAlign.length; j++) {
344
+ var diff = linesToAlign[j][1] - chunk.editTo;
345
+ if (diff == 0) continue chunkLoop
346
+ if (diff > 0) break;
 
 
 
 
347
  }
348
+ linesToAlign.splice(j, 0, [getMatchingOrigLine(chunk.editTo, dv.chunks), chunk.editTo, chunk.origTo]);
 
349
  }
350
  }
351
  return linesToAlign;
411
 
412
  function drawConnectorsForChunk(dv, chunk, sTopOrig, sTopEdit, w) {
413
  var flip = dv.type == "left";
414
+ var top = dv.orig.heightAtLine(chunk.origFrom, "local", true) - sTopOrig;
415
  if (dv.svg) {
416
  var topLpx = top;
417
+ var topRpx = dv.edit.heightAtLine(chunk.editFrom, "local", true) - sTopEdit;
418
  if (flip) { var tmp = topLpx; topLpx = topRpx; topRpx = tmp; }
419
+ var botLpx = dv.orig.heightAtLine(chunk.origTo, "local", true) - sTopOrig;
420
+ var botRpx = dv.edit.heightAtLine(chunk.editTo, "local", true) - sTopEdit;
421
  if (flip) { var tmp = botLpx; botLpx = botRpx; botRpx = tmp; }
422
  var curveTop = " C " + w/2 + " " + topRpx + " " + w/2 + " " + topLpx + " " + (w + 2) + " " + topLpx;
423
  var curveBot = " C " + w/2 + " " + botLpx + " " + w/2 + " " + botRpx + " -1 " + botRpx;
468
 
469
  if (hasLeft) {
470
  left = this.left = new DiffView(this, "left");
471
+ var leftPane = elt("div", null, "CodeMirror-merge-pane CodeMirror-merge-left");
472
  wrap.push(leftPane);
473
  wrap.push(buildGap(left));
474
  }
475
 
476
+ var editPane = elt("div", null, "CodeMirror-merge-pane CodeMirror-merge-editor");
477
  wrap.push(editPane);
478
 
479
  if (hasRight) {
480
  right = this.right = new DiffView(this, "right");
481
  wrap.push(buildGap(right));
482
+ var rightPane = elt("div", null, "CodeMirror-merge-pane CodeMirror-merge-right");
483
  wrap.push(rightPane);
484
  }
485
 
492
 
493
  if (left) left.init(leftPane, origLeft, options);
494
  if (right) right.init(rightPane, origRight, options);
 
495
  if (options.collapseIdentical)
496
  this.editor().operation(function() {
497
  collapseIdenticalStretches(self, options.collapseIdentical);
500
  this.aligners = [];
501
  alignChunks(this.left || this.right, true);
502
  }
503
+ if (left) left.registerEvents()
504
+ if (right) right.registerEvents()
505
+
506
 
507
  var onResize = function() {
508
  if (left) makeConnections(left);
545
  }
546
 
547
  MergeView.prototype = {
548
+ constructor: MergeView,
549
  editor: function() { return this.edit; },
550
  rightOriginal: function() { return this.right && this.right.orig; },
551
  leftOriginal: function() { return this.left && this.left.orig; },
571
  var dmp = new diff_match_patch();
572
  function getDiff(a, b) {
573
  var diff = dmp.diff_main(a, b);
 
574
  // The library sometimes leaves in empty parts, which confuse the algorithm
575
  for (var i = 0; i < diff.length; ++i) {
576
  var part = diff[i];
js/esites_editor/dist/js/vendor/codemirror/addon/mode/overlay.js CHANGED
@@ -76,8 +76,13 @@ CodeMirror.overlayMode = function(base, overlay, combine) {
76
  innerMode: function(state) { return {state: state.base, mode: base}; },
77
 
78
  blankLine: function(state) {
79
- if (base.blankLine) base.blankLine(state.base);
80
- if (overlay.blankLine) overlay.blankLine(state.overlay);
 
 
 
 
 
81
  }
82
  };
83
  };
76
  innerMode: function(state) { return {state: state.base, mode: base}; },
77
 
78
  blankLine: function(state) {
79
+ var baseToken, overlayToken;
80
+ if (base.blankLine) baseToken = base.blankLine(state.base);
81
+ if (overlay.blankLine) overlayToken = overlay.blankLine(state.overlay);
82
+
83
+ return overlayToken == null ?
84
+ baseToken :
85
+ (combine && baseToken != null ? baseToken + " " + overlayToken : overlayToken);
86
  }
87
  };
88
  };
js/esites_editor/dist/js/vendor/codemirror/addon/scroll/scrollpastend.js CHANGED
@@ -40,7 +40,9 @@
40
  if (cm.state.scrollPastEndPadding != padding) {
41
  cm.state.scrollPastEndPadding = padding;
42
  cm.display.lineSpace.parentNode.style.paddingBottom = padding;
 
43
  cm.setSize();
 
44
  }
45
  }
46
  });
40
  if (cm.state.scrollPastEndPadding != padding) {
41
  cm.state.scrollPastEndPadding = padding;
42
  cm.display.lineSpace.parentNode.style.paddingBottom = padding;
43
+ cm.off("refresh", updateBottomMargin);
44
  cm.setSize();
45
+ cm.on("refresh", updateBottomMargin);
46
  }
47
  }
48
  });
js/esites_editor/dist/js/vendor/codemirror/addon/scroll/simplescrollbars.js CHANGED
@@ -59,10 +59,10 @@
59
  CodeMirror.on(this.node, "DOMMouseScroll", onWheel);
60
  }
61
 
62
- Bar.prototype.setPos = function(pos) {
63
  if (pos < 0) pos = 0;
64
  if (pos > this.total - this.screen) pos = this.total - this.screen;
65
- if (pos == this.pos) return false;
66
  this.pos = pos;
67
  this.inner.style[this.orientation == "horizontal" ? "left" : "top"] =
68
  (pos * (this.size / this.total)) + "px";
@@ -76,9 +76,12 @@
76
  var minButtonSize = 10;
77
 
78
  Bar.prototype.update = function(scrollSize, clientSize, barSize) {
79
- this.screen = clientSize;
80
- this.total = scrollSize;
81
- this.size = barSize;
 
 
 
82
 
83
  var buttonSize = this.screen * (this.size / this.total);
84
  if (buttonSize < minButtonSize) {
@@ -87,7 +90,7 @@
87
  }
88
  this.inner.style[this.orientation == "horizontal" ? "width" : "height"] =
89
  buttonSize + "px";
90
- this.setPos(this.pos);
91
  };
92
 
93
  function SimpleScrollbars(cls, place, scroll) {
59
  CodeMirror.on(this.node, "DOMMouseScroll", onWheel);
60
  }
61
 
62
+ Bar.prototype.setPos = function(pos, force) {
63
  if (pos < 0) pos = 0;
64
  if (pos > this.total - this.screen) pos = this.total - this.screen;
65
+ if (!force && pos == this.pos) return false;
66
  this.pos = pos;
67
  this.inner.style[this.orientation == "horizontal" ? "left" : "top"] =
68
  (pos * (this.size / this.total)) + "px";
76
  var minButtonSize = 10;
77
 
78
  Bar.prototype.update = function(scrollSize, clientSize, barSize) {
79
+ var sizeChanged = this.screen != clientSize || this.total != scrollSize || this.size != barSize
80
+ if (sizeChanged) {
81
+ this.screen = clientSize;
82
+ this.total = scrollSize;
83
+ this.size = barSize;
84
+ }
85
 
86
  var buttonSize = this.screen * (this.size / this.total);
87
  if (buttonSize < minButtonSize) {
90
  }
91
  this.inner.style[this.orientation == "horizontal" ? "width" : "height"] =
92
  buttonSize + "px";
93
+ this.setPos(this.pos, sizeChanged);
94
  };
95
 
96
  function SimpleScrollbars(cls, place, scroll) {
js/esites_editor/dist/js/vendor/codemirror/addon/search/match-highlighter.js CHANGED
@@ -45,6 +45,7 @@
45
  this.options[name] = (options && options.hasOwnProperty(name) ? options : defaults)[name]
46
  this.overlay = this.timeout = null;
47
  this.matchesonscroll = null;
 
48
  }
49
 
50
  CodeMirror.defineOption("highlightSelectionMatches", false, function(cm, val, old) {
@@ -53,16 +54,34 @@
53
  clearTimeout(cm.state.matchHighlighter.timeout);
54
  cm.state.matchHighlighter = null;
55
  cm.off("cursorActivity", cursorActivity);
 
56
  }
57
  if (val) {
58
- cm.state.matchHighlighter = new State(val);
59
- highlightMatches(cm);
 
 
 
 
 
60
  cm.on("cursorActivity", cursorActivity);
61
  }
62
  });
63
 
64
  function cursorActivity(cm) {
65
  var state = cm.state.matchHighlighter;
 
 
 
 
 
 
 
 
 
 
 
 
66
  clearTimeout(state.timeout);
67
  state.timeout = setTimeout(function() {highlightMatches(cm);}, state.options.delay);
68
  }
@@ -72,7 +91,7 @@
72
  cm.addOverlay(state.overlay = makeOverlay(query, hasBoundary, style));
73
  if (state.options.annotateScrollbar && cm.showMatchesOnScrollbar) {
74
  var searchFor = hasBoundary ? new RegExp("\\b" + query + "\\b") : query;
75
- state.matchesonscroll = cm.showMatchesOnScrollbar(searchFor, true,
76
  {className: "CodeMirror-selection-highlight-scrollbar"});
77
  }
78
  }
45
  this.options[name] = (options && options.hasOwnProperty(name) ? options : defaults)[name]
46
  this.overlay = this.timeout = null;
47
  this.matchesonscroll = null;
48
+ this.active = false;
49
  }
50
 
51
  CodeMirror.defineOption("highlightSelectionMatches", false, function(cm, val, old) {
54
  clearTimeout(cm.state.matchHighlighter.timeout);
55
  cm.state.matchHighlighter = null;
56
  cm.off("cursorActivity", cursorActivity);
57
+ cm.off("focus", onFocus)
58
  }
59
  if (val) {
60
+ var state = cm.state.matchHighlighter = new State(val);
61
+ if (cm.hasFocus()) {
62
+ state.active = true
63
+ highlightMatches(cm)
64
+ } else {
65
+ cm.on("focus", onFocus)
66
+ }
67
  cm.on("cursorActivity", cursorActivity);
68
  }
69
  });
70
 
71
  function cursorActivity(cm) {
72
  var state = cm.state.matchHighlighter;
73
+ if (state.active || cm.hasFocus()) scheduleHighlight(cm, state)
74
+ }
75
+
76
+ function onFocus(cm) {
77
+ var state = cm.state.matchHighlighter
78
+ if (!state.active) {
79
+ state.active = true
80
+ scheduleHighlight(cm, state)
81
+ }
82
+ }
83
+
84
+ function scheduleHighlight(cm, state) {
85
  clearTimeout(state.timeout);
86
  state.timeout = setTimeout(function() {highlightMatches(cm);}, state.options.delay);
87
  }
91
  cm.addOverlay(state.overlay = makeOverlay(query, hasBoundary, style));
92
  if (state.options.annotateScrollbar && cm.showMatchesOnScrollbar) {
93
  var searchFor = hasBoundary ? new RegExp("\\b" + query + "\\b") : query;
94
+ state.matchesonscroll = cm.showMatchesOnScrollbar(searchFor, false,
95
  {className: "CodeMirror-selection-highlight-scrollbar"});
96
  }
97
  }
js/esites_editor/dist/js/vendor/codemirror/addon/search/search.js CHANGED
@@ -57,12 +57,13 @@
57
  return cm.getSearchCursor(query, pos, queryCaseInsensitive(query));
58
  }
59
 
60
- function persistentDialog(cm, text, deflt, f) {
61
- cm.openDialog(text, f, {
62
  value: deflt,
63
  selectValueOnOpen: true,
64
  closeOnEnter: false,
65
- onClose: function() { clearSearch(cm); }
 
66
  });
67
  }
68
 
@@ -112,13 +113,13 @@
112
  }
113
  }
114
 
115
- function doSearch(cm, rev, persistent) {
116
  var state = getSearchState(cm);
117
  if (state.query) return findNext(cm, rev);
118
  var q = cm.getSelection() || state.lastQuery;
119
  if (persistent && cm.openDialog) {
120
  var hiding = null
121
- persistentDialog(cm, queryDialog, q, function(query, event) {
122
  CodeMirror.e_stop(event);
123
  if (!query) return;
124
  if (query != state.queryText) {
@@ -133,7 +134,25 @@
133
  dialog.getBoundingClientRect().bottom - 4 > cm.cursorCoords(to, "window").top)
134
  (hiding = dialog).style.opacity = .4
135
  })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
  });
 
 
 
 
137
  } else {
138
  dialog(cm, queryDialog, "Search for:", q, function(query) {
139
  if (query && !state.query) cm.operation(function() {
@@ -223,6 +242,8 @@
223
 
224
  CodeMirror.commands.find = function(cm) {clearSearch(cm); doSearch(cm);};
225
  CodeMirror.commands.findPersistent = function(cm) {clearSearch(cm); doSearch(cm, false, true);};
 
 
226
  CodeMirror.commands.findNext = doSearch;
227
  CodeMirror.commands.findPrev = function(cm) {doSearch(cm, true);};
228
  CodeMirror.commands.clearSearch = clearSearch;
57
  return cm.getSearchCursor(query, pos, queryCaseInsensitive(query));
58
  }
59
 
60
+ function persistentDialog(cm, text, deflt, onEnter, onKeyDown) {
61
+ cm.openDialog(text, onEnter, {
62
  value: deflt,
63
  selectValueOnOpen: true,
64
  closeOnEnter: false,
65
+ onClose: function() { clearSearch(cm); },
66
+ onKeyDown: onKeyDown
67
  });
68
  }
69
 
113
  }
114
  }
115
 
116
+ function doSearch(cm, rev, persistent, immediate) {
117
  var state = getSearchState(cm);
118
  if (state.query) return findNext(cm, rev);
119
  var q = cm.getSelection() || state.lastQuery;
120
  if (persistent && cm.openDialog) {
121
  var hiding = null
122
+ var searchNext = function(query, event) {
123
  CodeMirror.e_stop(event);
124
  if (!query) return;
125
  if (query != state.queryText) {
134
  dialog.getBoundingClientRect().bottom - 4 > cm.cursorCoords(to, "window").top)
135
  (hiding = dialog).style.opacity = .4
136
  })
137
+ };
138
+ persistentDialog(cm, queryDialog, q, searchNext, function(event, query) {
139
+ var keyName = CodeMirror.keyName(event)
140
+ var cmd = CodeMirror.keyMap[cm.getOption("keyMap")][keyName]
141
+ if (!cmd) cmd = cm.getOption('extraKeys')[keyName]
142
+ if (cmd == "findNext" || cmd == "findPrev" ||
143
+ cmd == "findPersistentNext" || cmd == "findPersistentPrev") {
144
+ CodeMirror.e_stop(event);
145
+ startSearch(cm, getSearchState(cm), query);
146
+ cm.execCommand(cmd);
147
+ } else if (cmd == "find" || cmd == "findPersistent") {
148
+ CodeMirror.e_stop(event);
149
+ searchNext(query, event);
150
+ }
151
  });
152
+ if (immediate && q) {
153
+ startSearch(cm, state, q);
154
+ findNext(cm, rev);
155
+ }
156
  } else {
157
  dialog(cm, queryDialog, "Search for:", q, function(query) {
158
  if (query && !state.query) cm.operation(function() {
242
 
243
  CodeMirror.commands.find = function(cm) {clearSearch(cm); doSearch(cm);};
244
  CodeMirror.commands.findPersistent = function(cm) {clearSearch(cm); doSearch(cm, false, true);};
245
+ CodeMirror.commands.findPersistentNext = function(cm) {doSearch(cm, false, true, true);};
246
+ CodeMirror.commands.findPersistentPrev = function(cm) {doSearch(cm, true, true, true);};
247
  CodeMirror.commands.findNext = doSearch;
248
  CodeMirror.commands.findPrev = function(cm) {doSearch(cm, true);};
249
  CodeMirror.commands.clearSearch = clearSearch;
js/esites_editor/dist/js/vendor/codemirror/addon/selection/active-line.js CHANGED
@@ -1,12 +1,6 @@
1
  // CodeMirror, copyright (c) by Marijn Haverbeke and others
2
  // Distributed under an MIT license: http://codemirror.net/LICENSE
3
 
4
- // Because sometimes you need to style the cursor's line.
5
- //
6
- // Adds an option 'styleActiveLine' which, when enabled, gives the
7
- // active line's wrapping <div> the CSS class "CodeMirror-activeline",
8
- // and gives its background <div> the class "CodeMirror-activeline-background".
9
-
10
  (function(mod) {
11
  if (typeof exports == "object" && typeof module == "object") // CommonJS
12
  mod(require("../../lib/codemirror"));
@@ -21,16 +15,18 @@
21
  var GUTT_CLASS = "CodeMirror-activeline-gutter";
22
 
23
  CodeMirror.defineOption("styleActiveLine", false, function(cm, val, old) {
24
- var prev = old && old != CodeMirror.Init;
25
- if (val && !prev) {
26
- cm.state.activeLines = [];
27
- updateActiveLines(cm, cm.listSelections());
28
- cm.on("beforeSelectionChange", selectionChange);
29
- } else if (!val && prev) {
30
  cm.off("beforeSelectionChange", selectionChange);
31
  clearActiveLines(cm);
32
  delete cm.state.activeLines;
33
  }
 
 
 
 
 
34
  });
35
 
36
  function clearActiveLines(cm) {
@@ -52,7 +48,9 @@
52
  var active = [];
53
  for (var i = 0; i < ranges.length; i++) {
54
  var range = ranges[i];
55
- if (!range.empty()) continue;
 
 
56
  var line = cm.getLineHandleVisualStart(range.head.line);
57
  if (active[active.length - 1] != line) active.push(line);
58
  }
1
  // CodeMirror, copyright (c) by Marijn Haverbeke and others
2
  // Distributed under an MIT license: http://codemirror.net/LICENSE
3
 
 
 
 
 
 
 
4
  (function(mod) {
5
  if (typeof exports == "object" && typeof module == "object") // CommonJS
6
  mod(require("../../lib/codemirror"));
15
  var GUTT_CLASS = "CodeMirror-activeline-gutter";
16
 
17
  CodeMirror.defineOption("styleActiveLine", false, function(cm, val, old) {
18
+ var prev = old == CodeMirror.Init ? false : old;
19
+ if (val == prev) return
20
+ if (prev) {
 
 
 
21
  cm.off("beforeSelectionChange", selectionChange);
22
  clearActiveLines(cm);
23
  delete cm.state.activeLines;
24
  }
25
+ if (val) {
26
+ cm.state.activeLines = [];
27
+ updateActiveLines(cm, cm.listSelections());
28
+ cm.on("beforeSelectionChange", selectionChange);
29
+ }
30
  });
31
 
32
  function clearActiveLines(cm) {
48
  var active = [];
49
  for (var i = 0; i < ranges.length; i++) {
50
  var range = ranges[i];
51
+ var option = cm.getOption("styleActiveLine");
52
+ if (typeof option == "object" && option.nonEmpty ? range.anchor.line != range.head.line : !range.empty())
53
+ continue
54
  var line = cm.getLineHandleVisualStart(range.head.line);
55
  if (active[active.length - 1] != line) active.push(line);
56
  }
js/esites_editor/dist/js/vendor/codemirror/addon/wrap/hardwrap.js CHANGED
@@ -30,7 +30,9 @@
30
  }
31
 
32
  function findBreakPoint(text, column, wrapOn, killTrailingSpace) {
33
- for (var at = column; at > 0; --at)
 
 
34
  if (wrapOn.test(text.slice(at - 1, at + 1))) break;
35
  for (var first = true;; first = false) {
36
  var endOfText = at;
30
  }
31
 
32
  function findBreakPoint(text, column, wrapOn, killTrailingSpace) {
33
+ var at = column
34
+ while (at < text.length && text.charAt(at) == " ") at++
35
+ for (; at > 0; --at)
36
  if (wrapOn.test(text.slice(at - 1, at + 1))) break;
37
  for (var first = true;; first = false) {
38
  var endOfText = at;
js/esites_editor/dist/js/vendor/codemirror/keymap/emacs.js CHANGED
@@ -1 +1 @@
1
- !function(mod){"object"==typeof exports&&"object"==typeof module?mod(require("../lib/codemirror")):"function"==typeof define&&define.amd?define(["../lib/codemirror"],mod):mod(CodeMirror)}(function(CodeMirror){"use strict";function posEq(a,b){return a.line==b.line&&a.ch==b.ch}function addToRing(str){killRing.push(str);killRing.length>50&&killRing.shift()}function growRingTop(str){if(!killRing.length)return addToRing(str);killRing[killRing.length-1]+=str;return void 0}function getFromRing(n){return killRing[killRing.length-(n?Math.min(n,1):1)]||""}function popFromRing(){killRing.length>1&&killRing.pop();return getFromRing()}function kill(cm,from,to,mayGrow,text){null==text&&(text=cm.getRange(from,to));mayGrow&&lastKill&&lastKill.cm==cm&&posEq(from,lastKill.pos)&&cm.isClean(lastKill.gen)?growRingTop(text):addToRing(text);cm.replaceRange("",from,to,"+delete");lastKill=mayGrow?{cm:cm,pos:from,gen:cm.changeGeneration()}:null}function byChar(cm,pos,dir){return cm.findPosH(pos,dir,"char",!0)}function byWord(cm,pos,dir){return cm.findPosH(pos,dir,"word",!0)}function byLine(cm,pos,dir){return cm.findPosV(pos,dir,"line",cm.doc.sel.goalColumn)}function byPage(cm,pos,dir){return cm.findPosV(pos,dir,"page",cm.doc.sel.goalColumn)}function byParagraph(cm,pos,dir){for(var no=pos.line,line=cm.getLine(no),sawText=/\S/.test(0>dir?line.slice(0,pos.ch):line.slice(pos.ch)),fst=cm.firstLine(),lst=cm.lastLine();;){no+=dir;if(fst>no||no>lst)return cm.clipPos(Pos(no-dir,0>dir?0:null));line=cm.getLine(no);var hasText=/\S/.test(line);if(hasText)sawText=!0;else if(sawText)return Pos(no,0)}}function bySentence(cm,pos,dir){for(var line=pos.line,ch=pos.ch,text=cm.getLine(pos.line),sawWord=!1;;){var next=text.charAt(ch+(0>dir?-1:0));if(next){if(sawWord&&/[!?.]/.test(next))return Pos(line,ch+(dir>0?1:0));sawWord||(sawWord=/\w/.test(next));ch+=dir}else{if(line==(0>dir?cm.firstLine():cm.lastLine()))return Pos(line,ch);text=cm.getLine(line+dir);if(!/\S/.test(text))return Pos(line,ch);line+=dir;ch=0>dir?text.length:0}}}function byExpr(cm,pos,dir){var wrap;if(cm.findMatchingBracket&&(wrap=cm.findMatchingBracket(pos,!0))&&wrap.match&&(wrap.forward?1:-1)==dir)return dir>0?Pos(wrap.to.line,wrap.to.ch+1):wrap.to;for(var first=!0;;first=!1){var token=cm.getTokenAt(pos),after=Pos(pos.line,0>dir?token.start:token.end);if(!(first&&dir>0&&token.end==pos.ch)&&/\w/.test(token.string))return after;var newPos=cm.findPosH(after,dir,"char");if(posEq(after,newPos))return pos;pos=newPos}}function getPrefix(cm,precise){var digits=cm.state.emacsPrefix;if(!digits)return precise?null:1;clearPrefix(cm);return"-"==digits?-1:Number(digits)}function repeated(cmd){var f="string"==typeof cmd?function(cm){cm.execCommand(cmd)}:cmd;return function(cm){var prefix=getPrefix(cm);f(cm);for(var i=1;prefix>i;++i)f(cm)}}function findEnd(cm,pos,by,dir){var prefix=getPrefix(cm);if(0>prefix){dir=-dir;prefix=-prefix}for(var i=0;prefix>i;++i){var newPos=by(cm,pos,dir);if(posEq(newPos,pos))break;pos=newPos}return pos}function move(by,dir){var f=function(cm){cm.extendSelection(findEnd(cm,cm.getCursor(),by,dir))};f.motion=!0;return f}function killTo(cm,by,dir){for(var cursor,selections=cm.listSelections(),i=selections.length;i--;){cursor=selections[i].head;kill(cm,cursor,findEnd(cm,cursor,by,dir),!0)}}function killRegion(cm){if(cm.somethingSelected()){for(var selection,selections=cm.listSelections(),i=selections.length;i--;){selection=selections[i];kill(cm,selection.anchor,selection.head)}return!0}}function addPrefix(cm,digit){if(cm.state.emacsPrefix)"-"!=digit&&(cm.state.emacsPrefix+=digit);else{cm.state.emacsPrefix=digit;cm.on("keyHandled",maybeClearPrefix);cm.on("inputRead",maybeDuplicateInput)}}function maybeClearPrefix(cm,arg){cm.state.emacsPrefixMap||prefixPreservingKeys.hasOwnProperty(arg)||clearPrefix(cm)}function clearPrefix(cm){cm.state.emacsPrefix=null;cm.off("keyHandled",maybeClearPrefix);cm.off("inputRead",maybeDuplicateInput)}function maybeDuplicateInput(cm,event){var dup=getPrefix(cm);if(dup>1&&"+input"==event.origin){for(var one=event.text.join("\n"),txt="",i=1;dup>i;++i)txt+=one;cm.replaceSelection(txt)}}function addPrefixMap(cm){cm.state.emacsPrefixMap=!0;cm.addKeyMap(prefixMap);cm.on("keyHandled",maybeRemovePrefixMap);cm.on("inputRead",maybeRemovePrefixMap)}function maybeRemovePrefixMap(cm,arg){if("string"!=typeof arg||!/^\d$/.test(arg)&&"Ctrl-U"!=arg){cm.removeKeyMap(prefixMap);cm.state.emacsPrefixMap=!1;cm.off("keyHandled",maybeRemovePrefixMap);cm.off("inputRead",maybeRemovePrefixMap)}}function setMark(cm){cm.setCursor(cm.getCursor());cm.setExtending(!cm.getExtending());cm.on("change",function(){cm.setExtending(!1)})}function clearMark(cm){cm.setExtending(!1);cm.setCursor(cm.getCursor())}function getInput(cm,msg,f){cm.openDialog?cm.openDialog(msg+': <input type="text" style="width: 10em"/>',f,{bottom:!0}):f(prompt(msg,""))}function operateOnWord(cm,op){var start=cm.getCursor(),end=cm.findPosH(start,1,"word");cm.replaceRange(op(cm.getRange(start,end)),start,end);cm.setCursor(end)}function toEnclosingExpr(cm){for(var pos=cm.getCursor(),line=pos.line,ch=pos.ch,stack=[];line>=cm.firstLine();){for(var text=cm.getLine(line),i=null==ch?text.length:ch;i>0;){var ch=text.charAt(--i);if(")"==ch)stack.push("(");else if("]"==ch)stack.push("[");else if("}"==ch)stack.push("{");else if(/[\(\{\[]/.test(ch)&&(!stack.length||stack.pop()!=ch))return cm.extendSelection(Pos(line,i))}--line;ch=null}}function quit(cm){cm.execCommand("clearSearch");clearMark(cm)}function regPrefix(d){prefixMap[d]=function(cm){addPrefix(cm,d)};keyMap["Ctrl-"+d]=function(cm){addPrefix(cm,d)};prefixPreservingKeys["Ctrl-"+d]=!0}for(var Pos=CodeMirror.Pos,killRing=[],lastKill=null,prefixPreservingKeys={"Alt-G":!0,"Ctrl-X":!0,"Ctrl-Q":!0,"Ctrl-U":!0},keyMap=CodeMirror.keyMap.emacs=CodeMirror.normalizeKeyMap({"Ctrl-W":function(cm){kill(cm,cm.getCursor("start"),cm.getCursor("end"))},"Ctrl-K":repeated(function(cm){var start=cm.getCursor(),end=cm.clipPos(Pos(start.line)),text=cm.getRange(start,end);if(!/\S/.test(text)){text+="\n";end=Pos(start.line+1,0)}kill(cm,start,end,!0,text)}),"Alt-W":function(cm){addToRing(cm.getSelection());clearMark(cm)},"Ctrl-Y":function(cm){var start=cm.getCursor();cm.replaceRange(getFromRing(getPrefix(cm)),start,start,"paste");cm.setSelection(start,cm.getCursor())},"Alt-Y":function(cm){cm.replaceSelection(popFromRing(),"around","paste")},"Ctrl-Space":setMark,"Ctrl-Shift-2":setMark,"Ctrl-F":move(byChar,1),"Ctrl-B":move(byChar,-1),Right:move(byChar,1),Left:move(byChar,-1),"Ctrl-D":function(cm){killTo(cm,byChar,1)},Delete:function(cm){killRegion(cm)||killTo(cm,byChar,1)},"Ctrl-H":function(cm){killTo(cm,byChar,-1)},Backspace:function(cm){killRegion(cm)||killTo(cm,byChar,-1)},"Alt-F":move(byWord,1),"Alt-B":move(byWord,-1),"Alt-D":function(cm){killTo(cm,byWord,1)},"Alt-Backspace":function(cm){killTo(cm,byWord,-1)},"Ctrl-N":move(byLine,1),"Ctrl-P":move(byLine,-1),Down:move(byLine,1),Up:move(byLine,-1),"Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd",End:"goLineEnd",Home:"goLineStart","Alt-V":move(byPage,-1),"Ctrl-V":move(byPage,1),PageUp:move(byPage,-1),PageDown:move(byPage,1),"Ctrl-Up":move(byParagraph,-1),"Ctrl-Down":move(byParagraph,1),"Alt-A":move(bySentence,-1),"Alt-E":move(bySentence,1),"Alt-K":function(cm){killTo(cm,bySentence,1)},"Ctrl-Alt-K":function(cm){killTo(cm,byExpr,1)},"Ctrl-Alt-Backspace":function(cm){killTo(cm,byExpr,-1)},"Ctrl-Alt-F":move(byExpr,1),"Ctrl-Alt-B":move(byExpr,-1),"Shift-Ctrl-Alt-2":function(cm){var cursor=cm.getCursor();cm.setSelection(findEnd(cm,cursor,byExpr,1),cursor)},"Ctrl-Alt-T":function(cm){var leftStart=byExpr(cm,cm.getCursor(),-1),leftEnd=byExpr(cm,leftStart,1),rightEnd=byExpr(cm,leftEnd,1),rightStart=byExpr(cm,rightEnd,-1);cm.replaceRange(cm.getRange(rightStart,rightEnd)+cm.getRange(leftEnd,rightStart)+cm.getRange(leftStart,leftEnd),leftStart,rightEnd)},"Ctrl-Alt-U":repeated(toEnclosingExpr),"Alt-Space":function(cm){for(var pos=cm.getCursor(),from=pos.ch,to=pos.ch,text=cm.getLine(pos.line);from&&/\s/.test(text.charAt(from-1));)--from;for(;to<text.length&&/\s/.test(text.charAt(to));)++to;cm.replaceRange(" ",Pos(pos.line,from),Pos(pos.line,to))},"Ctrl-O":repeated(function(cm){cm.replaceSelection("\n","start")}),"Ctrl-T":repeated(function(cm){cm.execCommand("transposeChars")}),"Alt-C":repeated(function(cm){operateOnWord(cm,function(w){var letter=w.search(/\w/);return-1==letter?w:w.slice(0,letter)+w.charAt(letter).toUpperCase()+w.slice(letter+1).toLowerCase()})}),"Alt-U":repeated(function(cm){operateOnWord(cm,function(w){return w.toUpperCase()})}),"Alt-L":repeated(function(cm){operateOnWord(cm,function(w){return w.toLowerCase()})}),"Alt-;":"toggleComment","Ctrl-/":repeated("undo"),"Shift-Ctrl--":repeated("undo"),"Ctrl-Z":repeated("undo"),"Cmd-Z":repeated("undo"),"Shift-Alt-,":"goDocStart","Shift-Alt-.":"goDocEnd","Ctrl-S":"findNext","Ctrl-R":"findPrev","Ctrl-G":quit,"Shift-Alt-5":"replace","Alt-/":"autocomplete","Ctrl-J":"newlineAndIndent",Enter:!1,Tab:"indentAuto","Alt-G G":function(cm){var prefix=getPrefix(cm,!0);if(null!=prefix&&prefix>0)return cm.setCursor(prefix-1);getInput(cm,"Goto line",function(str){var num;str&&!isNaN(num=Number(str))&&num==(0|num)&&num>0&&cm.setCursor(num-1)});return void 0},"Ctrl-X Tab":function(cm){cm.indentSelection(getPrefix(cm,!0)||cm.getOption("indentUnit"))},"Ctrl-X Ctrl-X":function(cm){cm.setSelection(cm.getCursor("head"),cm.getCursor("anchor"))},"Ctrl-X Ctrl-S":"save","Ctrl-X Ctrl-W":"save","Ctrl-X S":"saveAll","Ctrl-X F":"open","Ctrl-X U":repeated("undo"),"Ctrl-X K":"close","Ctrl-X Delete":function(cm){kill(cm,cm.getCursor(),bySentence(cm,cm.getCursor(),1),!0)},"Ctrl-X H":"selectAll","Ctrl-Q Tab":repeated("insertTab"),"Ctrl-U":addPrefixMap}),prefixMap={"Ctrl-G":clearPrefix},i=0;10>i;++i)regPrefix(String(i));regPrefix("-")});
1
+ !function(mod){"object"==typeof exports&&"object"==typeof module?mod(require("../lib/codemirror")):"function"==typeof define&&define.amd?define(["../lib/codemirror"],mod):mod(CodeMirror)}(function(CodeMirror){"use strict";function posEq(a,b){return a.line==b.line&&a.ch==b.ch}function addToRing(str){killRing.push(str);killRing.length>50&&killRing.shift()}function growRingTop(str){if(!killRing.length)return addToRing(str);killRing[killRing.length-1]+=str}function getFromRing(n){return killRing[killRing.length-(n?Math.min(n,1):1)]||""}function popFromRing(){killRing.length>1&&killRing.pop();return getFromRing()}function kill(cm,from,to,mayGrow,text){null==text&&(text=cm.getRange(from,to));mayGrow&&lastKill&&lastKill.cm==cm&&posEq(from,lastKill.pos)&&cm.isClean(lastKill.gen)?growRingTop(text):addToRing(text);cm.replaceRange("",from,to,"+delete");lastKill=mayGrow?{cm:cm,pos:from,gen:cm.changeGeneration()}:null}function byChar(cm,pos,dir){return cm.findPosH(pos,dir,"char",!0)}function byWord(cm,pos,dir){return cm.findPosH(pos,dir,"word",!0)}function byLine(cm,pos,dir){return cm.findPosV(pos,dir,"line",cm.doc.sel.goalColumn)}function byPage(cm,pos,dir){return cm.findPosV(pos,dir,"page",cm.doc.sel.goalColumn)}function byParagraph(cm,pos,dir){for(var no=pos.line,line=cm.getLine(no),sawText=/\S/.test(dir<0?line.slice(0,pos.ch):line.slice(pos.ch)),fst=cm.firstLine(),lst=cm.lastLine();;){no+=dir;if(no<fst||no>lst)return cm.clipPos(Pos(no-dir,dir<0?0:null));line=cm.getLine(no);var hasText=/\S/.test(line);if(hasText)sawText=!0;else if(sawText)return Pos(no,0)}}function bySentence(cm,pos,dir){for(var line=pos.line,ch=pos.ch,text=cm.getLine(pos.line),sawWord=!1;;){var next=text.charAt(ch+(dir<0?-1:0));if(next){if(sawWord&&/[!?.]/.test(next))return Pos(line,ch+(dir>0?1:0));sawWord||(sawWord=/\w/.test(next));ch+=dir}else{if(line==(dir<0?cm.firstLine():cm.lastLine()))return Pos(line,ch);text=cm.getLine(line+dir);if(!/\S/.test(text))return Pos(line,ch);line+=dir;ch=dir<0?text.length:0}}}function byExpr(cm,pos,dir){var wrap;if(cm.findMatchingBracket&&(wrap=cm.findMatchingBracket(pos,!0))&&wrap.match&&(wrap.forward?1:-1)==dir)return dir>0?Pos(wrap.to.line,wrap.to.ch+1):wrap.to;for(var first=!0;;first=!1){var token=cm.getTokenAt(pos),after=Pos(pos.line,dir<0?token.start:token.end);if(!(first&&dir>0&&token.end==pos.ch)&&/\w/.test(token.string))return after;var newPos=cm.findPosH(after,dir,"char");if(posEq(after,newPos))return pos;pos=newPos}}function getPrefix(cm,precise){var digits=cm.state.emacsPrefix;if(!digits)return precise?null:1;clearPrefix(cm);return"-"==digits?-1:Number(digits)}function repeated(cmd){var f="string"==typeof cmd?function(cm){cm.execCommand(cmd)}:cmd;return function(cm){var prefix=getPrefix(cm);f(cm);for(var i=1;i<prefix;++i)f(cm)}}function findEnd(cm,pos,by,dir){var prefix=getPrefix(cm);if(prefix<0){dir=-dir;prefix=-prefix}for(var i=0;i<prefix;++i){var newPos=by(cm,pos,dir);if(posEq(newPos,pos))break;pos=newPos}return pos}function move(by,dir){var f=function(cm){cm.extendSelection(findEnd(cm,cm.getCursor(),by,dir))};f.motion=!0;return f}function killTo(cm,by,dir){for(var cursor,selections=cm.listSelections(),i=selections.length;i--;){cursor=selections[i].head;kill(cm,cursor,findEnd(cm,cursor,by,dir),!0)}}function killRegion(cm){if(cm.somethingSelected()){for(var selection,selections=cm.listSelections(),i=selections.length;i--;){selection=selections[i];kill(cm,selection.anchor,selection.head)}return!0}}function addPrefix(cm,digit){if(cm.state.emacsPrefix)"-"!=digit&&(cm.state.emacsPrefix+=digit);else{cm.state.emacsPrefix=digit;cm.on("keyHandled",maybeClearPrefix);cm.on("inputRead",maybeDuplicateInput)}}function maybeClearPrefix(cm,arg){cm.state.emacsPrefixMap||prefixPreservingKeys.hasOwnProperty(arg)||clearPrefix(cm)}function clearPrefix(cm){cm.state.emacsPrefix=null;cm.off("keyHandled",maybeClearPrefix);cm.off("inputRead",maybeDuplicateInput)}function maybeDuplicateInput(cm,event){var dup=getPrefix(cm);if(dup>1&&"+input"==event.origin){for(var one=event.text.join("\n"),txt="",i=1;i<dup;++i)txt+=one;cm.replaceSelection(txt)}}function addPrefixMap(cm){cm.state.emacsPrefixMap=!0;cm.addKeyMap(prefixMap);cm.on("keyHandled",maybeRemovePrefixMap);cm.on("inputRead",maybeRemovePrefixMap)}function maybeRemovePrefixMap(cm,arg){if("string"!=typeof arg||!/^\d$/.test(arg)&&"Ctrl-U"!=arg){cm.removeKeyMap(prefixMap);cm.state.emacsPrefixMap=!1;cm.off("keyHandled",maybeRemovePrefixMap);cm.off("inputRead",maybeRemovePrefixMap)}}function setMark(cm){cm.setCursor(cm.getCursor());cm.setExtending(!cm.getExtending());cm.on("change",function(){cm.setExtending(!1)})}function clearMark(cm){cm.setExtending(!1);cm.setCursor(cm.getCursor())}function getInput(cm,msg,f){cm.openDialog?cm.openDialog(msg+': <input type="text" style="width: 10em"/>',f,{bottom:!0}):f(prompt(msg,""))}function operateOnWord(cm,op){var start=cm.getCursor(),end=cm.findPosH(start,1,"word");cm.replaceRange(op(cm.getRange(start,end)),start,end);cm.setCursor(end)}function toEnclosingExpr(cm){for(var pos=cm.getCursor(),line=pos.line,ch=pos.ch,stack=[];line>=cm.firstLine();){for(var text=cm.getLine(line),i=null==ch?text.length:ch;i>0;){var ch=text.charAt(--i);if(")"==ch)stack.push("(");else if("]"==ch)stack.push("[");else if("}"==ch)stack.push("{");else if(/[\(\{\[]/.test(ch)&&(!stack.length||stack.pop()!=ch))return cm.extendSelection(Pos(line,i))}--line;ch=null}}function quit(cm){cm.execCommand("clearSearch");clearMark(cm)}function regPrefix(d){prefixMap[d]=function(cm){addPrefix(cm,d)};keyMap["Ctrl-"+d]=function(cm){addPrefix(cm,d)};prefixPreservingKeys["Ctrl-"+d]=!0}var Pos=CodeMirror.Pos,killRing=[],lastKill=null,prefixPreservingKeys={"Alt-G":!0,"Ctrl-X":!0,"Ctrl-Q":!0,"Ctrl-U":!0};CodeMirror.emacs={kill:kill,killRegion:killRegion,repeated:repeated};for(var keyMap=CodeMirror.keyMap.emacs=CodeMirror.normalizeKeyMap({"Ctrl-W":function(cm){kill(cm,cm.getCursor("start"),cm.getCursor("end"))},"Ctrl-K":repeated(function(cm){var start=cm.getCursor(),end=cm.clipPos(Pos(start.line)),text=cm.getRange(start,end);if(!/\S/.test(text)){text+="\n";end=Pos(start.line+1,0)}kill(cm,start,end,!0,text)}),"Alt-W":function(cm){addToRing(cm.getSelection());clearMark(cm)},"Ctrl-Y":function(cm){var start=cm.getCursor();cm.replaceRange(getFromRing(getPrefix(cm)),start,start,"paste");cm.setSelection(start,cm.getCursor())},"Alt-Y":function(cm){cm.replaceSelection(popFromRing(),"around","paste")},"Ctrl-Space":setMark,"Ctrl-Shift-2":setMark,"Ctrl-F":move(byChar,1),"Ctrl-B":move(byChar,-1),Right:move(byChar,1),Left:move(byChar,-1),"Ctrl-D":function(cm){killTo(cm,byChar,1)},Delete:function(cm){killRegion(cm)||killTo(cm,byChar,1)},"Ctrl-H":function(cm){killTo(cm,byChar,-1)},Backspace:function(cm){killRegion(cm)||killTo(cm,byChar,-1)},"Alt-F":move(byWord,1),"Alt-B":move(byWord,-1),"Alt-D":function(cm){killTo(cm,byWord,1)},"Alt-Backspace":function(cm){killTo(cm,byWord,-1)},"Ctrl-N":move(byLine,1),"Ctrl-P":move(byLine,-1),Down:move(byLine,1),Up:move(byLine,-1),"Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd",End:"goLineEnd",Home:"goLineStart","Alt-V":move(byPage,-1),"Ctrl-V":move(byPage,1),PageUp:move(byPage,-1),PageDown:move(byPage,1),"Ctrl-Up":move(byParagraph,-1),"Ctrl-Down":move(byParagraph,1),"Alt-A":move(bySentence,-1),"Alt-E":move(bySentence,1),"Alt-K":function(cm){killTo(cm,bySentence,1)},"Ctrl-Alt-K":function(cm){killTo(cm,byExpr,1)},"Ctrl-Alt-Backspace":function(cm){killTo(cm,byExpr,-1)},"Ctrl-Alt-F":move(byExpr,1),"Ctrl-Alt-B":move(byExpr,-1),"Shift-Ctrl-Alt-2":function(cm){var cursor=cm.getCursor();cm.setSelection(findEnd(cm,cursor,byExpr,1),cursor)},"Ctrl-Alt-T":function(cm){var leftStart=byExpr(cm,cm.getCursor(),-1),leftEnd=byExpr(cm,leftStart,1),rightEnd=byExpr(cm,leftEnd,1),rightStart=byExpr(cm,rightEnd,-1);cm.replaceRange(cm.getRange(rightStart,rightEnd)+cm.getRange(leftEnd,rightStart)+cm.getRange(leftStart,leftEnd),leftStart,rightEnd)},"Ctrl-Alt-U":repeated(toEnclosingExpr),"Alt-Space":function(cm){for(var pos=cm.getCursor(),from=pos.ch,to=pos.ch,text=cm.getLine(pos.line);from&&/\s/.test(text.charAt(from-1));)--from;for(;to<text.length&&/\s/.test(text.charAt(to));)++to;cm.replaceRange(" ",Pos(pos.line,from),Pos(pos.line,to))},"Ctrl-O":repeated(function(cm){cm.replaceSelection("\n","start")}),"Ctrl-T":repeated(function(cm){cm.execCommand("transposeChars")}),"Alt-C":repeated(function(cm){operateOnWord(cm,function(w){var letter=w.search(/\w/);return letter==-1?w:w.slice(0,letter)+w.charAt(letter).toUpperCase()+w.slice(letter+1).toLowerCase()})}),"Alt-U":repeated(function(cm){operateOnWord(cm,function(w){return w.toUpperCase()})}),"Alt-L":repeated(function(cm){operateOnWord(cm,function(w){return w.toLowerCase()})}),"Alt-;":"toggleComment","Ctrl-/":repeated("undo"),"Shift-Ctrl--":repeated("undo"),"Ctrl-Z":repeated("undo"),"Cmd-Z":repeated("undo"),"Shift-Alt-,":"goDocStart","Shift-Alt-.":"goDocEnd","Ctrl-S":"findNext","Ctrl-R":"findPrev","Ctrl-G":quit,"Shift-Alt-5":"replace","Alt-/":"autocomplete","Ctrl-J":"newlineAndIndent",Enter:!1,Tab:"indentAuto","Alt-G G":function(cm){var prefix=getPrefix(cm,!0);if(null!=prefix&&prefix>0)return cm.setCursor(prefix-1);getInput(cm,"Goto line",function(str){var num;str&&!isNaN(num=Number(str))&&num==(0|num)&&num>0&&cm.setCursor(num-1)})},"Ctrl-X Tab":function(cm){cm.indentSelection(getPrefix(cm,!0)||cm.getOption("indentUnit"))},"Ctrl-X Ctrl-X":function(cm){cm.setSelection(cm.getCursor("head"),cm.getCursor("anchor"))},"Ctrl-X Ctrl-S":"save","Ctrl-X Ctrl-W":"save","Ctrl-X S":"saveAll","Ctrl-X F":"open","Ctrl-X U":repeated("undo"),"Ctrl-X K":"close","Ctrl-X Delete":function(cm){kill(cm,cm.getCursor(),bySentence(cm,cm.getCursor(),1),!0)},"Ctrl-X H":"selectAll","Ctrl-Q Tab":repeated("insertTab"),"Ctrl-U":addPrefixMap}),prefixMap={"Ctrl-G":clearPrefix},i=0;i<10;++i)regPrefix(String(i));regPrefix("-")});
js/esites_editor/dist/js/vendor/codemirror/keymap/sublime.js CHANGED
@@ -1 +1 @@
1
- !function(mod){"object"==typeof exports&&"object"==typeof module?mod(require("../lib/codemirror"),require("../addon/search/searchcursor"),require("../addon/edit/matchbrackets")):"function"==typeof define&&define.amd?define(["../lib/codemirror","../addon/search/searchcursor","../addon/edit/matchbrackets"],mod):mod(CodeMirror)}(function(CodeMirror){"use strict";function findPosSubword(doc,start,dir){if(0>dir&&0==start.ch)return doc.clipPos(Pos(start.line-1));var line=doc.getLine(start.line);if(dir>0&&start.ch>=line.length)return doc.clipPos(Pos(start.line+1,0));for(var type,state="start",pos=start.ch,e=0>dir?0:line.length,i=0;pos!=e;pos+=dir,i++){var next=line.charAt(0>dir?pos-1:pos),cat="_"!=next&&CodeMirror.isWordChar(next)?"w":"o";"w"==cat&&next.toUpperCase()==next&&(cat="W");if("start"==state){if("o"!=cat){state="in";type=cat}}else if("in"==state&&type!=cat){"w"==type&&"W"==cat&&0>dir&&pos--;if("W"==type&&"w"==cat&&dir>0){type="w";continue}break}}return Pos(start.line,pos)}function moveSubword(cm,dir){cm.extendSelectionsBy(function(range){return cm.display.shift||cm.doc.extend||range.empty()?findPosSubword(cm.doc,range.head,dir):0>dir?range.from():range.to()})}function insertLine(cm,above){if(cm.isReadOnly())return CodeMirror.Pass;cm.operation(function(){for(var len=cm.listSelections().length,newSelection=[],last=-1,i=0;len>i;i++){var head=cm.listSelections()[i].head;if(!(head.line<=last)){var at=Pos(head.line+(above?0:1),0);cm.replaceRange("\n",at,null,"+insertLine");cm.indentLine(at.line,null,!0);newSelection.push({head:at,anchor:at});last=head.line+1}}cm.setSelections(newSelection)});return void 0}function wordAt(cm,pos){for(var start=pos.ch,end=start,line=cm.getLine(pos.line);start&&CodeMirror.isWordChar(line.charAt(start-1));)--start;for(;end<line.length&&CodeMirror.isWordChar(line.charAt(end));)++end;return{from:Pos(pos.line,start),to:Pos(pos.line,end),word:line.slice(start,end)}}function selectBetweenBrackets(cm){var pos=cm.getCursor(),opening=cm.scanForBracket(pos,-1);if(opening)for(;;){var closing=cm.scanForBracket(pos,1);if(!closing)return;if(closing.ch==mirror.charAt(mirror.indexOf(opening.ch)+1)){cm.setSelection(Pos(opening.pos.line,opening.pos.ch+1),closing.pos,!1);return!0}pos=Pos(closing.pos.line,closing.pos.ch+1)}}function sortLines(cm,caseSensitive){if(cm.isReadOnly())return CodeMirror.Pass;for(var selected,ranges=cm.listSelections(),toSort=[],i=0;i<ranges.length;i++){var range=ranges[i];if(!range.empty()){for(var from=range.from().line,to=range.to().line;i<ranges.length-1&&ranges[i+1].from().line==to;)to=range[++i].to().line;toSort.push(from,to)}}toSort.length?selected=!0:toSort.push(cm.firstLine(),cm.lastLine());cm.operation(function(){for(var ranges=[],i=0;i<toSort.length;i+=2){var from=toSort[i],to=toSort[i+1],start=Pos(from,0),end=Pos(to),lines=cm.getRange(start,end,!1);caseSensitive?lines.sort():lines.sort(function(a,b){var au=a.toUpperCase(),bu=b.toUpperCase();if(au!=bu){a=au;b=bu}return b>a?-1:a==b?0:1});cm.replaceRange(lines,start,end);selected&&ranges.push({anchor:start,head:end})}selected&&cm.setSelections(ranges,0)})}function modifyWordOrSelection(cm,mod){cm.operation(function(){for(var ranges=cm.listSelections(),indices=[],replacements=[],i=0;i<ranges.length;i++){var range=ranges[i];if(range.empty()){indices.push(i);replacements.push("")}else replacements.push(mod(cm.getRange(range.from(),range.to())))}cm.replaceSelections(replacements,"around","case");for(var at,i=indices.length-1;i>=0;i--){var range=ranges[indices[i]];if(!(at&&CodeMirror.cmpPos(range.head,at)>0)){var word=wordAt(cm,range.head);at=word.from;cm.replaceRange(mod(word.word),word.from,word.to)}}})}function getTarget(cm){var from=cm.getCursor("from"),to=cm.getCursor("to");if(0==CodeMirror.cmpPos(from,to)){var word=wordAt(cm,from);if(!word.word)return;from=word.from;to=word.to}return{from:from,to:to,query:cm.getRange(from,to),word:word}}function findAndGoTo(cm,forward){var target=getTarget(cm);if(target){var query=target.query,cur=cm.getSearchCursor(query,forward?target.to:target.from);if(forward?cur.findNext():cur.findPrevious())cm.setSelection(cur.from(),cur.to());else{cur=cm.getSearchCursor(query,forward?Pos(cm.firstLine(),0):cm.clipPos(Pos(cm.lastLine())));(forward?cur.findNext():cur.findPrevious())?cm.setSelection(cur.from(),cur.to()):target.word&&cm.setSelection(target.from,target.to)}}}var map=CodeMirror.keyMap.sublime={fallthrough:"default"},cmds=CodeMirror.commands,Pos=CodeMirror.Pos,mac=CodeMirror.keyMap["default"]==CodeMirror.keyMap.macDefault,ctrl=mac?"Cmd-":"Ctrl-";cmds[map["Alt-Left"]="goSubwordLeft"]=function(cm){moveSubword(cm,-1)};cmds[map["Alt-Right"]="goSubwordRight"]=function(cm){moveSubword(cm,1)};mac&&(map["Cmd-Left"]="goLineStartSmart");var scrollLineCombo=mac?"Ctrl-Alt-":"Ctrl-";cmds[map[scrollLineCombo+"Up"]="scrollLineUp"]=function(cm){var info=cm.getScrollInfo();if(!cm.somethingSelected()){var visibleBottomLine=cm.lineAtHeight(info.top+info.clientHeight,"local");cm.getCursor().line>=visibleBottomLine&&cm.execCommand("goLineUp")}cm.scrollTo(null,info.top-cm.defaultTextHeight())};cmds[map[scrollLineCombo+"Down"]="scrollLineDown"]=function(cm){var info=cm.getScrollInfo();if(!cm.somethingSelected()){var visibleTopLine=cm.lineAtHeight(info.top,"local")+1;cm.getCursor().line<=visibleTopLine&&cm.execCommand("goLineDown")}cm.scrollTo(null,info.top+cm.defaultTextHeight())};cmds[map["Shift-"+ctrl+"L"]="splitSelectionByLine"]=function(cm){for(var ranges=cm.listSelections(),lineRanges=[],i=0;i<ranges.length;i++)for(var from=ranges[i].from(),to=ranges[i].to(),line=from.line;line<=to.line;++line)to.line>from.line&&line==to.line&&0==to.ch||lineRanges.push({anchor:line==from.line?from:Pos(line,0),head:line==to.line?to:Pos(line)});cm.setSelections(lineRanges,0)};map["Shift-Tab"]="indentLess";cmds[map.Esc="singleSelectionTop"]=function(cm){var range=cm.listSelections()[0];cm.setSelection(range.anchor,range.head,{scroll:!1})};cmds[map[ctrl+"L"]="selectLine"]=function(cm){for(var ranges=cm.listSelections(),extended=[],i=0;i<ranges.length;i++){var range=ranges[i];extended.push({anchor:Pos(range.from().line,0),head:Pos(range.to().line+1,0)})}cm.setSelections(extended)};map["Shift-Ctrl-K"]="deleteLine";cmds[map[ctrl+"Enter"]="insertLineAfter"]=function(cm){return insertLine(cm,!1)};cmds[map["Shift-"+ctrl+"Enter"]="insertLineBefore"]=function(cm){return insertLine(cm,!0)};cmds[map[ctrl+"D"]="selectNextOccurrence"]=function(cm){var from=cm.getCursor("from"),to=cm.getCursor("to"),fullWord=cm.state.sublimeFindFullWord==cm.doc.sel;if(0==CodeMirror.cmpPos(from,to)){var word=wordAt(cm,from);if(!word.word)return;cm.setSelection(word.from,word.to);fullWord=!0}else{var text=cm.getRange(from,to),query=fullWord?new RegExp("\\b"+text+"\\b"):text,cur=cm.getSearchCursor(query,to);if(cur.findNext())cm.addSelection(cur.from(),cur.to());else{cur=cm.getSearchCursor(query,Pos(cm.firstLine(),0));cur.findNext()&&cm.addSelection(cur.from(),cur.to())}}fullWord&&(cm.state.sublimeFindFullWord=cm.doc.sel)};var mirror="(){}[]";cmds[map["Shift-"+ctrl+"Space"]="selectScope"]=function(cm){selectBetweenBrackets(cm)||cm.execCommand("selectAll")};cmds[map["Shift-"+ctrl+"M"]="selectBetweenBrackets"]=function(cm){return selectBetweenBrackets(cm)?void 0:CodeMirror.Pass};cmds[map[ctrl+"M"]="goToBracket"]=function(cm){cm.extendSelectionsBy(function(range){var next=cm.scanForBracket(range.head,1);if(next&&0!=CodeMirror.cmpPos(next.pos,range.head))return next.pos;var prev=cm.scanForBracket(range.head,-1);return prev&&Pos(prev.pos.line,prev.pos.ch+1)||range.head})};var swapLineCombo=mac?"Cmd-Ctrl-":"Shift-Ctrl-";cmds[map[swapLineCombo+"Up"]="swapLineUp"]=function(cm){if(cm.isReadOnly())return CodeMirror.Pass;for(var ranges=cm.listSelections(),linesToMove=[],at=cm.firstLine()-1,newSels=[],i=0;i<ranges.length;i++){var range=ranges[i],from=range.from().line-1,to=range.to().line;newSels.push({anchor:Pos(range.anchor.line-1,range.anchor.ch),head:Pos(range.head.line-1,range.head.ch)});0!=range.to().ch||range.empty()||--to;from>at?linesToMove.push(from,to):linesToMove.length&&(linesToMove[linesToMove.length-1]=to);at=to}cm.operation(function(){for(var i=0;i<linesToMove.length;i+=2){var from=linesToMove[i],to=linesToMove[i+1],line=cm.getLine(from);cm.replaceRange("",Pos(from,0),Pos(from+1,0),"+swapLine");to>cm.lastLine()?cm.replaceRange("\n"+line,Pos(cm.lastLine()),null,"+swapLine"):cm.replaceRange(line+"\n",Pos(to,0),null,"+swapLine")}cm.setSelections(newSels);cm.scrollIntoView()})};cmds[map[swapLineCombo+"Down"]="swapLineDown"]=function(cm){if(cm.isReadOnly())return CodeMirror.Pass;for(var ranges=cm.listSelections(),linesToMove=[],at=cm.lastLine()+1,i=ranges.length-1;i>=0;i--){var range=ranges[i],from=range.to().line+1,to=range.from().line;0!=range.to().ch||range.empty()||from--;at>from?linesToMove.push(from,to):linesToMove.length&&(linesToMove[linesToMove.length-1]=to);at=to}cm.operation(function(){for(var i=linesToMove.length-2;i>=0;i-=2){var from=linesToMove[i],to=linesToMove[i+1],line=cm.getLine(from);from==cm.lastLine()?cm.replaceRange("",Pos(from-1),Pos(from),"+swapLine"):cm.replaceRange("",Pos(from,0),Pos(from+1,0),"+swapLine");cm.replaceRange(line+"\n",Pos(to,0),null,"+swapLine")}cm.scrollIntoView()})};cmds[map[ctrl+"/"]="toggleCommentIndented"]=function(cm){cm.toggleComment({indent:!0})};cmds[map[ctrl+"J"]="joinLines"]=function(cm){for(var ranges=cm.listSelections(),joined=[],i=0;i<ranges.length;i++){for(var range=ranges[i],from=range.from(),start=from.line,end=range.to().line;i<ranges.length-1&&ranges[i+1].from().line==end;)end=ranges[++i].to().line;joined.push({start:start,end:end,anchor:!range.empty()&&from})}cm.operation(function(){for(var offset=0,ranges=[],i=0;i<joined.length;i++){for(var head,obj=joined[i],anchor=obj.anchor&&Pos(obj.anchor.line-offset,obj.anchor.ch),line=obj.start;line<=obj.end;line++){var actual=line-offset;line==obj.end&&(head=Pos(actual,cm.getLine(actual).length+1));if(actual<cm.lastLine()){cm.replaceRange(" ",Pos(actual),Pos(actual+1,/^\s*/.exec(cm.getLine(actual+1))[0].length));++offset}}ranges.push({anchor:anchor||head,head:head})}cm.setSelections(ranges,0)})};cmds[map["Shift-"+ctrl+"D"]="duplicateLine"]=function(cm){cm.operation(function(){for(var rangeCount=cm.listSelections().length,i=0;rangeCount>i;i++){var range=cm.listSelections()[i];range.empty()?cm.replaceRange(cm.getLine(range.head.line)+"\n",Pos(range.head.line,0)):cm.replaceRange(cm.getRange(range.from(),range.to()),range.from())}cm.scrollIntoView()})};map[ctrl+"T"]="transposeChars";cmds[map.F9="sortLines"]=function(cm){sortLines(cm,!0)};cmds[map[ctrl+"F9"]="sortLinesInsensitive"]=function(cm){sortLines(cm,!1)};cmds[map.F2="nextBookmark"]=function(cm){var marks=cm.state.sublimeBookmarks;if(marks)for(;marks.length;){var current=marks.shift(),found=current.find();if(found){marks.push(current);return cm.setSelection(found.from,found.to)}}};cmds[map["Shift-F2"]="prevBookmark"]=function(cm){var marks=cm.state.sublimeBookmarks;if(marks)for(;marks.length;){marks.unshift(marks.pop());var found=marks[marks.length-1].find();if(found)return cm.setSelection(found.from,found.to);marks.pop()}};cmds[map[ctrl+"F2"]="toggleBookmark"]=function(cm){for(var ranges=cm.listSelections(),marks=cm.state.sublimeBookmarks||(cm.state.sublimeBookmarks=[]),i=0;i<ranges.length;i++){for(var from=ranges[i].from(),to=ranges[i].to(),found=cm.findMarks(from,to),j=0;j<found.length;j++)if(found[j].sublimeBookmark){found[j].clear();for(var k=0;k<marks.length;k++)marks[k]==found[j]&&marks.splice(k--,1);break}j==found.length&&marks.push(cm.markText(from,to,{sublimeBookmark:!0,clearWhenEmpty:!1}))}};cmds[map["Shift-"+ctrl+"F2"]="clearBookmarks"]=function(cm){var marks=cm.state.sublimeBookmarks;if(marks)for(var i=0;i<marks.length;i++)marks[i].clear();marks.length=0};cmds[map["Alt-F2"]="selectBookmarks"]=function(cm){var marks=cm.state.sublimeBookmarks,ranges=[];if(marks)for(var i=0;i<marks.length;i++){var found=marks[i].find();found?ranges.push({anchor:found.from,head:found.to}):marks.splice(i--,0)}ranges.length&&cm.setSelections(ranges,0)};map["Alt-Q"]="wrapLines";var cK=ctrl+"K ";map[cK+ctrl+"Backspace"]="delLineLeft";cmds[map.Backspace="smartBackspace"]=function(cm){if(cm.somethingSelected())return CodeMirror.Pass;var cursor=cm.getCursor(),toStartOfLine=cm.getRange({line:cursor.line,ch:0},cursor),column=CodeMirror.countColumn(toStartOfLine,null,cm.getOption("tabSize")),indentUnit=cm.getOption("indentUnit");if(toStartOfLine&&!/\S/.test(toStartOfLine)&&column%indentUnit==0){var prevIndent=new Pos(cursor.line,CodeMirror.findColumn(toStartOfLine,column-indentUnit,indentUnit));return prevIndent.ch==cursor.ch?CodeMirror.Pass:cm.replaceRange("",prevIndent,cursor,"+delete")}return CodeMirror.Pass};cmds[map[cK+ctrl+"K"]="delLineRight"]=function(cm){cm.operation(function(){for(var ranges=cm.listSelections(),i=ranges.length-1;i>=0;i--)cm.replaceRange("",ranges[i].anchor,Pos(ranges[i].to().line),"+delete");cm.scrollIntoView()})};cmds[map[cK+ctrl+"U"]="upcaseAtCursor"]=function(cm){modifyWordOrSelection(cm,function(str){return str.toUpperCase()})};cmds[map[cK+ctrl+"L"]="downcaseAtCursor"]=function(cm){modifyWordOrSelection(cm,function(str){return str.toLowerCase()})};cmds[map[cK+ctrl+"Space"]="setSublimeMark"]=function(cm){cm.state.sublimeMark&&cm.state.sublimeMark.clear();cm.state.sublimeMark=cm.setBookmark(cm.getCursor())};cmds[map[cK+ctrl+"A"]="selectToSublimeMark"]=function(cm){var found=cm.state.sublimeMark&&cm.state.sublimeMark.find();found&&cm.setSelection(cm.getCursor(),found)};cmds[map[cK+ctrl+"W"]="deleteToSublimeMark"]=function(cm){var found=cm.state.sublimeMark&&cm.state.sublimeMark.find();if(found){var from=cm.getCursor(),to=found;if(CodeMirror.cmpPos(from,to)>0){var tmp=to;to=from;from=tmp}cm.state.sublimeKilled=cm.getRange(from,to);cm.replaceRange("",from,to)}};cmds[map[cK+ctrl+"X"]="swapWithSublimeMark"]=function(cm){var found=cm.state.sublimeMark&&cm.state.sublimeMark.find();if(found){cm.state.sublimeMark.clear();cm.state.sublimeMark=cm.setBookmark(cm.getCursor());cm.setCursor(found)}};cmds[map[cK+ctrl+"Y"]="sublimeYank"]=function(cm){null!=cm.state.sublimeKilled&&cm.replaceSelection(cm.state.sublimeKilled,null,"paste")};map[cK+ctrl+"G"]="clearBookmarks";cmds[map[cK+ctrl+"C"]="showInCenter"]=function(cm){var pos=cm.cursorCoords(null,"local");cm.scrollTo(null,(pos.top+pos.bottom)/2-cm.getScrollInfo().clientHeight/2)};cmds[map["Shift-Alt-Up"]="selectLinesUpward"]=function(cm){cm.operation(function(){for(var ranges=cm.listSelections(),i=0;i<ranges.length;i++){var range=ranges[i];range.head.line>cm.firstLine()&&cm.addSelection(Pos(range.head.line-1,range.head.ch))}})};cmds[map["Shift-Alt-Down"]="selectLinesDownward"]=function(cm){cm.operation(function(){for(var ranges=cm.listSelections(),i=0;i<ranges.length;i++){var range=ranges[i];range.head.line<cm.lastLine()&&cm.addSelection(Pos(range.head.line+1,range.head.ch))}})};cmds[map[ctrl+"F3"]="findUnder"]=function(cm){findAndGoTo(cm,!0)};cmds[map["Shift-"+ctrl+"F3"]="findUnderPrevious"]=function(cm){findAndGoTo(cm,!1)};cmds[map["Alt-F3"]="findAllUnder"]=function(cm){var target=getTarget(cm);if(target){for(var cur=cm.getSearchCursor(target.query),matches=[],primaryIndex=-1;cur.findNext();){matches.push({anchor:cur.from(),head:cur.to()});cur.from().line<=target.from.line&&cur.from().ch<=target.from.ch&&primaryIndex++}cm.setSelections(matches,primaryIndex)}};map["Shift-"+ctrl+"["]="fold";map["Shift-"+ctrl+"]"]="unfold";map[cK+ctrl+"0"]=map[cK+ctrl+"j"]="unfoldAll";map[ctrl+"I"]="findIncremental";map["Shift-"+ctrl+"I"]="findIncrementalReverse";map[ctrl+"H"]="replace";map.F3="findNext";map["Shift-F3"]="findPrev";CodeMirror.normalizeKeyMap(map)});
1
+ !function(mod){"object"==typeof exports&&"object"==typeof module?mod(require("../lib/codemirror"),require("../addon/search/searchcursor"),require("../addon/edit/matchbrackets")):"function"==typeof define&&define.amd?define(["../lib/codemirror","../addon/search/searchcursor","../addon/edit/matchbrackets"],mod):mod(CodeMirror)}(function(CodeMirror){"use strict";function findPosSubword(doc,start,dir){if(dir<0&&0==start.ch)return doc.clipPos(Pos(start.line-1));var line=doc.getLine(start.line);if(dir>0&&start.ch>=line.length)return doc.clipPos(Pos(start.line+1,0));for(var type,state="start",pos=start.ch,e=dir<0?0:line.length,i=0;pos!=e;pos+=dir,i++){var next=line.charAt(dir<0?pos-1:pos),cat="_"!=next&&CodeMirror.isWordChar(next)?"w":"o";"w"==cat&&next.toUpperCase()==next&&(cat="W");if("start"==state){if("o"!=cat){state="in";type=cat}}else if("in"==state&&type!=cat){"w"==type&&"W"==cat&&dir<0&&pos--;if("W"==type&&"w"==cat&&dir>0){type="w";continue}break}}return Pos(start.line,pos)}function moveSubword(cm,dir){cm.extendSelectionsBy(function(range){return cm.display.shift||cm.doc.extend||range.empty()?findPosSubword(cm.doc,range.head,dir):dir<0?range.from():range.to()})}function insertLine(cm,above){if(cm.isReadOnly())return CodeMirror.Pass;cm.operation(function(){for(var len=cm.listSelections().length,newSelection=[],last=-1,i=0;i<len;i++){var head=cm.listSelections()[i].head;if(!(head.line<=last)){var at=Pos(head.line+(above?0:1),0);cm.replaceRange("\n",at,null,"+insertLine");cm.indentLine(at.line,null,!0);newSelection.push({head:at,anchor:at});last=head.line+1}}cm.setSelections(newSelection)});cm.execCommand("indentAuto")}function wordAt(cm,pos){for(var start=pos.ch,end=start,line=cm.getLine(pos.line);start&&CodeMirror.isWordChar(line.charAt(start-1));)--start;for(;end<line.length&&CodeMirror.isWordChar(line.charAt(end));)++end;return{from:Pos(pos.line,start),to:Pos(pos.line,end),word:line.slice(start,end)}}function selectBetweenBrackets(cm){for(var ranges=cm.listSelections(),newRanges=[],i=0;i<ranges.length;i++){var range=ranges[i],pos=range.head,opening=cm.scanForBracket(pos,-1);if(!opening)return!1;for(;;){var closing=cm.scanForBracket(pos,1);if(!closing)return!1;if(closing.ch==mirror.charAt(mirror.indexOf(opening.ch)+1)){newRanges.push({anchor:Pos(opening.pos.line,opening.pos.ch+1),head:closing.pos});break}pos=Pos(closing.pos.line,closing.pos.ch+1)}}cm.setSelections(newRanges);return!0}function sortLines(cm,caseSensitive){if(cm.isReadOnly())return CodeMirror.Pass;for(var selected,ranges=cm.listSelections(),toSort=[],i=0;i<ranges.length;i++){var range=ranges[i];if(!range.empty()){for(var from=range.from().line,to=range.to().line;i<ranges.length-1&&ranges[i+1].from().line==to;)to=range[++i].to().line;toSort.push(from,to)}}toSort.length?selected=!0:toSort.push(cm.firstLine(),cm.lastLine());cm.operation(function(){for(var ranges=[],i=0;i<toSort.length;i+=2){var from=toSort[i],to=toSort[i+1],start=Pos(from,0),end=Pos(to),lines=cm.getRange(start,end,!1);caseSensitive?lines.sort():lines.sort(function(a,b){var au=a.toUpperCase(),bu=b.toUpperCase();if(au!=bu){a=au;b=bu}return a<b?-1:a==b?0:1});cm.replaceRange(lines,start,end);selected&&ranges.push({anchor:start,head:end})}selected&&cm.setSelections(ranges,0)})}function modifyWordOrSelection(cm,mod){cm.operation(function(){for(var ranges=cm.listSelections(),indices=[],replacements=[],i=0;i<ranges.length;i++){var range=ranges[i];if(range.empty()){indices.push(i);replacements.push("")}else replacements.push(mod(cm.getRange(range.from(),range.to())))}cm.replaceSelections(replacements,"around","case");for(var at,i=indices.length-1;i>=0;i--){var range=ranges[indices[i]];if(!(at&&CodeMirror.cmpPos(range.head,at)>0)){var word=wordAt(cm,range.head);at=word.from;cm.replaceRange(mod(word.word),word.from,word.to)}}})}function getTarget(cm){var from=cm.getCursor("from"),to=cm.getCursor("to");if(0==CodeMirror.cmpPos(from,to)){var word=wordAt(cm,from);if(!word.word)return;from=word.from;to=word.to}return{from:from,to:to,query:cm.getRange(from,to),word:word}}function findAndGoTo(cm,forward){var target=getTarget(cm);if(target){var query=target.query,cur=cm.getSearchCursor(query,forward?target.to:target.from);if(forward?cur.findNext():cur.findPrevious())cm.setSelection(cur.from(),cur.to());else{cur=cm.getSearchCursor(query,forward?Pos(cm.firstLine(),0):cm.clipPos(Pos(cm.lastLine())));(forward?cur.findNext():cur.findPrevious())?cm.setSelection(cur.from(),cur.to()):target.word&&cm.setSelection(target.from,target.to)}}}var map=CodeMirror.keyMap.sublime={fallthrough:"default"},cmds=CodeMirror.commands,Pos=CodeMirror.Pos,mac=CodeMirror.keyMap["default"]==CodeMirror.keyMap.macDefault,ctrl=mac?"Cmd-":"Ctrl-",goSubwordCombo=mac?"Ctrl-":"Alt-";cmds[map[goSubwordCombo+"Left"]="goSubwordLeft"]=function(cm){moveSubword(cm,-1)};cmds[map[goSubwordCombo+"Right"]="goSubwordRight"]=function(cm){moveSubword(cm,1)};mac&&(map["Cmd-Left"]="goLineStartSmart");var scrollLineCombo=mac?"Ctrl-Alt-":"Ctrl-";cmds[map[scrollLineCombo+"Up"]="scrollLineUp"]=function(cm){var info=cm.getScrollInfo();if(!cm.somethingSelected()){var visibleBottomLine=cm.lineAtHeight(info.top+info.clientHeight,"local");cm.getCursor().line>=visibleBottomLine&&cm.execCommand("goLineUp")}cm.scrollTo(null,info.top-cm.defaultTextHeight())};cmds[map[scrollLineCombo+"Down"]="scrollLineDown"]=function(cm){var info=cm.getScrollInfo();if(!cm.somethingSelected()){var visibleTopLine=cm.lineAtHeight(info.top,"local")+1;cm.getCursor().line<=visibleTopLine&&cm.execCommand("goLineDown")}cm.scrollTo(null,info.top+cm.defaultTextHeight())};cmds[map["Shift-"+ctrl+"L"]="splitSelectionByLine"]=function(cm){for(var ranges=cm.listSelections(),lineRanges=[],i=0;i<ranges.length;i++)for(var from=ranges[i].from(),to=ranges[i].to(),line=from.line;line<=to.line;++line)to.line>from.line&&line==to.line&&0==to.ch||lineRanges.push({anchor:line==from.line?from:Pos(line,0),head:line==to.line?to:Pos(line)});cm.setSelections(lineRanges,0)};map["Shift-Tab"]="indentLess";cmds[map.Esc="singleSelectionTop"]=function(cm){var range=cm.listSelections()[0];cm.setSelection(range.anchor,range.head,{scroll:!1})};cmds[map[ctrl+"L"]="selectLine"]=function(cm){for(var ranges=cm.listSelections(),extended=[],i=0;i<ranges.length;i++){var range=ranges[i];extended.push({anchor:Pos(range.from().line,0),head:Pos(range.to().line+1,0)})}cm.setSelections(extended)};map["Shift-Ctrl-K"]="deleteLine";cmds[map[ctrl+"Enter"]="insertLineAfter"]=function(cm){return insertLine(cm,!1)};cmds[map["Shift-"+ctrl+"Enter"]="insertLineBefore"]=function(cm){return insertLine(cm,!0)};cmds[map[ctrl+"D"]="selectNextOccurrence"]=function(cm){var from=cm.getCursor("from"),to=cm.getCursor("to"),fullWord=cm.state.sublimeFindFullWord==cm.doc.sel;if(0==CodeMirror.cmpPos(from,to)){var word=wordAt(cm,from);if(!word.word)return;cm.setSelection(word.from,word.to);fullWord=!0}else{var text=cm.getRange(from,to),query=fullWord?new RegExp("\\b"+text+"\\b"):text,cur=cm.getSearchCursor(query,to);if(cur.findNext())cm.addSelection(cur.from(),cur.to());else{cur=cm.getSearchCursor(query,Pos(cm.firstLine(),0));cur.findNext()&&cm.addSelection(cur.from(),cur.to())}}fullWord&&(cm.state.sublimeFindFullWord=cm.doc.sel)};var mirror="(){}[]";cmds[map["Shift-"+ctrl+"Space"]="selectScope"]=function(cm){selectBetweenBrackets(cm)||cm.execCommand("selectAll")};cmds[map["Shift-"+ctrl+"M"]="selectBetweenBrackets"]=function(cm){if(!selectBetweenBrackets(cm))return CodeMirror.Pass};cmds[map[ctrl+"M"]="goToBracket"]=function(cm){cm.extendSelectionsBy(function(range){var next=cm.scanForBracket(range.head,1);if(next&&0!=CodeMirror.cmpPos(next.pos,range.head))return next.pos;var prev=cm.scanForBracket(range.head,-1);return prev&&Pos(prev.pos.line,prev.pos.ch+1)||range.head})};var swapLineCombo=mac?"Cmd-Ctrl-":"Shift-Ctrl-";cmds[map[swapLineCombo+"Up"]="swapLineUp"]=function(cm){if(cm.isReadOnly())return CodeMirror.Pass;for(var ranges=cm.listSelections(),linesToMove=[],at=cm.firstLine()-1,newSels=[],i=0;i<ranges.length;i++){var range=ranges[i],from=range.from().line-1,to=range.to().line;newSels.push({anchor:Pos(range.anchor.line-1,range.anchor.ch),head:Pos(range.head.line-1,range.head.ch)});0!=range.to().ch||range.empty()||--to;from>at?linesToMove.push(from,to):linesToMove.length&&(linesToMove[linesToMove.length-1]=to);at=to}cm.operation(function(){for(var i=0;i<linesToMove.length;i+=2){var from=linesToMove[i],to=linesToMove[i+1],line=cm.getLine(from);cm.replaceRange("",Pos(from,0),Pos(from+1,0),"+swapLine");to>cm.lastLine()?cm.replaceRange("\n"+line,Pos(cm.lastLine()),null,"+swapLine"):cm.replaceRange(line+"\n",Pos(to,0),null,"+swapLine")}cm.setSelections(newSels);cm.scrollIntoView()})};cmds[map[swapLineCombo+"Down"]="swapLineDown"]=function(cm){if(cm.isReadOnly())return CodeMirror.Pass;for(var ranges=cm.listSelections(),linesToMove=[],at=cm.lastLine()+1,i=ranges.length-1;i>=0;i--){var range=ranges[i],from=range.to().line+1,to=range.from().line;0!=range.to().ch||range.empty()||from--;from<at?linesToMove.push(from,to):linesToMove.length&&(linesToMove[linesToMove.length-1]=to);at=to}cm.operation(function(){for(var i=linesToMove.length-2;i>=0;i-=2){var from=linesToMove[i],to=linesToMove[i+1],line=cm.getLine(from);from==cm.lastLine()?cm.replaceRange("",Pos(from-1),Pos(from),"+swapLine"):cm.replaceRange("",Pos(from,0),Pos(from+1,0),"+swapLine");cm.replaceRange(line+"\n",Pos(to,0),null,"+swapLine")}cm.scrollIntoView()})};cmds[map[ctrl+"/"]="toggleCommentIndented"]=function(cm){cm.toggleComment({indent:!0})};cmds[map[ctrl+"J"]="joinLines"]=function(cm){for(var ranges=cm.listSelections(),joined=[],i=0;i<ranges.length;i++){for(var range=ranges[i],from=range.from(),start=from.line,end=range.to().line;i<ranges.length-1&&ranges[i+1].from().line==end;)end=ranges[++i].to().line;joined.push({start:start,end:end,anchor:!range.empty()&&from})}cm.operation(function(){for(var offset=0,ranges=[],i=0;i<joined.length;i++){for(var head,obj=joined[i],anchor=obj.anchor&&Pos(obj.anchor.line-offset,obj.anchor.ch),line=obj.start;line<=obj.end;line++){var actual=line-offset;line==obj.end&&(head=Pos(actual,cm.getLine(actual).length+1));if(actual<cm.lastLine()){cm.replaceRange(" ",Pos(actual),Pos(actual+1,/^\s*/.exec(cm.getLine(actual+1))[0].length));++offset}}ranges.push({anchor:anchor||head,head:head})}cm.setSelections(ranges,0)})};cmds[map["Shift-"+ctrl+"D"]="duplicateLine"]=function(cm){cm.operation(function(){for(var rangeCount=cm.listSelections().length,i=0;i<rangeCount;i++){var range=cm.listSelections()[i];range.empty()?cm.replaceRange(cm.getLine(range.head.line)+"\n",Pos(range.head.line,0)):cm.replaceRange(cm.getRange(range.from(),range.to()),range.from())}cm.scrollIntoView()})};mac||(map[ctrl+"T"]="transposeChars");cmds[map.F9="sortLines"]=function(cm){sortLines(cm,!0)};cmds[map[ctrl+"F9"]="sortLinesInsensitive"]=function(cm){sortLines(cm,!1)};cmds[map.F2="nextBookmark"]=function(cm){var marks=cm.state.sublimeBookmarks;if(marks)for(;marks.length;){var current=marks.shift(),found=current.find();if(found){marks.push(current);return cm.setSelection(found.from,found.to)}}};cmds[map["Shift-F2"]="prevBookmark"]=function(cm){var marks=cm.state.sublimeBookmarks;if(marks)for(;marks.length;){marks.unshift(marks.pop());var found=marks[marks.length-1].find();if(found)return cm.setSelection(found.from,found.to);marks.pop()}};cmds[map[ctrl+"F2"]="toggleBookmark"]=function(cm){for(var ranges=cm.listSelections(),marks=cm.state.sublimeBookmarks||(cm.state.sublimeBookmarks=[]),i=0;i<ranges.length;i++){for(var from=ranges[i].from(),to=ranges[i].to(),found=cm.findMarks(from,to),j=0;j<found.length;j++)if(found[j].sublimeBookmark){found[j].clear();for(var k=0;k<marks.length;k++)marks[k]==found[j]&&marks.splice(k--,1);break}j==found.length&&marks.push(cm.markText(from,to,{sublimeBookmark:!0,clearWhenEmpty:!1}))}};cmds[map["Shift-"+ctrl+"F2"]="clearBookmarks"]=function(cm){var marks=cm.state.sublimeBookmarks;if(marks)for(var i=0;i<marks.length;i++)marks[i].clear();marks.length=0};cmds[map["Alt-F2"]="selectBookmarks"]=function(cm){var marks=cm.state.sublimeBookmarks,ranges=[];if(marks)for(var i=0;i<marks.length;i++){var found=marks[i].find();found?ranges.push({anchor:found.from,head:found.to}):marks.splice(i--,0)}ranges.length&&cm.setSelections(ranges,0)};map["Alt-Q"]="wrapLines";var cK=ctrl+"K ";map[cK+ctrl+"Backspace"]="delLineLeft";cmds[map.Backspace="smartBackspace"]=function(cm){if(cm.somethingSelected())return CodeMirror.Pass;cm.operation(function(){for(var cursors=cm.listSelections(),indentUnit=cm.getOption("indentUnit"),i=cursors.length-1;i>=0;i--){var cursor=cursors[i].head,toStartOfLine=cm.getRange({line:cursor.line,ch:0},cursor),column=CodeMirror.countColumn(toStartOfLine,null,cm.getOption("tabSize")),deletePos=cm.findPosH(cursor,-1,"char",!1);if(toStartOfLine&&!/\S/.test(toStartOfLine)&&column%indentUnit==0){var prevIndent=new Pos(cursor.line,CodeMirror.findColumn(toStartOfLine,column-indentUnit,indentUnit));prevIndent.ch!=cursor.ch&&(deletePos=prevIndent)}cm.replaceRange("",deletePos,cursor,"+delete")}})};cmds[map[cK+ctrl+"K"]="delLineRight"]=function(cm){cm.operation(function(){for(var ranges=cm.listSelections(),i=ranges.length-1;i>=0;i--)cm.replaceRange("",ranges[i].anchor,Pos(ranges[i].to().line),"+delete");cm.scrollIntoView()})};cmds[map[cK+ctrl+"U"]="upcaseAtCursor"]=function(cm){modifyWordOrSelection(cm,function(str){return str.toUpperCase()})};cmds[map[cK+ctrl+"L"]="downcaseAtCursor"]=function(cm){modifyWordOrSelection(cm,function(str){return str.toLowerCase()})};cmds[map[cK+ctrl+"Space"]="setSublimeMark"]=function(cm){cm.state.sublimeMark&&cm.state.sublimeMark.clear();cm.state.sublimeMark=cm.setBookmark(cm.getCursor())};cmds[map[cK+ctrl+"A"]="selectToSublimeMark"]=function(cm){var found=cm.state.sublimeMark&&cm.state.sublimeMark.find();found&&cm.setSelection(cm.getCursor(),found)};cmds[map[cK+ctrl+"W"]="deleteToSublimeMark"]=function(cm){var found=cm.state.sublimeMark&&cm.state.sublimeMark.find();if(found){var from=cm.getCursor(),to=found;if(CodeMirror.cmpPos(from,to)>0){var tmp=to;to=from;from=tmp}cm.state.sublimeKilled=cm.getRange(from,to);cm.replaceRange("",from,to)}};cmds[map[cK+ctrl+"X"]="swapWithSublimeMark"]=function(cm){var found=cm.state.sublimeMark&&cm.state.sublimeMark.find();if(found){cm.state.sublimeMark.clear();cm.state.sublimeMark=cm.setBookmark(cm.getCursor());cm.setCursor(found)}};cmds[map[cK+ctrl+"Y"]="sublimeYank"]=function(cm){null!=cm.state.sublimeKilled&&cm.replaceSelection(cm.state.sublimeKilled,null,"paste")};map[cK+ctrl+"G"]="clearBookmarks";cmds[map[cK+ctrl+"C"]="showInCenter"]=function(cm){var pos=cm.cursorCoords(null,"local");cm.scrollTo(null,(pos.top+pos.bottom)/2-cm.getScrollInfo().clientHeight/2)};var selectLinesCombo=mac?"Ctrl-Shift-":"Ctrl-Alt-";cmds[map[selectLinesCombo+"Up"]="selectLinesUpward"]=function(cm){cm.operation(function(){for(var ranges=cm.listSelections(),i=0;i<ranges.length;i++){var range=ranges[i];range.head.line>cm.firstLine()&&cm.addSelection(Pos(range.head.line-1,range.head.ch))}})};cmds[map[selectLinesCombo+"Down"]="selectLinesDownward"]=function(cm){cm.operation(function(){for(var ranges=cm.listSelections(),i=0;i<ranges.length;i++){var range=ranges[i];range.head.line<cm.lastLine()&&cm.addSelection(Pos(range.head.line+1,range.head.ch))}})};cmds[map[ctrl+"F3"]="findUnder"]=function(cm){findAndGoTo(cm,!0)};cmds[map["Shift-"+ctrl+"F3"]="findUnderPrevious"]=function(cm){findAndGoTo(cm,!1)};cmds[map["Alt-F3"]="findAllUnder"]=function(cm){var target=getTarget(cm);if(target){for(var cur=cm.getSearchCursor(target.query),matches=[],primaryIndex=-1;cur.findNext();){matches.push({anchor:cur.from(),head:cur.to()});cur.from().line<=target.from.line&&cur.from().ch<=target.from.ch&&primaryIndex++}cm.setSelections(matches,primaryIndex)}};map["Shift-"+ctrl+"["]="fold";map["Shift-"+ctrl+"]"]="unfold";map[cK+ctrl+"0"]=map[cK+ctrl+"J"]="unfoldAll";map[ctrl+"I"]="findIncremental";map["Shift-"+ctrl+"I"]="findIncrementalReverse";map[ctrl+"H"]="replace";map.F3="findNext";map["Shift-F3"]="findPrev";CodeMirror.normalizeKeyMap(map)});
js/esites_editor/dist/js/vendor/codemirror/keymap/vim.js CHANGED
@@ -1,4 +1,4 @@
1
- !function(mod){"object"==typeof exports&&"object"==typeof module?mod(require("../lib/codemirror"),require("../addon/search/searchcursor"),require("../addon/dialog/dialog"),require("../addon/edit/matchbrackets.js")):"function"==typeof define&&define.amd?define(["../lib/codemirror","../addon/search/searchcursor","../addon/dialog/dialog","../addon/edit/matchbrackets"],mod):mod(CodeMirror)}(function(CodeMirror){"use strict";var defaultKeymap=[{keys:"<Left>",type:"keyToKey",toKeys:"h"},{keys:"<Right>",type:"keyToKey",toKeys:"l"},{keys:"<Up>",type:"keyToKey",toKeys:"k"},{keys:"<Down>",type:"keyToKey",toKeys:"j"},{keys:"<Space>",type:"keyToKey",toKeys:"l"},{keys:"<BS>",type:"keyToKey",toKeys:"h",context:"normal"},{keys:"<C-Space>",type:"keyToKey",toKeys:"W"},{keys:"<C-BS>",type:"keyToKey",toKeys:"B",context:"normal"},{keys:"<S-Space>",type:"keyToKey",toKeys:"w"},{keys:"<S-BS>",type:"keyToKey",toKeys:"b",context:"normal"},{keys:"<C-n>",type:"keyToKey",toKeys:"j"},{keys:"<C-p>",type:"keyToKey",toKeys:"k"},{keys:"<C-[>",type:"keyToKey",toKeys:"<Esc>"},{keys:"<C-c>",type:"keyToKey",toKeys:"<Esc>"},{keys:"<C-[>",type:"keyToKey",toKeys:"<Esc>",context:"insert"},{keys:"<C-c>",type:"keyToKey",toKeys:"<Esc>",context:"insert"},{keys:"s",type:"keyToKey",toKeys:"cl",context:"normal"},{keys:"s",type:"keyToKey",toKeys:"c",context:"visual"},{keys:"S",type:"keyToKey",toKeys:"cc",context:"normal"},{keys:"S",type:"keyToKey",toKeys:"VdO",context:"visual"},{keys:"<Home>",type:"keyToKey",toKeys:"0"},{keys:"<End>",type:"keyToKey",toKeys:"$"},{keys:"<PageUp>",type:"keyToKey",toKeys:"<C-b>"},{keys:"<PageDown>",type:"keyToKey",toKeys:"<C-f>"},{keys:"<CR>",type:"keyToKey",toKeys:"j^",context:"normal"},{keys:"H",type:"motion",motion:"moveToTopLine",motionArgs:{linewise:!0,toJumplist:!0}},{keys:"M",type:"motion",motion:"moveToMiddleLine",motionArgs:{linewise:!0,toJumplist:!0}},{keys:"L",type:"motion",motion:"moveToBottomLine",motionArgs:{linewise:!0,toJumplist:!0}},{keys:"h",type:"motion",motion:"moveByCharacters",motionArgs:{forward:!1}},{keys:"l",type:"motion",motion:"moveByCharacters",motionArgs:{forward:!0}},{keys:"j",type:"motion",motion:"moveByLines",motionArgs:{forward:!0,linewise:!0}},{keys:"k",type:"motion",motion:"moveByLines",motionArgs:{forward:!1,linewise:!0}},{keys:"gj",type:"motion",motion:"moveByDisplayLines",motionArgs:{forward:!0}},{keys:"gk",type:"motion",motion:"moveByDisplayLines",motionArgs:{forward:!1}},{keys:"w",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!1}},{keys:"W",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!1,bigWord:!0}},{keys:"e",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!0,inclusive:!0}},{keys:"E",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!0,bigWord:!0,inclusive:!0}},{keys:"b",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!1}},{keys:"B",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!1,bigWord:!0}},{keys:"ge",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!0,inclusive:!0}},{keys:"gE",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!0,bigWord:!0,inclusive:!0}},{keys:"{",type:"motion",motion:"moveByParagraph",motionArgs:{forward:!1,toJumplist:!0}},{keys:"}",type:"motion",motion:"moveByParagraph",motionArgs:{forward:!0,toJumplist:!0}},{keys:"<C-f>",type:"motion",motion:"moveByPage",motionArgs:{forward:!0}},{keys:"<C-b>",type:"motion",motion:"moveByPage",motionArgs:{forward:!1}},{keys:"<C-d>",type:"motion",motion:"moveByScroll",motionArgs:{forward:!0,explicitRepeat:!0}},{keys:"<C-u>",type:"motion",motion:"moveByScroll",motionArgs:{forward:!1,explicitRepeat:!0}},{keys:"gg",type:"motion",motion:"moveToLineOrEdgeOfDocument",motionArgs:{forward:!1,explicitRepeat:!0,linewise:!0,toJumplist:!0}},{keys:"G",type:"motion",motion:"moveToLineOrEdgeOfDocument",motionArgs:{forward:!0,explicitRepeat:!0,linewise:!0,toJumplist:!0}},{keys:"0",type:"motion",motion:"moveToStartOfLine"},{keys:"^",type:"motion",motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:"+",type:"motion",motion:"moveByLines",motionArgs:{forward:!0,toFirstChar:!0}},{keys:"-",type:"motion",motion:"moveByLines",motionArgs:{forward:!1,toFirstChar:!0}},{keys:"_",type:"motion",motion:"moveByLines",motionArgs:{forward:!0,toFirstChar:!0,repeatOffset:-1}},{keys:"$",type:"motion",motion:"moveToEol",motionArgs:{inclusive:!0}},{keys:"%",type:"motion",motion:"moveToMatchedSymbol",motionArgs:{inclusive:!0,toJumplist:!0}},{keys:"f<character>",type:"motion",motion:"moveToCharacter",motionArgs:{forward:!0,inclusive:!0}},{keys:"F<character>",type:"motion",motion:"moveToCharacter",motionArgs:{forward:!1}},{keys:"t<character>",type:"motion",motion:"moveTillCharacter",motionArgs:{forward:!0,inclusive:!0}},{keys:"T<character>",type:"motion",motion:"moveTillCharacter",motionArgs:{forward:!1}},{keys:";",type:"motion",motion:"repeatLastCharacterSearch",motionArgs:{forward:!0}},{keys:",",type:"motion",motion:"repeatLastCharacterSearch",motionArgs:{forward:!1}},{keys:"'<character>",type:"motion",motion:"goToMark",motionArgs:{toJumplist:!0,linewise:!0}},{keys:"`<character>",type:"motion",motion:"goToMark",motionArgs:{toJumplist:!0}},{keys:"]`",type:"motion",motion:"jumpToMark",motionArgs:{forward:!0}},{keys:"[`",type:"motion",motion:"jumpToMark",motionArgs:{forward:!1}},{keys:"]'",type:"motion",motion:"jumpToMark",motionArgs:{forward:!0,linewise:!0}},{keys:"['",type:"motion",motion:"jumpToMark",motionArgs:{forward:!1,linewise:!0}},{keys:"]p",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!0,isEdit:!0,matchIndent:!0}},{keys:"[p",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!1,isEdit:!0,matchIndent:!0}},{keys:"]<character>",type:"motion",motion:"moveToSymbol",motionArgs:{forward:!0,toJumplist:!0}},{keys:"[<character>",type:"motion",motion:"moveToSymbol",motionArgs:{forward:!1,toJumplist:!0}},{keys:"|",type:"motion",motion:"moveToColumn"},{keys:"o",type:"motion",motion:"moveToOtherHighlightedEnd",context:"visual"},{keys:"O",type:"motion",motion:"moveToOtherHighlightedEnd",motionArgs:{sameLine:!0},context:"visual"},{keys:"d",type:"operator",operator:"delete"},{keys:"y",type:"operator",operator:"yank"},{keys:"c",type:"operator",operator:"change"},{keys:">",type:"operator",operator:"indent",operatorArgs:{indentRight:!0}},{keys:"<",type:"operator",operator:"indent",operatorArgs:{indentRight:!1}},{keys:"g~",type:"operator",operator:"changeCase"},{keys:"gu",type:"operator",operator:"changeCase",operatorArgs:{toLower:!0},isEdit:!0},{keys:"gU",type:"operator",operator:"changeCase",operatorArgs:{toLower:!1},isEdit:!0},{keys:"n",type:"motion",motion:"findNext",motionArgs:{forward:!0,toJumplist:!0}},{keys:"N",type:"motion",motion:"findNext",motionArgs:{forward:!1,toJumplist:!0}},{keys:"x",type:"operatorMotion",operator:"delete",motion:"moveByCharacters",motionArgs:{forward:!0},operatorMotionArgs:{visualLine:!1}},{keys:"X",type:"operatorMotion",operator:"delete",motion:"moveByCharacters",motionArgs:{forward:!1},operatorMotionArgs:{visualLine:!0}},{keys:"D",type:"operatorMotion",operator:"delete",motion:"moveToEol",motionArgs:{inclusive:!0},context:"normal"},{keys:"D",type:"operator",operator:"delete",operatorArgs:{linewise:!0},context:"visual"},{keys:"Y",type:"operatorMotion",operator:"yank",motion:"moveToEol",motionArgs:{inclusive:!0},context:"normal"},{keys:"Y",type:"operator",operator:"yank",operatorArgs:{linewise:!0},context:"visual"},{keys:"C",type:"operatorMotion",operator:"change",motion:"moveToEol",motionArgs:{inclusive:!0},context:"normal"},{keys:"C",type:"operator",operator:"change",operatorArgs:{linewise:!0},context:"visual"},{keys:"~",type:"operatorMotion",operator:"changeCase",motion:"moveByCharacters",motionArgs:{forward:!0},operatorArgs:{shouldMoveCursor:!0},context:"normal"},{keys:"~",type:"operator",operator:"changeCase",context:"visual"},{keys:"<C-w>",type:"operatorMotion",operator:"delete",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!1},context:"insert"},{keys:"<C-i>",type:"action",action:"jumpListWalk",actionArgs:{forward:!0}},{keys:"<C-o>",type:"action",action:"jumpListWalk",actionArgs:{forward:!1}},{keys:"<C-e>",type:"action",action:"scroll",actionArgs:{forward:!0,linewise:!0}},{keys:"<C-y>",type:"action",action:"scroll",actionArgs:{forward:!1,linewise:!0}},{keys:"a",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"charAfter"},context:"normal"},{keys:"A",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"eol"},context:"normal"},{keys:"A",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"endOfSelectedArea"},context:"visual"},{keys:"i",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"inplace"},context:"normal"},{keys:"I",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"firstNonBlank"},context:"normal"},{keys:"I",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"startOfSelectedArea"},context:"visual"},{keys:"o",type:"action",action:"newLineAndEnterInsertMode",isEdit:!0,interlaceInsertRepeat:!0,actionArgs:{after:!0},context:"normal"},{keys:"O",type:"action",action:"newLineAndEnterInsertMode",isEdit:!0,interlaceInsertRepeat:!0,actionArgs:{after:!1},context:"normal"},{keys:"v",type:"action",action:"toggleVisualMode"},{keys:"V",type:"action",action:"toggleVisualMode",actionArgs:{linewise:!0}},{keys:"<C-v>",type:"action",action:"toggleVisualMode",actionArgs:{blockwise:!0}},{keys:"<C-q>",type:"action",action:"toggleVisualMode",actionArgs:{blockwise:!0}},{keys:"gv",type:"action",action:"reselectLastSelection"},{keys:"J",type:"action",action:"joinLines",isEdit:!0},{keys:"p",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!0,isEdit:!0}},{keys:"P",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!1,isEdit:!0}},{keys:"r<character>",type:"action",action:"replace",isEdit:!0},{keys:"@<character>",type:"action",action:"replayMacro"},{keys:"q<character>",type:"action",action:"enterMacroRecordMode"},{keys:"R",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{replace:!0}},{keys:"u",type:"action",action:"undo",context:"normal"},{keys:"u",type:"operator",operator:"changeCase",operatorArgs:{toLower:!0},context:"visual",isEdit:!0},{keys:"U",type:"operator",operator:"changeCase",operatorArgs:{toLower:!1},context:"visual",isEdit:!0},{keys:"<C-r>",type:"action",action:"redo"},{keys:"m<character>",type:"action",action:"setMark"},{keys:'"<character>',type:"action",action:"setRegister"},{keys:"zz",type:"action",action:"scrollToCursor",actionArgs:{position:"center"}},{keys:"z.",type:"action",action:"scrollToCursor",actionArgs:{position:"center"},motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:"zt",type:"action",action:"scrollToCursor",actionArgs:{position:"top"}},{keys:"z<CR>",type:"action",action:"scrollToCursor",actionArgs:{position:"top"},motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:"z-",type:"action",action:"scrollToCursor",actionArgs:{position:"bottom"}},{keys:"zb",type:"action",action:"scrollToCursor",actionArgs:{position:"bottom"},motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:".",type:"action",action:"repeatLastEdit"},{keys:"<C-a>",type:"action",action:"incrementNumberToken",isEdit:!0,actionArgs:{increase:!0,backtrack:!1}},{keys:"<C-x>",type:"action",action:"incrementNumberToken",isEdit:!0,actionArgs:{increase:!1,backtrack:!1}},{keys:"a<character>",type:"motion",motion:"textObjectManipulation"},{keys:"i<character>",type:"motion",motion:"textObjectManipulation",motionArgs:{textObjectInner:!0}},{keys:"/",type:"search",searchArgs:{forward:!0,querySrc:"prompt",toJumplist:!0}},{keys:"?",type:"search",searchArgs:{forward:!1,querySrc:"prompt",toJumplist:!0}},{keys:"*",type:"search",searchArgs:{forward:!0,querySrc:"wordUnderCursor",wholeWordOnly:!0,toJumplist:!0}},{keys:"#",type:"search",searchArgs:{forward:!1,querySrc:"wordUnderCursor",wholeWordOnly:!0,toJumplist:!0}},{keys:"g*",type:"search",searchArgs:{forward:!0,querySrc:"wordUnderCursor",toJumplist:!0}},{keys:"g#",type:"search",searchArgs:{forward:!1,querySrc:"wordUnderCursor",toJumplist:!0}},{keys:":",type:"ex"}],defaultExCommandMap=[{name:"colorscheme",shortName:"colo"},{name:"map"},{name:"imap",shortName:"im"},{name:"nmap",shortName:"nm"},{name:"vmap",shortName:"vm"},{name:"unmap"},{name:"write",shortName:"w"},{name:"undo",shortName:"u"},{name:"redo",shortName:"red"},{name:"set",shortName:"se"},{name:"set",shortName:"se"},{name:"setlocal",shortName:"setl"},{name:"setglobal",shortName:"setg"},{name:"sort",shortName:"sor"},{name:"substitute",shortName:"s",possiblyAsync:!0},{name:"nohlsearch",shortName:"noh"},{name:"yank",shortName:"y"},{name:"delmarks",shortName:"delm"},{name:"registers",shortName:"reg",excludeFromCommandHistory:!0},{name:"global",shortName:"g"}],Pos=CodeMirror.Pos,Vim=function(){function enterVimMode(cm){cm.setOption("disableInput",!0);cm.setOption("showCursorWhenSelecting",!1);CodeMirror.signal(cm,"vim-mode-change",{mode:"normal"});cm.on("cursorActivity",onCursorActivity);maybeInitVimState(cm);CodeMirror.on(cm.getInputField(),"paste",getOnPasteFn(cm))}function leaveVimMode(cm){cm.setOption("disableInput",!1);cm.off("cursorActivity",onCursorActivity);CodeMirror.off(cm.getInputField(),"paste",getOnPasteFn(cm));cm.state.vim=null}function detachVimMap(cm,next){this==CodeMirror.keyMap.vim&&CodeMirror.rmClass(cm.getWrapperElement(),"cm-fat-cursor");next&&next.attach==attachVimMap||leaveVimMode(cm,!1)}function attachVimMap(cm,prev){this==CodeMirror.keyMap.vim&&CodeMirror.addClass(cm.getWrapperElement(),"cm-fat-cursor");prev&&prev.attach==attachVimMap||enterVimMode(cm)}function cmKey(key,cm){if(!cm)return void 0;var vimKey=cmKeyToVimKey(key);if(!vimKey)return!1;var cmd=CodeMirror.Vim.findKey(cm,vimKey);"function"==typeof cmd&&CodeMirror.signal(cm,"vim-keypress",vimKey);return cmd}function cmKeyToVimKey(key){if("'"==key.charAt(0))return key.charAt(1);var pieces=key.split(/-(?!$)/),lastPiece=pieces[pieces.length-1];if(1==pieces.length&&1==pieces[0].length)return!1;if(2==pieces.length&&"Shift"==pieces[0]&&1==lastPiece.length)return!1;for(var hasCharacter=!1,i=0;i<pieces.length;i++){var piece=pieces[i];piece in modifiers?pieces[i]=modifiers[piece]:hasCharacter=!0;piece in specialKeys&&(pieces[i]=specialKeys[piece])}if(!hasCharacter)return!1;isUpperCase(lastPiece)&&(pieces[pieces.length-1]=lastPiece.toLowerCase());return"<"+pieces.join("-")+">"}function getOnPasteFn(cm){var vim=cm.state.vim;vim.onPasteFn||(vim.onPasteFn=function(){if(!vim.insertMode){cm.setCursor(offsetCursor(cm.getCursor(),0,1));actions.enterInsertMode(cm,{},vim)}});return vim.onPasteFn}function makeKeyRange(start,size){for(var keys=[],i=start;start+size>i;i++)keys.push(String.fromCharCode(i));return keys}function isLine(cm,line){return line>=cm.firstLine()&&line<=cm.lastLine()}function isLowerCase(k){return/^[a-z]$/.test(k)}function isMatchableSymbol(k){return-1!="()[]{}".indexOf(k)}function isNumber(k){return numberRegex.test(k)}function isUpperCase(k){return/^[A-Z]$/.test(k)}function isWhiteSpaceString(k){return/^\s*$/.test(k)}function inArray(val,arr){for(var i=0;i<arr.length;i++)if(arr[i]==val)return!0;return!1}function defineOption(name,defaultValue,type,aliases,callback){if(void 0===defaultValue&&!callback)throw Error("defaultValue is required unless callback is provided");type||(type="string");options[name]={type:type,defaultValue:defaultValue,callback:callback};if(aliases)for(var i=0;i<aliases.length;i++)options[aliases[i]]=options[name];defaultValue&&setOption(name,defaultValue)}function setOption(name,value,cm,cfg){var option=options[name];cfg=cfg||{};var scope=cfg.scope;if(!option)throw Error("Unknown option: "+name);if("boolean"==option.type){if(value&&value!==!0)throw Error("Invalid argument: "+name+"="+value);value!==!1&&(value=!0)}if(option.callback){"local"!==scope&&option.callback(value,void 0);"global"!==scope&&cm&&option.callback(value,cm)}else{"local"!==scope&&(option.value="boolean"==option.type?!!value:value);"global"!==scope&&cm&&(cm.state.vim.options[name]={value:value})}}function getOption(name,cm,cfg){var option=options[name];cfg=cfg||{};var scope=cfg.scope;if(!option)throw Error("Unknown option: "+name);if(!option.callback){var local="global"!==scope&&cm&&cm.state.vim.options[name];return(local||"local"!==scope&&option||{}).value}var local=cm&&option.callback(void 0,cm);return"global"!==scope&&void 0!==local?local:"local"!==scope?option.callback():void 0}function MacroModeState(){this.latestRegister=void 0;this.isPlaying=!1;this.isRecording=!1;this.replaySearchQueries=[];this.onRecordingDone=void 0;this.lastInsertModeChanges=createInsertModeChanges()}function maybeInitVimState(cm){cm.state.vim||(cm.state.vim={inputState:new InputState,lastEditInputState:void 0,lastEditActionCommand:void 0,lastHPos:-1,lastHSPos:-1,lastMotion:null,marks:{},fakeCursor:null,insertMode:!1,insertModeRepeat:void 0,visualMode:!1,visualLine:!1,visualBlock:!1,lastSelection:null,lastPastedText:null,sel:{},options:{}});return cm.state.vim}function resetVimGlobalState(){vimGlobalState={searchQuery:null,searchIsReversed:!1,lastSubstituteReplacePart:void 0,jumpList:createCircularJumpList(),macroModeState:new MacroModeState,lastCharacterSearch:{increment:0,forward:!0,selectedCharacter:""},registerController:new RegisterController({}),searchHistoryController:new HistoryController({}),exCommandHistoryController:new HistoryController({})};for(var optionName in options){var option=options[optionName];option.value=option.defaultValue}}function InputState(){this.prefixRepeat=[];this.motionRepeat=[];this.operator=null;this.operatorArgs=null;this.motion=null;this.motionArgs=null;this.keyBuffer=[];this.registerName=null}function clearInputState(cm,reason){cm.state.vim.inputState=new InputState;CodeMirror.signal(cm,"vim-command-done",reason)}function Register(text,linewise,blockwise){this.clear();this.keyBuffer=[text||""];this.insertModeChanges=[];this.searchQueries=[];this.linewise=!!linewise;this.blockwise=!!blockwise}function defineRegister(name,register){var registers=vimGlobalState.registerController.registers[name];if(!name||1!=name.length)throw Error("Register name must be 1 character");if(registers[name])throw Error("Register already defined "+name);registers[name]=register;validRegisters.push(name)}function RegisterController(registers){this.registers=registers;this.unnamedRegister=registers['"']=new Register;registers["."]=new Register;registers[":"]=new Register;registers["/"]=new Register}function HistoryController(){this.historyBuffer=[];this.iterator=0;this.initialPrefix=null}function defineMotion(name,fn){motions[name]=fn}function fillArray(val,times){for(var arr=[],i=0;times>i;i++)arr.push(val);return arr}function defineOperator(name,fn){operators[name]=fn}function defineAction(name,fn){actions[name]=fn}function clipCursorToContent(cm,cur,includeLineBreak){var line=Math.min(Math.max(cm.firstLine(),cur.line),cm.lastLine()),maxCh=lineLength(cm,line)-1;maxCh=includeLineBreak?maxCh+1:maxCh;var ch=Math.min(Math.max(0,cur.ch),maxCh);return Pos(line,ch)}function copyArgs(args){var ret={};for(var prop in args)args.hasOwnProperty(prop)&&(ret[prop]=args[prop]);return ret}function offsetCursor(cur,offsetLine,offsetCh){if("object"==typeof offsetLine){offsetCh=offsetLine.ch;offsetLine=offsetLine.line}return Pos(cur.line+offsetLine,cur.ch+offsetCh)}function getOffset(anchor,head){return{line:head.line-anchor.line,ch:head.line-anchor.line}}function commandMatches(keys,keyMap,context,inputState){for(var match,partial=[],full=[],i=0;i<keyMap.length;i++){var command=keyMap[i];if(!("insert"==context&&"insert"!=command.context||command.context&&command.context!=context||inputState.operator&&"action"==command.type)&&(match=commandMatch(keys,command.keys))){"partial"==match&&partial.push(command);"full"==match&&full.push(command)}}return{partial:partial.length&&partial,full:full.length&&full}}function commandMatch(pressed,mapped){if("<character>"==mapped.slice(-11)){var prefixLen=mapped.length-11,pressedPrefix=pressed.slice(0,prefixLen),mappedPrefix=mapped.slice(0,prefixLen);return pressedPrefix==mappedPrefix&&pressed.length>prefixLen?"full":0==mappedPrefix.indexOf(pressedPrefix)?"partial":!1}return pressed==mapped?"full":0==mapped.indexOf(pressed)?"partial":!1}function lastChar(keys){var match=/^.*(<[\w\-]+>)$/.exec(keys),selectedCharacter=match?match[1]:keys.slice(-1);if(selectedCharacter.length>1)switch(selectedCharacter){case"<CR>":selectedCharacter="\n";break;case"<Space>":selectedCharacter=" "}return selectedCharacter}function repeatFn(cm,fn,repeat){return function(){for(var i=0;repeat>i;i++)fn(cm)}}function copyCursor(cur){return Pos(cur.line,cur.ch)}function cursorEqual(cur1,cur2){return cur1.ch==cur2.ch&&cur1.line==cur2.line}function cursorIsBefore(cur1,cur2){return cur1.line<cur2.line?!0:cur1.line==cur2.line&&cur1.ch<cur2.ch?!0:!1}function cursorMin(cur1,cur2){arguments.length>2&&(cur2=cursorMin.apply(void 0,Array.prototype.slice.call(arguments,1)));return cursorIsBefore(cur1,cur2)?cur1:cur2}function cursorMax(cur1,cur2){arguments.length>2&&(cur2=cursorMax.apply(void 0,Array.prototype.slice.call(arguments,1)));return cursorIsBefore(cur1,cur2)?cur2:cur1}function cursorIsBetween(cur1,cur2,cur3){var cur1before2=cursorIsBefore(cur1,cur2),cur2before3=cursorIsBefore(cur2,cur3);return cur1before2&&cur2before3}function lineLength(cm,lineNum){return cm.getLine(lineNum).length}function trim(s){return s.trim?s.trim():s.replace(/^\s+|\s+$/g,"")}function escapeRegex(s){return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g,"\\$1")}function extendLineToColumn(cm,lineNum,column){var endCh=lineLength(cm,lineNum),spaces=new Array(column-endCh+1).join(" ");cm.setCursor(Pos(lineNum,endCh));cm.replaceRange(spaces,cm.getCursor())}function selectBlock(cm,selectionEnd){var selections=[],ranges=cm.listSelections(),head=copyCursor(cm.clipPos(selectionEnd)),isClipped=!cursorEqual(selectionEnd,head),curHead=cm.getCursor("head"),primIndex=getIndex(ranges,curHead),wasClipped=cursorEqual(ranges[primIndex].head,ranges[primIndex].anchor),max=ranges.length-1,index=max-primIndex>primIndex?max:0,base=ranges[index].anchor,firstLine=Math.min(base.line,head.line),lastLine=Math.max(base.line,head.line),baseCh=base.ch,headCh=head.ch,dir=ranges[index].head.ch-baseCh,newDir=headCh-baseCh;if(dir>0&&0>=newDir){baseCh++;isClipped||headCh--}else if(0>dir&&newDir>=0){baseCh--;wasClipped||headCh++}else if(0>dir&&-1==newDir){baseCh--;headCh++}for(var line=firstLine;lastLine>=line;line++){var range={anchor:new Pos(line,baseCh),head:new Pos(line,headCh)};selections.push(range)}primIndex=head.line==lastLine?selections.length-1:0;cm.setSelections(selections);selectionEnd.ch=headCh;base.ch=baseCh;return base}function selectForInsert(cm,head,height){for(var sel=[],i=0;height>i;i++){var lineHead=offsetCursor(head,i,0);sel.push({anchor:lineHead,head:lineHead})}cm.setSelections(sel,0)}function getIndex(ranges,cursor,end){for(var i=0;i<ranges.length;i++){var atAnchor="head"!=end&&cursorEqual(ranges[i].anchor,cursor),atHead="anchor"!=end&&cursorEqual(ranges[i].head,cursor);if(atAnchor||atHead)return i}return-1}function getSelectedAreaRange(cm,vim){var lastSelection=vim.lastSelection,getCurrentSelectedAreaRange=function(){var selections=cm.listSelections(),start=selections[0],end=selections[selections.length-1],selectionStart=cursorIsBefore(start.anchor,start.head)?start.anchor:start.head,selectionEnd=cursorIsBefore(end.anchor,end.head)?end.head:end.anchor;return[selectionStart,selectionEnd]},getLastSelectedAreaRange=function(){var selectionStart=cm.getCursor(),selectionEnd=cm.getCursor(),block=lastSelection.visualBlock;if(block){var width=block.width,height=block.height;selectionEnd=Pos(selectionStart.line+height,selectionStart.ch+width);for(var selections=[],i=selectionStart.line;i<selectionEnd.line;i++){var anchor=Pos(i,selectionStart.ch),head=Pos(i,selectionEnd.ch),range={anchor:anchor,head:head};selections.push(range)}cm.setSelections(selections)}else{var start=lastSelection.anchorMark.find(),end=lastSelection.headMark.find(),line=end.line-start.line,ch=end.ch-start.ch;selectionEnd={line:selectionEnd.line+line,ch:line?selectionEnd.ch:ch+selectionEnd.ch};if(lastSelection.visualLine){selectionStart=Pos(selectionStart.line,0);selectionEnd=Pos(selectionEnd.line,lineLength(cm,selectionEnd.line))}cm.setSelection(selectionStart,selectionEnd)}return[selectionStart,selectionEnd]};return vim.visualMode?getCurrentSelectedAreaRange():getLastSelectedAreaRange()}function updateLastSelection(cm,vim){var anchor=vim.sel.anchor,head=vim.sel.head;if(vim.lastPastedText){head=cm.posFromIndex(cm.indexFromPos(anchor)+vim.lastPastedText.length);vim.lastPastedText=null}vim.lastSelection={anchorMark:cm.setBookmark(anchor),headMark:cm.setBookmark(head),anchor:copyCursor(anchor),head:copyCursor(head),visualMode:vim.visualMode,visualLine:vim.visualLine,visualBlock:vim.visualBlock}}function expandSelection(cm,start,end){var tmp,sel=cm.state.vim.sel,head=sel.head,anchor=sel.anchor;if(cursorIsBefore(end,start)){tmp=end;end=start;start=tmp}if(cursorIsBefore(head,anchor)){head=cursorMin(start,head);anchor=cursorMax(anchor,end)}else{anchor=cursorMin(start,anchor);head=cursorMax(head,end);head=offsetCursor(head,0,-1);-1==head.ch&&head.line!=cm.firstLine()&&(head=Pos(head.line-1,lineLength(cm,head.line-1)))}return[anchor,head]}function updateCmSelection(cm,sel,mode){var vim=cm.state.vim;sel=sel||vim.sel;var mode=mode||vim.visualLine?"line":vim.visualBlock?"block":"char",cmSel=makeCmSelection(cm,sel,mode);cm.setSelections(cmSel.ranges,cmSel.primary);updateFakeCursor(cm)}function makeCmSelection(cm,sel,mode,exclusive){var head=copyCursor(sel.head),anchor=copyCursor(sel.anchor);if("char"==mode){var headOffset=exclusive||cursorIsBefore(sel.head,sel.anchor)?0:1,anchorOffset=cursorIsBefore(sel.head,sel.anchor)?1:0;head=offsetCursor(sel.head,0,headOffset);anchor=offsetCursor(sel.anchor,0,anchorOffset);return{ranges:[{anchor:anchor,head:head}],primary:0}}if("line"==mode){if(cursorIsBefore(sel.head,sel.anchor)){head.ch=0;anchor.ch=lineLength(cm,anchor.line)}else{anchor.ch=0;var lastLine=cm.lastLine();head.line>lastLine&&(head.line=lastLine);head.ch=lineLength(cm,head.line)}return{ranges:[{anchor:anchor,head:head}],primary:0}}if("block"==mode){for(var top=Math.min(anchor.line,head.line),left=Math.min(anchor.ch,head.ch),bottom=Math.max(anchor.line,head.line),right=Math.max(anchor.ch,head.ch)+1,height=bottom-top+1,primary=head.line==top?0:height-1,ranges=[],i=0;height>i;i++)ranges.push({anchor:Pos(top+i,left),head:Pos(top+i,right)});return{ranges:ranges,primary:primary}}}function getHead(cm){var cur=cm.getCursor("head");1==cm.getSelection().length&&(cur=cursorMin(cur,cm.getCursor("anchor")));return cur}function exitVisualMode(cm,moveHead){var vim=cm.state.vim;moveHead!==!1&&cm.setCursor(clipCursorToContent(cm,vim.sel.head));updateLastSelection(cm,vim);vim.visualMode=!1;vim.visualLine=!1;vim.visualBlock=!1;CodeMirror.signal(cm,"vim-mode-change",{mode:"normal"});vim.fakeCursor&&vim.fakeCursor.clear()}function clipToLine(cm,curStart,curEnd){var selection=cm.getRange(curStart,curEnd);if(/\n\s*$/.test(selection)){var lines=selection.split("\n");lines.pop();for(var line,line=lines.pop();lines.length>0&&line&&isWhiteSpaceString(line);line=lines.pop()){curEnd.line--;curEnd.ch=0}if(line){curEnd.line--;curEnd.ch=lineLength(cm,curEnd.line)}else curEnd.ch=0}}function expandSelectionToLine(_cm,curStart,curEnd){curStart.ch=0;curEnd.ch=0;curEnd.line++}function findFirstNonWhiteSpaceCharacter(text){if(!text)return 0;var firstNonWS=text.search(/\S/);return-1==firstNonWS?text.length:firstNonWS}function expandWordUnderCursor(cm,inclusive,_forward,bigWord,noSymbol){for(var cur=getHead(cm),line=cm.getLine(cur.line),idx=cur.ch,test=noSymbol?wordCharTest[0]:bigWordCharTest[0];!test(line.charAt(idx));){idx++;if(idx>=line.length)return null}if(bigWord)test=bigWordCharTest[0];else{test=wordCharTest[0];test(line.charAt(idx))||(test=wordCharTest[1])}for(var end=idx,start=idx;test(line.charAt(end))&&end<line.length;)end++;for(;test(line.charAt(start))&&start>=0;)start--;start++;if(inclusive){for(var wordEnd=end;/\s/.test(line.charAt(end))&&end<line.length;)end++;if(wordEnd==end){for(var wordStart=start;/\s/.test(line.charAt(start-1))&&start>0;)start--;start||(start=wordStart)}}return{start:Pos(cur.line,start),end:Pos(cur.line,end)}}function recordJumpPosition(cm,oldCur,newCur){cursorEqual(oldCur,newCur)||vimGlobalState.jumpList.add(cm,oldCur,newCur)}function recordLastCharacterSearch(increment,args){vimGlobalState.lastCharacterSearch.increment=increment;vimGlobalState.lastCharacterSearch.forward=args.forward;vimGlobalState.lastCharacterSearch.selectedCharacter=args.selectedCharacter}function findSymbol(cm,repeat,forward,symb){var cur=copyCursor(cm.getCursor()),increment=forward?1:-1,endLine=forward?cm.lineCount():-1,curCh=cur.ch,line=cur.line,lineText=cm.getLine(line),state={lineText:lineText,nextCh:lineText.charAt(curCh),lastCh:null,index:curCh,symb:symb,reverseSymb:(forward?{")":"(","}":"{"}:{"(":")","{":"}"})[symb],forward:forward,depth:0,curMoveThrough:!1},mode=symbolToMode[symb];if(!mode)return cur;var init=findSymbolModes[mode].init,isComplete=findSymbolModes[mode].isComplete;init&&init(state);for(;line!==endLine&&repeat;){state.index+=increment;state.nextCh=state.lineText.charAt(state.index);if(!state.nextCh){line+=increment;state.lineText=cm.getLine(line)||"";if(increment>0)state.index=0;else{var lineLen=state.lineText.length;state.index=lineLen>0?lineLen-1:0}state.nextCh=state.lineText.charAt(state.index)}if(isComplete(state)){cur.line=line;cur.ch=state.index;repeat--}}return state.nextCh||state.curMoveThrough?Pos(line,state.index):cur}function findWord(cm,cur,forward,bigWord,emptyLineIsWord){var lineNum=cur.line,pos=cur.ch,line=cm.getLine(lineNum),dir=forward?1:-1,charTests=bigWord?bigWordCharTest:wordCharTest;if(emptyLineIsWord&&""==line){lineNum+=dir;line=cm.getLine(lineNum);if(!isLine(cm,lineNum))return null;pos=forward?0:line.length}for(;;){if(emptyLineIsWord&&""==line)return{from:0,to:0,line:lineNum};for(var stop=dir>0?line.length:-1,wordStart=stop,wordEnd=stop;pos!=stop;){for(var foundWord=!1,i=0;i<charTests.length&&!foundWord;++i)if(charTests[i](line.charAt(pos))){wordStart=pos;for(;pos!=stop&&charTests[i](line.charAt(pos));)pos+=dir;wordEnd=pos;foundWord=wordStart!=wordEnd;if(wordStart==cur.ch&&lineNum==cur.line&&wordEnd==wordStart+dir)continue;return{from:Math.min(wordStart,wordEnd+1),to:Math.max(wordStart,wordEnd),line:lineNum}}foundWord||(pos+=dir)}lineNum+=dir;if(!isLine(cm,lineNum))return null;line=cm.getLine(lineNum);pos=dir>0?0:line.length}}function moveToWord(cm,cur,repeat,forward,wordEnd,bigWord){var curStart=copyCursor(cur),words=[];(forward&&!wordEnd||!forward&&wordEnd)&&repeat++;for(var emptyLineIsWord=!(forward&&wordEnd),i=0;repeat>i;i++){var word=findWord(cm,cur,forward,bigWord,emptyLineIsWord);if(!word){var eodCh=lineLength(cm,cm.lastLine());words.push(forward?{line:cm.lastLine(),from:eodCh,to:eodCh}:{line:0,from:0,to:0});break}words.push(word);cur=Pos(word.line,forward?word.to-1:word.from)}var shortCircuit=words.length!=repeat,firstWord=words[0],lastWord=words.pop();if(forward&&!wordEnd){shortCircuit||firstWord.from==curStart.ch&&firstWord.line==curStart.line||(lastWord=words.pop());return Pos(lastWord.line,lastWord.from)}if(forward&&wordEnd)return Pos(lastWord.line,lastWord.to-1);if(!forward&&wordEnd){shortCircuit||firstWord.to==curStart.ch&&firstWord.line==curStart.line||(lastWord=words.pop());return Pos(lastWord.line,lastWord.to)}return Pos(lastWord.line,lastWord.from)}function moveToCharacter(cm,repeat,forward,character){for(var idx,cur=cm.getCursor(),start=cur.ch,i=0;repeat>i;i++){var line=cm.getLine(cur.line);idx=charIdxInLine(start,line,character,forward,!0);if(-1==idx)return null;start=idx}return Pos(cm.getCursor().line,idx)}function moveToColumn(cm,repeat){var line=cm.getCursor().line;return clipCursorToContent(cm,Pos(line,repeat-1));
2
- }function updateMark(cm,vim,markName,pos){if(inArray(markName,validMarks)){vim.marks[markName]&&vim.marks[markName].clear();vim.marks[markName]=cm.setBookmark(pos)}}function charIdxInLine(start,line,character,forward,includeChar){var idx;if(forward){idx=line.indexOf(character,start+1);-1==idx||includeChar||(idx-=1)}else{idx=line.lastIndexOf(character,start-1);-1==idx||includeChar||(idx+=1)}return idx}function findParagraph(cm,head,repeat,dir,inclusive){function isEmpty(i){return!cm.getLine(i)}function isBoundary(i,dir,any){return any?isEmpty(i)!=isEmpty(i+dir):!isEmpty(i)&&isEmpty(i+dir)}var start,end,line=head.line,min=cm.firstLine(),max=cm.lastLine(),i=line;if(dir){for(;i>=min&&max>=i&&repeat>0;){isBoundary(i,dir)&&repeat--;i+=dir}return new Pos(i,0)}var vim=cm.state.vim;if(vim.visualLine&&isBoundary(line,1,!0)){var anchor=vim.sel.anchor;isBoundary(anchor.line,-1,!0)&&(inclusive&&anchor.line==line||(line+=1))}var startState=isEmpty(line);for(i=line;max>=i&&repeat;i++)isBoundary(i,1,!0)&&(inclusive&&isEmpty(i)==startState||repeat--);end=new Pos(i,0);i>max&&!startState?startState=!0:inclusive=!1;for(i=line;i>min&&(inclusive&&isEmpty(i)!=startState&&i!=line||!isBoundary(i,-1,!0));i--);start=new Pos(i,0);return{start:start,end:end}}function selectCompanionObject(cm,head,symb,inclusive){var start,end,cur=head,bracketRegexp={"(":/[()]/,")":/[()]/,"[":/[[\]]/,"]":/[[\]]/,"{":/[{}]/,"}":/[{}]/}[symb],openSym={"(":"(",")":"(","[":"[","]":"[","{":"{","}":"{"}[symb],curChar=cm.getLine(cur.line).charAt(cur.ch),offset=curChar===openSym?1:0;start=cm.scanForBracket(Pos(cur.line,cur.ch+offset),-1,null,{bracketRegex:bracketRegexp});end=cm.scanForBracket(Pos(cur.line,cur.ch+offset),1,null,{bracketRegex:bracketRegexp});if(!start||!end)return{start:cur,end:cur};start=start.pos;end=end.pos;if(start.line==end.line&&start.ch>end.ch||start.line>end.line){var tmp=start;start=end;end=tmp}inclusive?end.ch+=1:start.ch+=1;return{start:start,end:end}}function findBeginningAndEnd(cm,head,symb,inclusive){var start,end,i,len,cur=copyCursor(head),line=cm.getLine(cur.line),chars=line.split(""),firstIndex=chars.indexOf(symb);if(cur.ch<firstIndex)cur.ch=firstIndex;else if(firstIndex<cur.ch&&chars[cur.ch]==symb){end=cur.ch;--cur.ch}if(chars[cur.ch]!=symb||end)for(i=cur.ch;i>-1&&!start;i--)chars[i]==symb&&(start=i+1);else start=cur.ch+1;if(start&&!end)for(i=start,len=chars.length;len>i&&!end;i++)chars[i]==symb&&(end=i);if(!start||!end)return{start:cur,end:cur};if(inclusive){--start;++end}return{start:Pos(cur.line,start),end:Pos(cur.line,end)}}function SearchState(){}function getSearchState(cm){var vim=cm.state.vim;return vim.searchState_||(vim.searchState_=new SearchState)}function dialog(cm,template,shortText,onClose,options){cm.openDialog?cm.openDialog(template,onClose,{bottom:!0,value:options.value,onKeyDown:options.onKeyDown,onKeyUp:options.onKeyUp,selectValueOnOpen:!1}):onClose(prompt(shortText,""))}function splitBySlash(argString){var slashes=findUnescapedSlashes(argString)||[];if(!slashes.length)return[];var tokens=[];if(0===slashes[0]){for(var i=0;i<slashes.length;i++)"number"==typeof slashes[i]&&tokens.push(argString.substring(slashes[i]+1,slashes[i+1]));return tokens}}function findUnescapedSlashes(str){for(var escapeNextChar=!1,slashes=[],i=0;i<str.length;i++){var c=str.charAt(i);escapeNextChar||"/"!=c||slashes.push(i);escapeNextChar=!escapeNextChar&&"\\"==c}return slashes}function translateRegex(str){for(var specials="|(){",unescape="}",escapeNextChar=!1,out=[],i=-1;i<str.length;i++){var c=str.charAt(i)||"",n=str.charAt(i+1)||"",specialComesNext=n&&-1!=specials.indexOf(n);if(escapeNextChar){"\\"===c&&specialComesNext||out.push(c);escapeNextChar=!1}else if("\\"===c){escapeNextChar=!0;n&&-1!=unescape.indexOf(n)&&(specialComesNext=!0);specialComesNext&&"\\"!==n||out.push(c)}else{out.push(c);specialComesNext&&"\\"!==n&&out.push("\\")}}return out.join("")}function translateRegexReplace(str){for(var escapeNextChar=!1,out=[],i=-1;i<str.length;i++){var c=str.charAt(i)||"",n=str.charAt(i+1)||"";if(charUnescapes[c+n]){out.push(charUnescapes[c+n]);i++}else if(escapeNextChar){out.push(c);escapeNextChar=!1}else if("\\"===c){escapeNextChar=!0;isNumber(n)||"$"===n?out.push("$"):"/"!==n&&"\\"!==n&&out.push("\\")}else{"$"===c&&out.push("$");out.push(c);"/"===n&&out.push("\\")}}return out.join("")}function unescapeRegexReplace(str){for(var stream=new CodeMirror.StringStream(str),output=[];!stream.eol();){for(;stream.peek()&&"\\"!=stream.peek();)output.push(stream.next());var matched=!1;for(var matcher in unescapes)if(stream.match(matcher,!0)){matched=!0;output.push(unescapes[matcher]);break}matched||output.push(stream.next())}return output.join("")}function parseQuery(query,ignoreCase,smartCase){var lastSearchRegister=vimGlobalState.registerController.getRegister("/");lastSearchRegister.setText(query);if(query instanceof RegExp)return query;var regexPart,forceIgnoreCase,slashes=findUnescapedSlashes(query);if(slashes.length){regexPart=query.substring(0,slashes[0]);var flagsPart=query.substring(slashes[0]);forceIgnoreCase=-1!=flagsPart.indexOf("i")}else regexPart=query;if(!regexPart)return null;getOption("pcre")||(regexPart=translateRegex(regexPart));smartCase&&(ignoreCase=/^[^A-Z]*$/.test(regexPart));var regexp=new RegExp(regexPart,ignoreCase||forceIgnoreCase?"i":void 0);return regexp}function showConfirm(cm,text){cm.openNotification?cm.openNotification('<span style="color: red">'+text+"</span>",{bottom:!0,duration:5e3}):alert(text)}function makePrompt(prefix,desc){var raw="";prefix&&(raw+='<span style="font-family: monospace">'+prefix+"</span>");raw+='<input type="text"/> <span style="color: #888">';if(desc){raw+='<span style="color: #888">';raw+=desc;raw+="</span>"}return raw}function showPrompt(cm,options){var shortText=(options.prefix||"")+" "+(options.desc||""),prompt=makePrompt(options.prefix,options.desc);dialog(cm,prompt,shortText,options.onClose,options)}function regexEqual(r1,r2){if(r1 instanceof RegExp&&r2 instanceof RegExp){for(var props=["global","multiline","ignoreCase","source"],i=0;i<props.length;i++){var prop=props[i];if(r1[prop]!==r2[prop])return!1}return!0}return!1}function updateSearchQuery(cm,rawQuery,ignoreCase,smartCase){if(rawQuery){var state=getSearchState(cm),query=parseQuery(rawQuery,!!ignoreCase,!!smartCase);if(query){highlightSearchMatches(cm,query);if(regexEqual(query,state.getQuery()))return query;state.setQuery(query);return query}}}function searchOverlay(query){if("^"==query.source.charAt(0))var matchSol=!0;return{token:function(stream){if(!matchSol||stream.sol()){var match=stream.match(query,!1);if(match){if(0==match[0].length){stream.next();return"searching"}if(!stream.sol()){stream.backUp(1);if(!query.exec(stream.next()+match[0])){stream.next();return null}}stream.match(query);return"searching"}for(;!stream.eol();){stream.next();if(stream.match(query,!1))break}}else stream.skipToEnd()},query:query}}function highlightSearchMatches(cm,query){var searchState=getSearchState(cm),overlay=searchState.getOverlay();if(!overlay||query!=overlay.query){overlay&&cm.removeOverlay(overlay);overlay=searchOverlay(query);cm.addOverlay(overlay);if(cm.showMatchesOnScrollbar){searchState.getScrollbarAnnotate()&&searchState.getScrollbarAnnotate().clear();searchState.setScrollbarAnnotate(cm.showMatchesOnScrollbar(query))}searchState.setOverlay(overlay)}}function findNext(cm,prev,query,repeat){void 0===repeat&&(repeat=1);return cm.operation(function(){for(var pos=cm.getCursor(),cursor=cm.getSearchCursor(query,pos),i=0;repeat>i;i++){var found=cursor.find(prev);0==i&&found&&cursorEqual(cursor.from(),pos)&&(found=cursor.find(prev));if(!found){cursor=cm.getSearchCursor(query,prev?Pos(cm.lastLine()):Pos(cm.firstLine(),0));if(!cursor.find(prev))return}}return cursor.from()})}function clearSearchHighlight(cm){var state=getSearchState(cm);cm.removeOverlay(getSearchState(cm).getOverlay());state.setOverlay(null);if(state.getScrollbarAnnotate()){state.getScrollbarAnnotate().clear();state.setScrollbarAnnotate(null)}}function isInRange(pos,start,end){"number"!=typeof pos&&(pos=pos.line);return start instanceof Array?inArray(pos,start):end?pos>=start&&end>=pos:pos==start}function getUserVisibleLines(cm){var scrollInfo=cm.getScrollInfo(),occludeToleranceTop=6,occludeToleranceBottom=10,from=cm.coordsChar({left:0,top:occludeToleranceTop+scrollInfo.top},"local"),bottomY=scrollInfo.clientHeight-occludeToleranceBottom+scrollInfo.top,to=cm.coordsChar({left:0,top:bottomY},"local");return{top:from.line,bottom:to.line}}function doReplace(cm,confirm,global,lineStart,lineEnd,searchCursor,query,replaceWith,callback){function replaceAll(){cm.operation(function(){for(;!done;){replace();next()}stop()})}function replace(){var text=cm.getRange(searchCursor.from(),searchCursor.to()),newText=text.replace(query,replaceWith);searchCursor.replace(newText)}function next(){for(;searchCursor.findNext()&&isInRange(searchCursor.from(),lineStart,lineEnd);)if(global||!lastPos||searchCursor.from().line!=lastPos.line){cm.scrollIntoView(searchCursor.from(),30);cm.setSelection(searchCursor.from(),searchCursor.to());lastPos=searchCursor.from();done=!1;return}done=!0}function stop(close){close&&close();cm.focus();if(lastPos){cm.setCursor(lastPos);var vim=cm.state.vim;vim.exMode=!1;vim.lastHPos=vim.lastHSPos=lastPos.ch}callback&&callback()}function onPromptKeyDown(e,_value,close){CodeMirror.e_stop(e);var keyName=CodeMirror.keyName(e);switch(keyName){case"Y":replace();next();break;case"N":next();break;case"A":var savedCallback=callback;callback=void 0;cm.operation(replaceAll);callback=savedCallback;break;case"L":replace();case"Q":case"Esc":case"Ctrl-C":case"Ctrl-[":stop(close)}done&&stop(close);return!0}cm.state.vim.exMode=!0;var done=!1,lastPos=searchCursor.from();next();if(done)showConfirm(cm,"No matches for "+query.source);else if(confirm)showPrompt(cm,{prefix:"replace with <strong>"+replaceWith+"</strong> (y/n/a/q/l)",onKeyDown:onPromptKeyDown});else{replaceAll();callback&&callback()}}function exitInsertMode(cm){var vim=cm.state.vim,macroModeState=vimGlobalState.macroModeState,insertModeChangeRegister=vimGlobalState.registerController.getRegister("."),isPlaying=macroModeState.isPlaying,lastChange=macroModeState.lastInsertModeChanges,text=[];if(!isPlaying){for(var selLength=lastChange.inVisualBlock?vim.lastSelection.visualBlock.height:1,changes=lastChange.changes,text=[],i=0;i<changes.length;){text.push(changes[i]);changes[i]instanceof InsertModeKey?i++:i+=selLength}lastChange.changes=text;cm.off("change",onChange);CodeMirror.off(cm.getInputField(),"keydown",onKeyEventTargetKeyDown)}if(!isPlaying&&vim.insertModeRepeat>1){repeatLastEdit(cm,vim,vim.insertModeRepeat-1,!0);vim.lastEditInputState.repeatOverride=vim.insertModeRepeat}delete vim.insertModeRepeat;vim.insertMode=!1;cm.setCursor(cm.getCursor().line,cm.getCursor().ch-1);cm.setOption("keyMap","vim");cm.setOption("disableInput",!0);cm.toggleOverwrite(!1);insertModeChangeRegister.setText(lastChange.changes.join(""));CodeMirror.signal(cm,"vim-mode-change",{mode:"normal"});macroModeState.isRecording&&logInsertModeChange(macroModeState)}function _mapCommand(command){defaultKeymap.unshift(command)}function mapCommand(keys,type,name,args,extra){var command={keys:keys,type:type};command[type]=name;command[type+"Args"]=args;for(var key in extra)command[key]=extra[key];_mapCommand(command)}function executeMacroRegister(cm,vim,macroModeState,registerName){var register=vimGlobalState.registerController.getRegister(registerName);if(":"!=registerName){var keyBuffer=register.keyBuffer,imc=0;macroModeState.isPlaying=!0;macroModeState.replaySearchQueries=register.searchQueries.slice(0);for(var i=0;i<keyBuffer.length;i++)for(var match,key,text=keyBuffer[i];text;){match=/<\w+-.+?>|<\w+>|./.exec(text);key=match[0];text=text.substring(match.index+key.length);CodeMirror.Vim.handleKey(cm,key,"macro");if(vim.insertMode){var changes=register.insertModeChanges[imc++].changes;vimGlobalState.macroModeState.lastInsertModeChanges.changes=changes;repeatInsertModeChanges(cm,changes,1);exitInsertMode(cm)}}macroModeState.isPlaying=!1}else{register.keyBuffer[0]&&exCommandDispatcher.processCommand(cm,register.keyBuffer[0]);macroModeState.isPlaying=!1}}function logKey(macroModeState,key){if(!macroModeState.isPlaying){var registerName=macroModeState.latestRegister,register=vimGlobalState.registerController.getRegister(registerName);register&&register.pushText(key)}}function logInsertModeChange(macroModeState){if(!macroModeState.isPlaying){var registerName=macroModeState.latestRegister,register=vimGlobalState.registerController.getRegister(registerName);register&&register.pushInsertModeChanges&&register.pushInsertModeChanges(macroModeState.lastInsertModeChanges)}}function logSearchQuery(macroModeState,query){if(!macroModeState.isPlaying){var registerName=macroModeState.latestRegister,register=vimGlobalState.registerController.getRegister(registerName);register&&register.pushSearchQuery&&register.pushSearchQuery(query)}}function onChange(_cm,changeObj){var macroModeState=vimGlobalState.macroModeState,lastChange=macroModeState.lastInsertModeChanges;if(!macroModeState.isPlaying)for(;changeObj;){lastChange.expectCursorActivityForChange=!0;if("+input"==changeObj.origin||"paste"==changeObj.origin||void 0===changeObj.origin){var text=changeObj.text.join("\n");lastChange.changes.push(text)}changeObj=changeObj.next}}function onCursorActivity(cm){var vim=cm.state.vim;if(vim.insertMode){var macroModeState=vimGlobalState.macroModeState;if(macroModeState.isPlaying)return;var lastChange=macroModeState.lastInsertModeChanges;lastChange.expectCursorActivityForChange?lastChange.expectCursorActivityForChange=!1:lastChange.changes=[]}else cm.curOp.isVimOp||handleExternalSelection(cm,vim);vim.visualMode&&updateFakeCursor(cm)}function updateFakeCursor(cm){var vim=cm.state.vim,from=clipCursorToContent(cm,copyCursor(vim.sel.head)),to=offsetCursor(from,0,1);vim.fakeCursor&&vim.fakeCursor.clear();vim.fakeCursor=cm.markText(from,to,{className:"cm-animate-fat-cursor"})}function handleExternalSelection(cm,vim){var anchor=cm.getCursor("anchor"),head=cm.getCursor("head");if(vim.visualMode&&!cm.somethingSelected())exitVisualMode(cm,!1);else if(!vim.visualMode&&!vim.insertMode&&cm.somethingSelected()){vim.visualMode=!0;vim.visualLine=!1;CodeMirror.signal(cm,"vim-mode-change",{mode:"visual"})}if(vim.visualMode){var headOffset=cursorIsBefore(head,anchor)?0:-1,anchorOffset=cursorIsBefore(head,anchor)?-1:0;head=offsetCursor(head,0,headOffset);anchor=offsetCursor(anchor,0,anchorOffset);vim.sel={anchor:anchor,head:head};updateMark(cm,vim,"<",cursorMin(head,anchor));updateMark(cm,vim,">",cursorMax(head,anchor))}else vim.insertMode||(vim.lastHPos=cm.getCursor().ch)}function InsertModeKey(keyName){this.keyName=keyName}function onKeyEventTargetKeyDown(e){function onKeyFound(){lastChange.changes.push(new InsertModeKey(keyName));return!0}var macroModeState=vimGlobalState.macroModeState,lastChange=macroModeState.lastInsertModeChanges,keyName=CodeMirror.keyName(e);keyName&&(-1!=keyName.indexOf("Delete")||-1!=keyName.indexOf("Backspace"))&&CodeMirror.lookupKey(keyName,"vim-insert",onKeyFound)}function repeatLastEdit(cm,vim,repeat,repeatForInsert){function repeatCommand(){isAction?commandDispatcher.processAction(cm,vim,vim.lastEditActionCommand):commandDispatcher.evalInput(cm,vim)}function repeatInsert(repeat){if(macroModeState.lastInsertModeChanges.changes.length>0){repeat=vim.lastEditActionCommand?repeat:1;var changeObject=macroModeState.lastInsertModeChanges;repeatInsertModeChanges(cm,changeObject.changes,repeat)}}var macroModeState=vimGlobalState.macroModeState;macroModeState.isPlaying=!0;var isAction=!!vim.lastEditActionCommand,cachedInputState=vim.inputState;vim.inputState=vim.lastEditInputState;if(isAction&&vim.lastEditActionCommand.interlaceInsertRepeat)for(var i=0;repeat>i;i++){repeatCommand();repeatInsert(1)}else{repeatForInsert||repeatCommand();repeatInsert(repeat)}vim.inputState=cachedInputState;vim.insertMode&&!repeatForInsert&&exitInsertMode(cm);macroModeState.isPlaying=!1}function repeatInsertModeChanges(cm,changes,repeat){function keyHandler(binding){"string"==typeof binding?CodeMirror.commands[binding](cm):binding(cm);return!0}var head=cm.getCursor("head"),inVisualBlock=vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock;if(inVisualBlock){var vim=cm.state.vim,lastSel=vim.lastSelection,offset=getOffset(lastSel.anchor,lastSel.head);selectForInsert(cm,head,offset.line+1);repeat=cm.listSelections().length;cm.setCursor(head)}for(var i=0;repeat>i;i++){inVisualBlock&&cm.setCursor(offsetCursor(head,i,0));for(var j=0;j<changes.length;j++){var change=changes[j];if(change instanceof InsertModeKey)CodeMirror.lookupKey(change.keyName,"vim-insert",keyHandler);else{var cur=cm.getCursor();cm.replaceRange(change,cur,cur)}}}inVisualBlock&&cm.setCursor(offsetCursor(head,0,1))}CodeMirror.defineOption("vimMode",!1,function(cm,val,prev){val&&"vim"!=cm.getOption("keyMap")?cm.setOption("keyMap","vim"):!val&&prev!=CodeMirror.Init&&/^vim/.test(cm.getOption("keyMap"))&&cm.setOption("keyMap","default")});var modifiers={Shift:"S",Ctrl:"C",Alt:"A",Cmd:"D",Mod:"A"},specialKeys={Enter:"CR",Backspace:"BS",Delete:"Del"},numberRegex=/[\d]/,wordCharTest=[CodeMirror.isWordChar,function(ch){return ch&&!CodeMirror.isWordChar(ch)&&!/\s/.test(ch)}],bigWordCharTest=[function(ch){return/\S/.test(ch)}],upperCaseAlphabet=makeKeyRange(65,26),lowerCaseAlphabet=makeKeyRange(97,26),numbers=makeKeyRange(48,10),validMarks=[].concat(upperCaseAlphabet,lowerCaseAlphabet,numbers,["<",">"]),validRegisters=[].concat(upperCaseAlphabet,lowerCaseAlphabet,numbers,["-",'"',".",":","/"]),options={};defineOption("filetype",void 0,"string",["ft"],function(name,cm){if(void 0!==cm){if(void 0===name){var mode=cm.getOption("mode");return"null"==mode?"":mode}var mode=""==name?"null":name;cm.setOption("mode",mode)}});var createCircularJumpList=function(){function add(cm,oldCur,newCur){function useNextSlot(cursor){var next=++pointer%size,trashMark=buffer[next];trashMark&&trashMark.clear();buffer[next]=cm.setBookmark(cursor)}var current=pointer%size,curMark=buffer[current];if(curMark){var markPos=curMark.find();markPos&&!cursorEqual(markPos,oldCur)&&useNextSlot(oldCur)}else useNextSlot(oldCur);useNextSlot(newCur);head=pointer;tail=pointer-size+1;0>tail&&(tail=0)}function move(cm,offset){pointer+=offset;pointer>head?pointer=head:tail>pointer&&(pointer=tail);var mark=buffer[(size+pointer)%size];if(mark&&!mark.find()){var newCur,inc=offset>0?1:-1,oldCur=cm.getCursor();do{pointer+=inc;mark=buffer[(size+pointer)%size];if(mark&&(newCur=mark.find())&&!cursorEqual(oldCur,newCur))break}while(head>pointer&&pointer>tail)}return mark}var size=100,pointer=-1,head=0,tail=0,buffer=new Array(size);return{cachedCursor:void 0,add:add,move:move}},createInsertModeChanges=function(c){return c?{changes:c.changes,expectCursorActivityForChange:c.expectCursorActivityForChange}:{changes:[],expectCursorActivityForChange:!1}};MacroModeState.prototype={exitMacroRecordMode:function(){var macroModeState=vimGlobalState.macroModeState;macroModeState.onRecordingDone&&macroModeState.onRecordingDone();macroModeState.onRecordingDone=void 0;macroModeState.isRecording=!1},enterMacroRecordMode:function(cm,registerName){var register=vimGlobalState.registerController.getRegister(registerName);if(register){register.clear();this.latestRegister=registerName;cm.openDialog&&(this.onRecordingDone=cm.openDialog("(recording)["+registerName+"]",null,{bottom:!0}));this.isRecording=!0}}};var vimGlobalState,lastInsertModeKeyTimer,vimApi={buildKeyMap:function(){},getRegisterController:function(){return vimGlobalState.registerController},resetVimGlobalState_:resetVimGlobalState,getVimGlobalState_:function(){return vimGlobalState},maybeInitVimState_:maybeInitVimState,suppressErrorLogging:!1,InsertModeKey:InsertModeKey,map:function(lhs,rhs,ctx){exCommandDispatcher.map(lhs,rhs,ctx)},unmap:function(lhs,ctx){exCommandDispatcher.unmap(lhs,ctx)},setOption:setOption,getOption:getOption,defineOption:defineOption,defineEx:function(name,prefix,func){if(prefix){if(0!==name.indexOf(prefix))throw new Error('(Vim.defineEx) "'+prefix+'" is not a prefix of "'+name+'", command not registered')}else prefix=name;exCommands[name]=func;exCommandDispatcher.commandMap_[prefix]={name:name,shortName:prefix,type:"api"}},handleKey:function(cm,key,origin){var command=this.findKey(cm,key,origin);return"function"==typeof command?command():void 0},findKey:function(cm,key,origin){function handleMacroRecording(){var macroModeState=vimGlobalState.macroModeState;if(macroModeState.isRecording){if("q"==key){macroModeState.exitMacroRecordMode();clearInputState(cm);return!0}"mapping"!=origin&&logKey(macroModeState,key)}}function handleEsc(){if("<Esc>"==key){clearInputState(cm);vim.visualMode?exitVisualMode(cm):vim.insertMode&&exitInsertMode(cm);return!0}}function doKeyToKey(keys){for(var match;keys;){match=/<\w+-.+?>|<\w+>|./.exec(keys);key=match[0];keys=keys.substring(match.index+key.length);CodeMirror.Vim.handleKey(cm,key,"mapping")}}function handleKeyInsertMode(){if(handleEsc())return!0;for(var keys=vim.inputState.keyBuffer=vim.inputState.keyBuffer+key,keysAreChars=1==key.length,match=commandDispatcher.matchCommand(keys,defaultKeymap,vim.inputState,"insert");keys.length>1&&"full"!=match.type;){var keys=vim.inputState.keyBuffer=keys.slice(1),thisMatch=commandDispatcher.matchCommand(keys,defaultKeymap,vim.inputState,"insert");"none"!=thisMatch.type&&(match=thisMatch)}if("none"==match.type){clearInputState(cm);return!1}if("partial"==match.type){lastInsertModeKeyTimer&&window.clearTimeout(lastInsertModeKeyTimer);lastInsertModeKeyTimer=window.setTimeout(function(){vim.insertMode&&vim.inputState.keyBuffer&&clearInputState(cm)},getOption("insertModeEscKeysTimeout"));return!keysAreChars}lastInsertModeKeyTimer&&window.clearTimeout(lastInsertModeKeyTimer);if(keysAreChars){var here=cm.getCursor();cm.replaceRange("",offsetCursor(here,0,-(keys.length-1)),here,"+input")}clearInputState(cm);return match.command}function handleKeyNonInsertMode(){if(handleMacroRecording()||handleEsc())return!0;var keys=vim.inputState.keyBuffer=vim.inputState.keyBuffer+key;if(/^[1-9]\d*$/.test(keys))return!0;var keysMatcher=/^(\d*)(.*)$/.exec(keys);if(!keysMatcher){clearInputState(cm);return!1}var context=vim.visualMode?"visual":"normal",match=commandDispatcher.matchCommand(keysMatcher[2]||keysMatcher[1],defaultKeymap,vim.inputState,context);if("none"==match.type){clearInputState(cm);return!1}if("partial"==match.type)return!0;vim.inputState.keyBuffer="";var keysMatcher=/^(\d*)(.*)$/.exec(keys);keysMatcher[1]&&"0"!=keysMatcher[1]&&vim.inputState.pushRepeatDigit(keysMatcher[1]);return match.command}var command,vim=maybeInitVimState(cm);command=vim.insertMode?handleKeyInsertMode():handleKeyNonInsertMode();return command===!1?void 0:command===!0?function(){}:function(){return cm.operation(function(){cm.curOp.isVimOp=!0;try{"keyToKey"==command.type?doKeyToKey(command.toKeys):commandDispatcher.processCommand(cm,vim,command)}catch(e){cm.state.vim=void 0;maybeInitVimState(cm);CodeMirror.Vim.suppressErrorLogging||console.log(e);throw e}return!0})}},handleEx:function(cm,input){exCommandDispatcher.processCommand(cm,input)},defineMotion:defineMotion,defineAction:defineAction,defineOperator:defineOperator,mapCommand:mapCommand,_mapCommand:_mapCommand,defineRegister:defineRegister,exitVisualMode:exitVisualMode,exitInsertMode:exitInsertMode};InputState.prototype.pushRepeatDigit=function(n){this.operator?this.motionRepeat=this.motionRepeat.concat(n):this.prefixRepeat=this.prefixRepeat.concat(n)};InputState.prototype.getRepeat=function(){var repeat=0;if(this.prefixRepeat.length>0||this.motionRepeat.length>0){repeat=1;this.prefixRepeat.length>0&&(repeat*=parseInt(this.prefixRepeat.join(""),10));this.motionRepeat.length>0&&(repeat*=parseInt(this.motionRepeat.join(""),10))}return repeat};Register.prototype={setText:function(text,linewise,blockwise){this.keyBuffer=[text||""];this.linewise=!!linewise;this.blockwise=!!blockwise},pushText:function(text,linewise){if(linewise){this.linewise||this.keyBuffer.push("\n");this.linewise=!0}this.keyBuffer.push(text)},pushInsertModeChanges:function(changes){this.insertModeChanges.push(createInsertModeChanges(changes))},pushSearchQuery:function(query){this.searchQueries.push(query)},clear:function(){this.keyBuffer=[];this.insertModeChanges=[];this.searchQueries=[];this.linewise=!1},toString:function(){return this.keyBuffer.join("")}};RegisterController.prototype={pushText:function(registerName,operator,text,linewise,blockwise){linewise&&"\n"==text.charAt(0)&&(text=text.slice(1)+"\n");linewise&&"\n"!==text.charAt(text.length-1)&&(text+="\n");var register=this.isValidRegister(registerName)?this.getRegister(registerName):null;if(register){var append=isUpperCase(registerName);append?register.pushText(text,linewise):register.setText(text,linewise,blockwise);this.unnamedRegister.setText(register.toString(),linewise)}else{switch(operator){case"yank":this.registers[0]=new Register(text,linewise,blockwise);break;case"delete":case"change":if(-1==text.indexOf("\n"))this.registers["-"]=new Register(text,linewise);else{this.shiftNumericRegisters_();this.registers[1]=new Register(text,linewise)}}this.unnamedRegister.setText(text,linewise,blockwise)}},getRegister:function(name){if(!this.isValidRegister(name))return this.unnamedRegister;name=name.toLowerCase();this.registers[name]||(this.registers[name]=new Register);return this.registers[name]},isValidRegister:function(name){return name&&inArray(name,validRegisters)},shiftNumericRegisters_:function(){for(var i=9;i>=2;i--)this.registers[i]=this.getRegister(""+(i-1))}};HistoryController.prototype={nextMatch:function(input,up){var historyBuffer=this.historyBuffer,dir=up?-1:1;null===this.initialPrefix&&(this.initialPrefix=input);for(var i=this.iterator+dir;up?i>=0:i<historyBuffer.length;i+=dir)for(var element=historyBuffer[i],j=0;j<=element.length;j++)if(this.initialPrefix==element.substring(0,j)){this.iterator=i;return element}if(i>=historyBuffer.length){this.iterator=historyBuffer.length;return this.initialPrefix}return 0>i?input:void 0},pushInput:function(input){var index=this.historyBuffer.indexOf(input);index>-1&&this.historyBuffer.splice(index,1);input.length&&this.historyBuffer.push(input)},reset:function(){this.initialPrefix=null;this.iterator=this.historyBuffer.length}};var commandDispatcher={matchCommand:function(keys,keyMap,inputState,context){var matches=commandMatches(keys,keyMap,context,inputState);if(!matches.full&&!matches.partial)return{type:"none"};if(!matches.full&&matches.partial)return{type:"partial"};for(var bestMatch,i=0;i<matches.full.length;i++){var match=matches.full[i];bestMatch||(bestMatch=match)}"<character>"==bestMatch.keys.slice(-11)&&(inputState.selectedCharacter=lastChar(keys));return{type:"full",command:bestMatch}},processCommand:function(cm,vim,command){vim.inputState.repeatOverride=command.repeatOverride;switch(command.type){case"motion":this.processMotion(cm,vim,command);break;case"operator":this.processOperator(cm,vim,command);break;case"operatorMotion":this.processOperatorMotion(cm,vim,command);break;case"action":this.processAction(cm,vim,command);break;case"search":this.processSearch(cm,vim,command);break;case"ex":case"keyToEx":this.processEx(cm,vim,command)}},processMotion:function(cm,vim,command){vim.inputState.motion=command.motion;vim.inputState.motionArgs=copyArgs(command.motionArgs);this.evalInput(cm,vim)},processOperator:function(cm,vim,command){var inputState=vim.inputState;if(inputState.operator){if(inputState.operator==command.operator){inputState.motion="expandToLine";inputState.motionArgs={linewise:!0};this.evalInput(cm,vim);return}clearInputState(cm)}inputState.operator=command.operator;inputState.operatorArgs=copyArgs(command.operatorArgs);vim.visualMode&&this.evalInput(cm,vim)},processOperatorMotion:function(cm,vim,command){var visualMode=vim.visualMode,operatorMotionArgs=copyArgs(command.operatorMotionArgs);operatorMotionArgs&&visualMode&&operatorMotionArgs.visualLine&&(vim.visualLine=!0);this.processOperator(cm,vim,command);visualMode||this.processMotion(cm,vim,command)},processAction:function(cm,vim,command){var inputState=vim.inputState,repeat=inputState.getRepeat(),repeatIsExplicit=!!repeat,actionArgs=copyArgs(command.actionArgs)||{};inputState.selectedCharacter&&(actionArgs.selectedCharacter=inputState.selectedCharacter);command.operator&&this.processOperator(cm,vim,command);command.motion&&this.processMotion(cm,vim,command);(command.motion||command.operator)&&this.evalInput(cm,vim);actionArgs.repeat=repeat||1;actionArgs.repeatIsExplicit=repeatIsExplicit;actionArgs.registerName=inputState.registerName;clearInputState(cm);vim.lastMotion=null;command.isEdit&&this.recordLastEdit(vim,inputState,command);actions[command.action](cm,actionArgs,vim)},processSearch:function(cm,vim,command){function handleQuery(query,ignoreCase,smartCase){vimGlobalState.searchHistoryController.pushInput(query);vimGlobalState.searchHistoryController.reset();try{updateSearchQuery(cm,query,ignoreCase,smartCase)}catch(e){showConfirm(cm,"Invalid regex: "+query);clearInputState(cm);return}commandDispatcher.processMotion(cm,vim,{type:"motion",motion:"findNext",motionArgs:{forward:!0,toJumplist:command.searchArgs.toJumplist}})}function onPromptClose(query){cm.scrollTo(originalScrollPos.left,originalScrollPos.top);handleQuery(query,!0,!0);var macroModeState=vimGlobalState.macroModeState;macroModeState.isRecording&&logSearchQuery(macroModeState,query)}function onPromptKeyUp(e,query,close){var up,keyName=CodeMirror.keyName(e);if("Up"==keyName||"Down"==keyName){up="Up"==keyName?!0:!1;query=vimGlobalState.searchHistoryController.nextMatch(query,up)||"";close(query)}else"Left"!=keyName&&"Right"!=keyName&&"Ctrl"!=keyName&&"Alt"!=keyName&&"Shift"!=keyName&&vimGlobalState.searchHistoryController.reset();var parsedQuery;try{parsedQuery=updateSearchQuery(cm,query,!0,!0)}catch(e){}if(parsedQuery)cm.scrollIntoView(findNext(cm,!forward,parsedQuery),30);else{clearSearchHighlight(cm);cm.scrollTo(originalScrollPos.left,originalScrollPos.top)}}function onPromptKeyDown(e,query,close){var keyName=CodeMirror.keyName(e);if("Esc"==keyName||"Ctrl-C"==keyName||"Ctrl-["==keyName||"Backspace"==keyName&&""==query){vimGlobalState.searchHistoryController.pushInput(query);vimGlobalState.searchHistoryController.reset();updateSearchQuery(cm,originalQuery);clearSearchHighlight(cm);cm.scrollTo(originalScrollPos.left,originalScrollPos.top);CodeMirror.e_stop(e);clearInputState(cm);close();cm.focus()}else if("Ctrl-U"==keyName){CodeMirror.e_stop(e);close("")}}if(cm.getSearchCursor){var forward=command.searchArgs.forward,wholeWordOnly=command.searchArgs.wholeWordOnly;getSearchState(cm).setReversed(!forward);var promptPrefix=forward?"/":"?",originalQuery=getSearchState(cm).getQuery(),originalScrollPos=cm.getScrollInfo();switch(command.searchArgs.querySrc){case"prompt":var macroModeState=vimGlobalState.macroModeState;if(macroModeState.isPlaying){var query=macroModeState.replaySearchQueries.shift();handleQuery(query,!0,!1)}else showPrompt(cm,{onClose:onPromptClose,prefix:promptPrefix,desc:searchPromptDesc,onKeyUp:onPromptKeyUp,onKeyDown:onPromptKeyDown});break;case"wordUnderCursor":var word=expandWordUnderCursor(cm,!1,!0,!1,!0),isKeyword=!0;if(!word){word=expandWordUnderCursor(cm,!1,!0,!1,!1);isKeyword=!1}if(!word)return;var query=cm.getLine(word.start.line).substring(word.start.ch,word.end.ch);query=isKeyword&&wholeWordOnly?"\\b"+query+"\\b":escapeRegex(query);vimGlobalState.jumpList.cachedCursor=cm.getCursor();cm.setCursor(word.start);handleQuery(query,!0,!1)}}},processEx:function(cm,vim,command){function onPromptClose(input){vimGlobalState.exCommandHistoryController.pushInput(input);vimGlobalState.exCommandHistoryController.reset();exCommandDispatcher.processCommand(cm,input)}function onPromptKeyDown(e,input,close){var up,keyName=CodeMirror.keyName(e);
3
- if("Esc"==keyName||"Ctrl-C"==keyName||"Ctrl-["==keyName||"Backspace"==keyName&&""==input){vimGlobalState.exCommandHistoryController.pushInput(input);vimGlobalState.exCommandHistoryController.reset();CodeMirror.e_stop(e);clearInputState(cm);close();cm.focus()}if("Up"==keyName||"Down"==keyName){up="Up"==keyName?!0:!1;input=vimGlobalState.exCommandHistoryController.nextMatch(input,up)||"";close(input)}else if("Ctrl-U"==keyName){CodeMirror.e_stop(e);close("")}else"Left"!=keyName&&"Right"!=keyName&&"Ctrl"!=keyName&&"Alt"!=keyName&&"Shift"!=keyName&&vimGlobalState.exCommandHistoryController.reset()}"keyToEx"==command.type?exCommandDispatcher.processCommand(cm,command.exArgs.input):vim.visualMode?showPrompt(cm,{onClose:onPromptClose,prefix:":",value:"'<,'>",onKeyDown:onPromptKeyDown}):showPrompt(cm,{onClose:onPromptClose,prefix:":",onKeyDown:onPromptKeyDown})},evalInput:function(cm,vim){var newHead,newAnchor,repeat,inputState=vim.inputState,motion=inputState.motion,motionArgs=inputState.motionArgs||{},operator=inputState.operator,operatorArgs=inputState.operatorArgs||{},registerName=inputState.registerName,sel=vim.sel,origHead=copyCursor(vim.visualMode?clipCursorToContent(cm,sel.head):cm.getCursor("head")),origAnchor=copyCursor(vim.visualMode?clipCursorToContent(cm,sel.anchor):cm.getCursor("anchor")),oldHead=copyCursor(origHead),oldAnchor=copyCursor(origAnchor);operator&&this.recordLastEdit(vim,inputState);repeat=void 0!==inputState.repeatOverride?inputState.repeatOverride:inputState.getRepeat();if(repeat>0&&motionArgs.explicitRepeat)motionArgs.repeatIsExplicit=!0;else if(motionArgs.noRepeat||!motionArgs.explicitRepeat&&0===repeat){repeat=1;motionArgs.repeatIsExplicit=!1}inputState.selectedCharacter&&(motionArgs.selectedCharacter=operatorArgs.selectedCharacter=inputState.selectedCharacter);motionArgs.repeat=repeat;clearInputState(cm);if(motion){var motionResult=motions[motion](cm,origHead,motionArgs,vim);vim.lastMotion=motions[motion];if(!motionResult)return;if(motionArgs.toJumplist){var jumpList=vimGlobalState.jumpList,cachedCursor=jumpList.cachedCursor;if(cachedCursor){recordJumpPosition(cm,cachedCursor,motionResult);delete jumpList.cachedCursor}else recordJumpPosition(cm,origHead,motionResult)}if(motionResult instanceof Array){newAnchor=motionResult[0];newHead=motionResult[1]}else newHead=motionResult;newHead||(newHead=copyCursor(origHead));if(vim.visualMode){vim.visualBlock&&newHead.ch===1/0||(newHead=clipCursorToContent(cm,newHead,vim.visualBlock));newAnchor&&(newAnchor=clipCursorToContent(cm,newAnchor,!0));newAnchor=newAnchor||oldAnchor;sel.anchor=newAnchor;sel.head=newHead;updateCmSelection(cm);updateMark(cm,vim,"<",cursorIsBefore(newAnchor,newHead)?newAnchor:newHead);updateMark(cm,vim,">",cursorIsBefore(newAnchor,newHead)?newHead:newAnchor)}else if(!operator){newHead=clipCursorToContent(cm,newHead);cm.setCursor(newHead.line,newHead.ch)}}if(operator){if(operatorArgs.lastSel){newAnchor=oldAnchor;var lastSel=operatorArgs.lastSel,lineOffset=Math.abs(lastSel.head.line-lastSel.anchor.line),chOffset=Math.abs(lastSel.head.ch-lastSel.anchor.ch);newHead=lastSel.visualLine?Pos(oldAnchor.line+lineOffset,oldAnchor.ch):lastSel.visualBlock?Pos(oldAnchor.line+lineOffset,oldAnchor.ch+chOffset):lastSel.head.line==lastSel.anchor.line?Pos(oldAnchor.line,oldAnchor.ch+chOffset):Pos(oldAnchor.line+lineOffset,oldAnchor.ch);vim.visualMode=!0;vim.visualLine=lastSel.visualLine;vim.visualBlock=lastSel.visualBlock;sel=vim.sel={anchor:newAnchor,head:newHead};updateCmSelection(cm)}else vim.visualMode&&(operatorArgs.lastSel={anchor:copyCursor(sel.anchor),head:copyCursor(sel.head),visualBlock:vim.visualBlock,visualLine:vim.visualLine});var curStart,curEnd,linewise,mode,cmSel;if(vim.visualMode){curStart=cursorMin(sel.head,sel.anchor);curEnd=cursorMax(sel.head,sel.anchor);linewise=vim.visualLine||operatorArgs.linewise;mode=vim.visualBlock?"block":linewise?"line":"char";cmSel=makeCmSelection(cm,{anchor:curStart,head:curEnd},mode);if(linewise){var ranges=cmSel.ranges;if("block"==mode)for(var i=0;i<ranges.length;i++)ranges[i].head.ch=lineLength(cm,ranges[i].head.line);else"line"==mode&&(ranges[0].head=Pos(ranges[0].head.line+1,0))}}else{curStart=copyCursor(newAnchor||oldAnchor);curEnd=copyCursor(newHead||oldHead);if(cursorIsBefore(curEnd,curStart)){var tmp=curStart;curStart=curEnd;curEnd=tmp}linewise=motionArgs.linewise||operatorArgs.linewise;linewise?expandSelectionToLine(cm,curStart,curEnd):motionArgs.forward&&clipToLine(cm,curStart,curEnd);mode="char";var exclusive=!motionArgs.inclusive||linewise;cmSel=makeCmSelection(cm,{anchor:curStart,head:curEnd},mode,exclusive)}cm.setSelections(cmSel.ranges,cmSel.primary);vim.lastMotion=null;operatorArgs.repeat=repeat;operatorArgs.registerName=registerName;operatorArgs.linewise=linewise;var operatorMoveTo=operators[operator](cm,operatorArgs,cmSel.ranges,oldAnchor,newHead);vim.visualMode&&exitVisualMode(cm,null!=operatorMoveTo);operatorMoveTo&&cm.setCursor(operatorMoveTo)}},recordLastEdit:function(vim,inputState,actionCommand){var macroModeState=vimGlobalState.macroModeState;if(!macroModeState.isPlaying){vim.lastEditInputState=inputState;vim.lastEditActionCommand=actionCommand;macroModeState.lastInsertModeChanges.changes=[];macroModeState.lastInsertModeChanges.expectCursorActivityForChange=!1}}},motions={moveToTopLine:function(cm,_head,motionArgs){var line=getUserVisibleLines(cm).top+motionArgs.repeat-1;return Pos(line,findFirstNonWhiteSpaceCharacter(cm.getLine(line)))},moveToMiddleLine:function(cm){var range=getUserVisibleLines(cm),line=Math.floor(.5*(range.top+range.bottom));return Pos(line,findFirstNonWhiteSpaceCharacter(cm.getLine(line)))},moveToBottomLine:function(cm,_head,motionArgs){var line=getUserVisibleLines(cm).bottom-motionArgs.repeat+1;return Pos(line,findFirstNonWhiteSpaceCharacter(cm.getLine(line)))},expandToLine:function(_cm,head,motionArgs){var cur=head;return Pos(cur.line+motionArgs.repeat-1,1/0)},findNext:function(cm,_head,motionArgs){var state=getSearchState(cm),query=state.getQuery();if(query){var prev=!motionArgs.forward;prev=state.isReversed()?!prev:prev;highlightSearchMatches(cm,query);return findNext(cm,prev,query,motionArgs.repeat)}},goToMark:function(cm,_head,motionArgs,vim){var mark=vim.marks[motionArgs.selectedCharacter];if(mark){var pos=mark.find();return motionArgs.linewise?{line:pos.line,ch:findFirstNonWhiteSpaceCharacter(cm.getLine(pos.line))}:pos}return null},moveToOtherHighlightedEnd:function(cm,_head,motionArgs,vim){if(vim.visualBlock&&motionArgs.sameLine){var sel=vim.sel;return[clipCursorToContent(cm,Pos(sel.anchor.line,sel.head.ch)),clipCursorToContent(cm,Pos(sel.head.line,sel.anchor.ch))]}return[vim.sel.head,vim.sel.anchor]},jumpToMark:function(cm,head,motionArgs,vim){for(var best=head,i=0;i<motionArgs.repeat;i++){var cursor=best;for(var key in vim.marks)if(isLowerCase(key)){var mark=vim.marks[key].find(),isWrongDirection=motionArgs.forward?cursorIsBefore(mark,cursor):cursorIsBefore(cursor,mark);if(!(isWrongDirection||motionArgs.linewise&&mark.line==cursor.line)){var equal=cursorEqual(cursor,best),between=motionArgs.forward?cursorIsBetween(cursor,mark,best):cursorIsBetween(best,mark,cursor);(equal||between)&&(best=mark)}}}motionArgs.linewise&&(best=Pos(best.line,findFirstNonWhiteSpaceCharacter(cm.getLine(best.line))));return best},moveByCharacters:function(_cm,head,motionArgs){var cur=head,repeat=motionArgs.repeat,ch=motionArgs.forward?cur.ch+repeat:cur.ch-repeat;return Pos(cur.line,ch)},moveByLines:function(cm,head,motionArgs,vim){var cur=head,endCh=cur.ch;switch(vim.lastMotion){case this.moveByLines:case this.moveByDisplayLines:case this.moveByScroll:case this.moveToColumn:case this.moveToEol:endCh=vim.lastHPos;break;default:vim.lastHPos=endCh}var repeat=motionArgs.repeat+(motionArgs.repeatOffset||0),line=motionArgs.forward?cur.line+repeat:cur.line-repeat,first=cm.firstLine(),last=cm.lastLine();if(first>line&&cur.line==first)return this.moveToStartOfLine(cm,head,motionArgs,vim);if(line>last&&cur.line==last)return this.moveToEol(cm,head,motionArgs,vim);if(motionArgs.toFirstChar){endCh=findFirstNonWhiteSpaceCharacter(cm.getLine(line));vim.lastHPos=endCh}vim.lastHSPos=cm.charCoords(Pos(line,endCh),"div").left;return Pos(line,endCh)},moveByDisplayLines:function(cm,head,motionArgs,vim){var cur=head;switch(vim.lastMotion){case this.moveByDisplayLines:case this.moveByScroll:case this.moveByLines:case this.moveToColumn:case this.moveToEol:break;default:vim.lastHSPos=cm.charCoords(cur,"div").left}var repeat=motionArgs.repeat,res=cm.findPosV(cur,motionArgs.forward?repeat:-repeat,"line",vim.lastHSPos);if(res.hitSide)if(motionArgs.forward)var lastCharCoords=cm.charCoords(res,"div"),goalCoords={top:lastCharCoords.top+8,left:vim.lastHSPos},res=cm.coordsChar(goalCoords,"div");else{var resCoords=cm.charCoords(Pos(cm.firstLine(),0),"div");resCoords.left=vim.lastHSPos;res=cm.coordsChar(resCoords,"div")}vim.lastHPos=res.ch;return res},moveByPage:function(cm,head,motionArgs){var curStart=head,repeat=motionArgs.repeat;return cm.findPosV(curStart,motionArgs.forward?repeat:-repeat,"page")},moveByParagraph:function(cm,head,motionArgs){var dir=motionArgs.forward?1:-1;return findParagraph(cm,head,motionArgs.repeat,dir)},moveByScroll:function(cm,head,motionArgs,vim){var scrollbox=cm.getScrollInfo(),curEnd=null,repeat=motionArgs.repeat;repeat||(repeat=scrollbox.clientHeight/(2*cm.defaultTextHeight()));var orig=cm.charCoords(head,"local");motionArgs.repeat=repeat;var curEnd=motions.moveByDisplayLines(cm,head,motionArgs,vim);if(!curEnd)return null;var dest=cm.charCoords(curEnd,"local");cm.scrollTo(null,scrollbox.top+dest.top-orig.top);return curEnd},moveByWords:function(cm,head,motionArgs){return moveToWord(cm,head,motionArgs.repeat,!!motionArgs.forward,!!motionArgs.wordEnd,!!motionArgs.bigWord)},moveTillCharacter:function(cm,_head,motionArgs){var repeat=motionArgs.repeat,curEnd=moveToCharacter(cm,repeat,motionArgs.forward,motionArgs.selectedCharacter),increment=motionArgs.forward?-1:1;recordLastCharacterSearch(increment,motionArgs);if(!curEnd)return null;curEnd.ch+=increment;return curEnd},moveToCharacter:function(cm,head,motionArgs){var repeat=motionArgs.repeat;recordLastCharacterSearch(0,motionArgs);return moveToCharacter(cm,repeat,motionArgs.forward,motionArgs.selectedCharacter)||head},moveToSymbol:function(cm,head,motionArgs){var repeat=motionArgs.repeat;return findSymbol(cm,repeat,motionArgs.forward,motionArgs.selectedCharacter)||head},moveToColumn:function(cm,head,motionArgs,vim){var repeat=motionArgs.repeat;vim.lastHPos=repeat-1;vim.lastHSPos=cm.charCoords(head,"div").left;return moveToColumn(cm,repeat)},moveToEol:function(cm,head,motionArgs,vim){var cur=head;vim.lastHPos=1/0;var retval=Pos(cur.line+motionArgs.repeat-1,1/0),end=cm.clipPos(retval);end.ch--;vim.lastHSPos=cm.charCoords(end,"div").left;return retval},moveToFirstNonWhiteSpaceCharacter:function(cm,head){var cursor=head;return Pos(cursor.line,findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line)))},moveToMatchedSymbol:function(cm,head){var symbol,cursor=head,line=cursor.line,ch=cursor.ch,lineText=cm.getLine(line);do{symbol=lineText.charAt(ch++);if(symbol&&isMatchableSymbol(symbol)){var style=cm.getTokenTypeAt(Pos(line,ch));if("string"!==style&&"comment"!==style)break}}while(symbol);if(symbol){var matched=cm.findMatchingBracket(Pos(line,ch));return matched.to}return cursor},moveToStartOfLine:function(_cm,head){return Pos(head.line,0)},moveToLineOrEdgeOfDocument:function(cm,_head,motionArgs){var lineNum=motionArgs.forward?cm.lastLine():cm.firstLine();motionArgs.repeatIsExplicit&&(lineNum=motionArgs.repeat-cm.getOption("firstLineNumber"));return Pos(lineNum,findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum)))},textObjectManipulation:function(cm,head,motionArgs,vim){var mirroredPairs={"(":")",")":"(","{":"}","}":"{","[":"]","]":"["},selfPaired={"'":!0,'"':!0},character=motionArgs.selectedCharacter;"b"==character?character="(":"B"==character&&(character="{");var tmp,inclusive=!motionArgs.textObjectInner;if(mirroredPairs[character])tmp=selectCompanionObject(cm,head,character,inclusive);else if(selfPaired[character])tmp=findBeginningAndEnd(cm,head,character,inclusive);else if("W"===character)tmp=expandWordUnderCursor(cm,inclusive,!0,!0);else if("w"===character)tmp=expandWordUnderCursor(cm,inclusive,!0,!1);else{if("p"!==character)return null;tmp=findParagraph(cm,head,motionArgs.repeat,0,inclusive);motionArgs.linewise=!0;if(vim.visualMode)vim.visualLine||(vim.visualLine=!0);else{var operatorArgs=vim.inputState.operatorArgs;operatorArgs&&(operatorArgs.linewise=!0);tmp.end.line--}}return cm.state.vim.visualMode?expandSelection(cm,tmp.start,tmp.end):[tmp.start,tmp.end]},repeatLastCharacterSearch:function(cm,head,motionArgs){var lastSearch=vimGlobalState.lastCharacterSearch,repeat=motionArgs.repeat,forward=motionArgs.forward===lastSearch.forward,increment=(lastSearch.increment?1:0)*(forward?-1:1);cm.moveH(-increment,"char");motionArgs.inclusive=forward?!0:!1;var curEnd=moveToCharacter(cm,repeat,forward,lastSearch.selectedCharacter);if(!curEnd){cm.moveH(increment,"char");return head}curEnd.ch+=increment;return curEnd}},operators={change:function(cm,args,ranges){var finalHead,text,vim=cm.state.vim;vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock=vim.visualBlock;if(vim.visualMode){text=cm.getSelection();var replacement=fillArray("",ranges.length);cm.replaceSelections(replacement);finalHead=cursorMin(ranges[0].head,ranges[0].anchor)}else{var anchor=ranges[0].anchor,head=ranges[0].head;text=cm.getRange(anchor,head);var lastState=vim.lastEditInputState||{};if("moveByWords"==lastState.motion&&!isWhiteSpaceString(text)){var match=/\s+$/.exec(text);if(match&&lastState.motionArgs&&lastState.motionArgs.forward){head=offsetCursor(head,0,-match[0].length);text=text.slice(0,-match[0].length)}}var prevLineEnd=new Pos(anchor.line-1,Number.MAX_VALUE),wasLastLine=cm.firstLine()==cm.lastLine();head.line>cm.lastLine()&&args.linewise&&!wasLastLine?cm.replaceRange("",prevLineEnd,head):cm.replaceRange("",anchor,head);if(args.linewise){if(!wasLastLine){cm.setCursor(prevLineEnd);CodeMirror.commands.newlineAndIndent(cm)}anchor.ch=Number.MAX_VALUE}finalHead=anchor}vimGlobalState.registerController.pushText(args.registerName,"change",text,args.linewise,ranges.length>1);actions.enterInsertMode(cm,{head:finalHead},cm.state.vim)},"delete":function(cm,args,ranges){var finalHead,text,vim=cm.state.vim;if(vim.visualBlock){text=cm.getSelection();var replacement=fillArray("",ranges.length);cm.replaceSelections(replacement);finalHead=ranges[0].anchor}else{var anchor=ranges[0].anchor,head=ranges[0].head;args.linewise&&head.line!=cm.firstLine()&&anchor.line==cm.lastLine()&&anchor.line==head.line-1&&(anchor.line==cm.firstLine()?anchor.ch=0:anchor=Pos(anchor.line-1,lineLength(cm,anchor.line-1)));text=cm.getRange(anchor,head);cm.replaceRange("",anchor,head);finalHead=anchor;args.linewise&&(finalHead=motions.moveToFirstNonWhiteSpaceCharacter(cm,anchor))}vimGlobalState.registerController.pushText(args.registerName,"delete",text,args.linewise,vim.visualBlock);return clipCursorToContent(cm,finalHead)},indent:function(cm,args,ranges){var vim=cm.state.vim,startLine=ranges[0].anchor.line,endLine=vim.visualBlock?ranges[ranges.length-1].anchor.line:ranges[0].head.line,repeat=vim.visualMode?args.repeat:1;args.linewise&&endLine--;for(var i=startLine;endLine>=i;i++)for(var j=0;repeat>j;j++)cm.indentLine(i,args.indentRight);return motions.moveToFirstNonWhiteSpaceCharacter(cm,ranges[0].anchor)},changeCase:function(cm,args,ranges,oldAnchor,newHead){for(var selections=cm.getSelections(),swapped=[],toLower=args.toLower,j=0;j<selections.length;j++){var toSwap=selections[j],text="";if(toLower===!0)text=toSwap.toLowerCase();else if(toLower===!1)text=toSwap.toUpperCase();else for(var i=0;i<toSwap.length;i++){var character=toSwap.charAt(i);text+=isUpperCase(character)?character.toLowerCase():character.toUpperCase()}swapped.push(text)}cm.replaceSelections(swapped);return args.shouldMoveCursor?newHead:!cm.state.vim.visualMode&&args.linewise&&ranges[0].anchor.line+1==ranges[0].head.line?motions.moveToFirstNonWhiteSpaceCharacter(cm,oldAnchor):args.linewise?oldAnchor:cursorMin(ranges[0].anchor,ranges[0].head)},yank:function(cm,args,ranges,oldAnchor){var vim=cm.state.vim,text=cm.getSelection(),endPos=vim.visualMode?cursorMin(vim.sel.anchor,vim.sel.head,ranges[0].head,ranges[0].anchor):oldAnchor;vimGlobalState.registerController.pushText(args.registerName,"yank",text,args.linewise,vim.visualBlock);return endPos}},actions={jumpListWalk:function(cm,actionArgs,vim){if(!vim.visualMode){var repeat=actionArgs.repeat,forward=actionArgs.forward,jumpList=vimGlobalState.jumpList,mark=jumpList.move(cm,forward?repeat:-repeat),markPos=mark?mark.find():void 0;markPos=markPos?markPos:cm.getCursor();cm.setCursor(markPos)}},scroll:function(cm,actionArgs,vim){if(!vim.visualMode){var repeat=actionArgs.repeat||1,lineHeight=cm.defaultTextHeight(),top=cm.getScrollInfo().top,delta=lineHeight*repeat,newPos=actionArgs.forward?top+delta:top-delta,cursor=copyCursor(cm.getCursor()),cursorCoords=cm.charCoords(cursor,"local");if(actionArgs.forward)if(newPos>cursorCoords.top){cursor.line+=(newPos-cursorCoords.top)/lineHeight;cursor.line=Math.ceil(cursor.line);cm.setCursor(cursor);cursorCoords=cm.charCoords(cursor,"local");cm.scrollTo(null,cursorCoords.top)}else cm.scrollTo(null,newPos);else{var newBottom=newPos+cm.getScrollInfo().clientHeight;if(newBottom<cursorCoords.bottom){cursor.line-=(cursorCoords.bottom-newBottom)/lineHeight;cursor.line=Math.floor(cursor.line);cm.setCursor(cursor);cursorCoords=cm.charCoords(cursor,"local");cm.scrollTo(null,cursorCoords.bottom-cm.getScrollInfo().clientHeight)}else cm.scrollTo(null,newPos)}}},scrollToCursor:function(cm,actionArgs){var lineNum=cm.getCursor().line,charCoords=cm.charCoords(Pos(lineNum,0),"local"),height=cm.getScrollInfo().clientHeight,y=charCoords.top,lineHeight=charCoords.bottom-y;switch(actionArgs.position){case"center":y=y-height/2+lineHeight;break;case"bottom":y=y-height+lineHeight}cm.scrollTo(null,y)},replayMacro:function(cm,actionArgs,vim){var registerName=actionArgs.selectedCharacter,repeat=actionArgs.repeat,macroModeState=vimGlobalState.macroModeState;"@"==registerName&&(registerName=macroModeState.latestRegister);for(;repeat--;)executeMacroRegister(cm,vim,macroModeState,registerName)},enterMacroRecordMode:function(cm,actionArgs){var macroModeState=vimGlobalState.macroModeState,registerName=actionArgs.selectedCharacter;macroModeState.enterMacroRecordMode(cm,registerName)},enterInsertMode:function(cm,actionArgs,vim){if(!cm.getOption("readOnly")){vim.insertMode=!0;vim.insertModeRepeat=actionArgs&&actionArgs.repeat||1;var insertAt=actionArgs?actionArgs.insertAt:null,sel=vim.sel,head=actionArgs.head||cm.getCursor("head"),height=cm.listSelections().length;if("eol"==insertAt)head=Pos(head.line,lineLength(cm,head.line));else if("charAfter"==insertAt)head=offsetCursor(head,0,1);else if("firstNonBlank"==insertAt)head=motions.moveToFirstNonWhiteSpaceCharacter(cm,head);else if("startOfSelectedArea"==insertAt)if(vim.visualBlock){head=Pos(Math.min(sel.head.line,sel.anchor.line),Math.min(sel.head.ch,sel.anchor.ch));height=Math.abs(sel.head.line-sel.anchor.line)+1}else head=sel.head.line<sel.anchor.line?sel.head:Pos(sel.anchor.line,0);else if("endOfSelectedArea"==insertAt)if(vim.visualBlock){head=Pos(Math.min(sel.head.line,sel.anchor.line),Math.max(sel.head.ch+1,sel.anchor.ch));height=Math.abs(sel.head.line-sel.anchor.line)+1}else head=sel.head.line>=sel.anchor.line?offsetCursor(sel.head,0,1):Pos(sel.anchor.line,0);else if("inplace"==insertAt&&vim.visualMode)return;cm.setOption("keyMap","vim-insert");cm.setOption("disableInput",!1);if(actionArgs&&actionArgs.replace){cm.toggleOverwrite(!0);cm.setOption("keyMap","vim-replace");CodeMirror.signal(cm,"vim-mode-change",{mode:"replace"})}else{cm.setOption("keyMap","vim-insert");CodeMirror.signal(cm,"vim-mode-change",{mode:"insert"})}if(!vimGlobalState.macroModeState.isPlaying){cm.on("change",onChange);CodeMirror.on(cm.getInputField(),"keydown",onKeyEventTargetKeyDown)}vim.visualMode&&exitVisualMode(cm);selectForInsert(cm,head,height)}},toggleVisualMode:function(cm,actionArgs,vim){var head,repeat=actionArgs.repeat,anchor=cm.getCursor();if(vim.visualMode)if(vim.visualLine^actionArgs.linewise||vim.visualBlock^actionArgs.blockwise){vim.visualLine=!!actionArgs.linewise;vim.visualBlock=!!actionArgs.blockwise;CodeMirror.signal(cm,"vim-mode-change",{mode:"visual",subMode:vim.visualLine?"linewise":vim.visualBlock?"blockwise":""});updateCmSelection(cm)}else exitVisualMode(cm);else{vim.visualMode=!0;vim.visualLine=!!actionArgs.linewise;vim.visualBlock=!!actionArgs.blockwise;head=clipCursorToContent(cm,Pos(anchor.line,anchor.ch+repeat-1),!0);vim.sel={anchor:anchor,head:head};CodeMirror.signal(cm,"vim-mode-change",{mode:"visual",subMode:vim.visualLine?"linewise":vim.visualBlock?"blockwise":""});updateCmSelection(cm);updateMark(cm,vim,"<",cursorMin(anchor,head));updateMark(cm,vim,">",cursorMax(anchor,head))}},reselectLastSelection:function(cm,_actionArgs,vim){var lastSelection=vim.lastSelection;vim.visualMode&&updateLastSelection(cm,vim);if(lastSelection){var anchor=lastSelection.anchorMark.find(),head=lastSelection.headMark.find();if(!anchor||!head)return;vim.sel={anchor:anchor,head:head};vim.visualMode=!0;vim.visualLine=lastSelection.visualLine;vim.visualBlock=lastSelection.visualBlock;updateCmSelection(cm);updateMark(cm,vim,"<",cursorMin(anchor,head));updateMark(cm,vim,">",cursorMax(anchor,head));CodeMirror.signal(cm,"vim-mode-change",{mode:"visual",subMode:vim.visualLine?"linewise":vim.visualBlock?"blockwise":""})}},joinLines:function(cm,actionArgs,vim){var curStart,curEnd;if(vim.visualMode){curStart=cm.getCursor("anchor");curEnd=cm.getCursor("head");if(cursorIsBefore(curEnd,curStart)){var tmp=curEnd;curEnd=curStart;curStart=tmp}curEnd.ch=lineLength(cm,curEnd.line)-1}else{var repeat=Math.max(actionArgs.repeat,2);curStart=cm.getCursor();curEnd=clipCursorToContent(cm,Pos(curStart.line+repeat-1,1/0))}for(var finalCh=0,i=curStart.line;i<curEnd.line;i++){finalCh=lineLength(cm,curStart.line);var tmp=Pos(curStart.line+1,lineLength(cm,curStart.line+1)),text=cm.getRange(curStart,tmp);text=text.replace(/\n\s*/g," ");cm.replaceRange(text,curStart,tmp)}var curFinalPos=Pos(curStart.line,finalCh);vim.visualMode&&exitVisualMode(cm,!1);cm.setCursor(curFinalPos)},newLineAndEnterInsertMode:function(cm,actionArgs,vim){vim.insertMode=!0;var insertAt=copyCursor(cm.getCursor());if(insertAt.line!==cm.firstLine()||actionArgs.after){insertAt.line=actionArgs.after?insertAt.line:insertAt.line-1;insertAt.ch=lineLength(cm,insertAt.line);cm.setCursor(insertAt);var newlineFn=CodeMirror.commands.newlineAndIndentContinueComment||CodeMirror.commands.newlineAndIndent;newlineFn(cm)}else{cm.replaceRange("\n",Pos(cm.firstLine(),0));cm.setCursor(cm.firstLine(),0)}this.enterInsertMode(cm,{repeat:actionArgs.repeat},vim)},paste:function(cm,actionArgs,vim){var cur=copyCursor(cm.getCursor()),register=vimGlobalState.registerController.getRegister(actionArgs.registerName),text=register.toString();if(text){if(actionArgs.matchIndent){var tabSize=cm.getOption("tabSize"),whitespaceLength=function(str){var tabs=str.split(" ").length-1,spaces=str.split(" ").length-1;return tabs*tabSize+1*spaces},currentLine=cm.getLine(cm.getCursor().line),indent=whitespaceLength(currentLine.match(/^\s*/)[0]),chompedText=text.replace(/\n$/,""),wasChomped=text!==chompedText,firstIndent=whitespaceLength(text.match(/^\s*/)[0]),text=chompedText.replace(/^\s*/gm,function(wspace){var newIndent=indent+(whitespaceLength(wspace)-firstIndent);if(0>newIndent)return"";if(cm.getOption("indentWithTabs")){var quotient=Math.floor(newIndent/tabSize);return Array(quotient+1).join(" ")}return Array(newIndent+1).join(" ")});text+=wasChomped?"\n":""}if(actionArgs.repeat>1)var text=Array(actionArgs.repeat+1).join(text);var linewise=register.linewise,blockwise=register.blockwise;if(linewise)if(vim.visualMode)text=vim.visualLine?text.slice(0,-1):"\n"+text.slice(0,text.length-1)+"\n";else if(actionArgs.after){text="\n"+text.slice(0,text.length-1);cur.ch=lineLength(cm,cur.line)}else cur.ch=0;else{if(blockwise){text=text.split("\n");for(var i=0;i<text.length;i++)text[i]=""==text[i]?" ":text[i]}cur.ch+=actionArgs.after?1:0}var curPosFinal,idx;if(vim.visualMode){vim.lastPastedText=text;var lastSelectionCurEnd,selectedArea=getSelectedAreaRange(cm,vim),selectionStart=selectedArea[0],selectionEnd=selectedArea[1],selectedText=cm.getSelection(),selections=cm.listSelections(),emptyStrings=new Array(selections.length).join("1").split("1");vim.lastSelection&&(lastSelectionCurEnd=vim.lastSelection.headMark.find());vimGlobalState.registerController.unnamedRegister.setText(selectedText);if(blockwise){cm.replaceSelections(emptyStrings);selectionEnd=Pos(selectionStart.line+text.length-1,selectionStart.ch);cm.setCursor(selectionStart);selectBlock(cm,selectionEnd);cm.replaceSelections(text);curPosFinal=selectionStart}else if(vim.visualBlock){cm.replaceSelections(emptyStrings);cm.setCursor(selectionStart);cm.replaceRange(text,selectionStart,selectionStart);curPosFinal=selectionStart}else{cm.replaceRange(text,selectionStart,selectionEnd);curPosFinal=cm.posFromIndex(cm.indexFromPos(selectionStart)+text.length-1)}lastSelectionCurEnd&&(vim.lastSelection.headMark=cm.setBookmark(lastSelectionCurEnd));linewise&&(curPosFinal.ch=0)}else if(blockwise){cm.setCursor(cur);for(var i=0;i<text.length;i++){var line=cur.line+i;line>cm.lastLine()&&cm.replaceRange("\n",Pos(line,0));var lastCh=lineLength(cm,line);lastCh<cur.ch&&extendLineToColumn(cm,line,cur.ch)}cm.setCursor(cur);selectBlock(cm,Pos(cur.line+text.length-1,cur.ch));cm.replaceSelections(text);curPosFinal=cur}else{cm.replaceRange(text,cur);if(linewise&&actionArgs.after)curPosFinal=Pos(cur.line+1,findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line+1)));else if(linewise&&!actionArgs.after)curPosFinal=Pos(cur.line,findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line)));else if(!linewise&&actionArgs.after){idx=cm.indexFromPos(cur);curPosFinal=cm.posFromIndex(idx+text.length-1)}else{idx=cm.indexFromPos(cur);curPosFinal=cm.posFromIndex(idx+text.length)}}vim.visualMode&&exitVisualMode(cm,!1);cm.setCursor(curPosFinal)}},undo:function(cm,actionArgs){cm.operation(function(){repeatFn(cm,CodeMirror.commands.undo,actionArgs.repeat)();cm.setCursor(cm.getCursor("anchor"))})},redo:function(cm,actionArgs){repeatFn(cm,CodeMirror.commands.redo,actionArgs.repeat)()},setRegister:function(_cm,actionArgs,vim){vim.inputState.registerName=actionArgs.selectedCharacter},setMark:function(cm,actionArgs,vim){var markName=actionArgs.selectedCharacter;updateMark(cm,vim,markName,cm.getCursor())},replace:function(cm,actionArgs,vim){var replaceTo,curEnd,replaceWith=actionArgs.selectedCharacter,curStart=cm.getCursor(),selections=cm.listSelections();if(vim.visualMode){curStart=cm.getCursor("start");curEnd=cm.getCursor("end")}else{var line=cm.getLine(curStart.line);replaceTo=curStart.ch+actionArgs.repeat;replaceTo>line.length&&(replaceTo=line.length);curEnd=Pos(curStart.line,replaceTo)}if("\n"==replaceWith){vim.visualMode||cm.replaceRange("",curStart,curEnd);(CodeMirror.commands.newlineAndIndentContinueComment||CodeMirror.commands.newlineAndIndent)(cm)}else{var replaceWithStr=cm.getRange(curStart,curEnd);replaceWithStr=replaceWithStr.replace(/[^\n]/g,replaceWith);if(vim.visualBlock){var spaces=new Array(cm.getOption("tabSize")+1).join(" ");replaceWithStr=cm.getSelection();replaceWithStr=replaceWithStr.replace(/\t/g,spaces).replace(/[^\n]/g,replaceWith).split("\n");cm.replaceSelections(replaceWithStr)}else cm.replaceRange(replaceWithStr,curStart,curEnd);if(vim.visualMode){curStart=cursorIsBefore(selections[0].anchor,selections[0].head)?selections[0].anchor:selections[0].head;cm.setCursor(curStart);exitVisualMode(cm,!1)}else cm.setCursor(offsetCursor(curEnd,0,-1))}},incrementNumberToken:function(cm,actionArgs){for(var match,start,end,numberStr,token,cur=cm.getCursor(),lineStr=cm.getLine(cur.line),re=/-?\d+/g;null!==(match=re.exec(lineStr));){token=match[0];start=match.index;end=start+token.length;if(cur.ch<end)break}if((actionArgs.backtrack||!(end<=cur.ch))&&token){var increment=actionArgs.increase?1:-1,number=parseInt(token)+increment*actionArgs.repeat,from=Pos(cur.line,start),to=Pos(cur.line,end);numberStr=number.toString();cm.replaceRange(numberStr,from,to);cm.setCursor(Pos(cur.line,start+numberStr.length-1))}},repeatLastEdit:function(cm,actionArgs,vim){var lastEditInputState=vim.lastEditInputState;if(lastEditInputState){var repeat=actionArgs.repeat;repeat&&actionArgs.repeatIsExplicit?vim.lastEditInputState.repeatOverride=repeat:repeat=vim.lastEditInputState.repeatOverride||repeat;repeatLastEdit(cm,vim,repeat,!1)}},exitInsertMode:exitInsertMode},symbolToMode={"(":"bracket",")":"bracket","{":"bracket","}":"bracket","[":"section","]":"section","*":"comment","/":"comment",m:"method",M:"method","#":"preprocess"},findSymbolModes={bracket:{isComplete:function(state){if(state.nextCh===state.symb){state.depth++;if(state.depth>=1)return!0}else state.nextCh===state.reverseSymb&&state.depth--;return!1}},section:{init:function(state){state.curMoveThrough=!0;state.symb=(state.forward?"]":"[")===state.symb?"{":"}"},isComplete:function(state){return 0===state.index&&state.nextCh===state.symb}},comment:{isComplete:function(state){var found="*"===state.lastCh&&"/"===state.nextCh;state.lastCh=state.nextCh;return found}},method:{init:function(state){state.symb="m"===state.symb?"{":"}";state.reverseSymb="{"===state.symb?"}":"{"},isComplete:function(state){return state.nextCh===state.symb?!0:!1}},preprocess:{init:function(state){state.index=0},isComplete:function(state){if("#"===state.nextCh){var token=state.lineText.match(/#(\w+)/)[1];if("endif"===token){if(state.forward&&0===state.depth)return!0;state.depth++}else if("if"===token){if(!state.forward&&0===state.depth)return!0;state.depth--}if("else"===token&&0===state.depth)return!0}return!1}}};defineOption("pcre",!0,"boolean");SearchState.prototype={getQuery:function(){return vimGlobalState.query},setQuery:function(query){vimGlobalState.query=query},getOverlay:function(){return this.searchOverlay},setOverlay:function(overlay){this.searchOverlay=overlay},isReversed:function(){return vimGlobalState.isReversed},setReversed:function(reversed){vimGlobalState.isReversed=reversed},getScrollbarAnnotate:function(){return this.annotate},setScrollbarAnnotate:function(annotate){this.annotate=annotate}};var charUnescapes={"\\n":"\n","\\r":"\r","\\t":" "},unescapes={"\\/":"/","\\\\":"\\","\\n":"\n","\\r":"\r","\\t":" "},searchPromptDesc="(Javascript regexp)",ExCommandDispatcher=function(){this.buildCommandMap_()};ExCommandDispatcher.prototype={processCommand:function(cm,input,opt_params){var that=this;cm.operation(function(){cm.curOp.isVimOp=!0;that._processCommand(cm,input,opt_params)})},_processCommand:function(cm,input,opt_params){var vim=cm.state.vim,commandHistoryRegister=vimGlobalState.registerController.getRegister(":"),previousCommand=commandHistoryRegister.toString();vim.visualMode&&exitVisualMode(cm);var inputStream=new CodeMirror.StringStream(input);commandHistoryRegister.setText(input);var params=opt_params||{};params.input=input;try{this.parseInput_(cm,inputStream,params)}catch(e){showConfirm(cm,e);throw e}var command,commandName;if(params.commandName){command=this.matchCommand_(params.commandName);if(command){commandName=command.name;command.excludeFromCommandHistory&&commandHistoryRegister.setText(previousCommand);this.parseCommandArgs_(inputStream,params,command);if("exToKey"==command.type){for(var i=0;i<command.toKeys.length;i++)CodeMirror.Vim.handleKey(cm,command.toKeys[i],"mapping");return}if("exToEx"==command.type){this.processCommand(cm,command.toInput);return}}}else void 0!==params.line&&(commandName="move");if(commandName)try{exCommands[commandName](cm,params);command&&command.possiblyAsync||!params.callback||params.callback();
4
- }catch(e){showConfirm(cm,e);throw e}else showConfirm(cm,'Not an editor command ":'+input+'"')},parseInput_:function(cm,inputStream,result){inputStream.eatWhile(":");if(inputStream.eat("%")){result.line=cm.firstLine();result.lineEnd=cm.lastLine()}else{result.line=this.parseLineSpec_(cm,inputStream);void 0!==result.line&&inputStream.eat(",")&&(result.lineEnd=this.parseLineSpec_(cm,inputStream))}var commandMatch=inputStream.match(/^(\w+)/);commandMatch?result.commandName=commandMatch[1]:result.commandName=inputStream.match(/.*/)[0];return result},parseLineSpec_:function(cm,inputStream){var numberMatch=inputStream.match(/^(\d+)/);if(numberMatch)return parseInt(numberMatch[1],10)-1;switch(inputStream.next()){case".":return cm.getCursor().line;case"$":return cm.lastLine();case"'":var mark=cm.state.vim.marks[inputStream.next()];if(mark&&mark.find())return mark.find().line;throw new Error("Mark not set");default:inputStream.backUp(1);return void 0}},parseCommandArgs_:function(inputStream,params,command){if(!inputStream.eol()){params.argString=inputStream.match(/.*/)[0];var delim=command.argDelimiter||/\s+/,args=trim(params.argString).split(delim);args.length&&args[0]&&(params.args=args)}},matchCommand_:function(commandName){for(var i=commandName.length;i>0;i--){var prefix=commandName.substring(0,i);if(this.commandMap_[prefix]){var command=this.commandMap_[prefix];if(0===command.name.indexOf(commandName))return command}}return null},buildCommandMap_:function(){this.commandMap_={};for(var i=0;i<defaultExCommandMap.length;i++){var command=defaultExCommandMap[i],key=command.shortName||command.name;this.commandMap_[key]=command}},map:function(lhs,rhs,ctx){if(":"!=lhs&&":"==lhs.charAt(0)){if(ctx)throw Error("Mode not supported for ex mappings");var commandName=lhs.substring(1);":"!=rhs&&":"==rhs.charAt(0)?this.commandMap_[commandName]={name:commandName,type:"exToEx",toInput:rhs.substring(1),user:!0}:this.commandMap_[commandName]={name:commandName,type:"exToKey",toKeys:rhs,user:!0}}else if(":"!=rhs&&":"==rhs.charAt(0)){var mapping={keys:lhs,type:"keyToEx",exArgs:{input:rhs.substring(1)},user:!0};ctx&&(mapping.context=ctx);defaultKeymap.unshift(mapping)}else{var mapping={keys:lhs,type:"keyToKey",toKeys:rhs,user:!0};ctx&&(mapping.context=ctx);defaultKeymap.unshift(mapping)}},unmap:function(lhs,ctx){if(":"!=lhs&&":"==lhs.charAt(0)){if(ctx)throw Error("Mode not supported for ex mappings");var commandName=lhs.substring(1);if(this.commandMap_[commandName]&&this.commandMap_[commandName].user){delete this.commandMap_[commandName];return}}else for(var keys=lhs,i=0;i<defaultKeymap.length;i++)if(keys==defaultKeymap[i].keys&&defaultKeymap[i].context===ctx&&defaultKeymap[i].user){defaultKeymap.splice(i,1);return}throw Error("No such mapping.")}};var exCommands={colorscheme:function(cm,params){!params.args||params.args.length<1?showConfirm(cm,cm.getOption("theme")):cm.setOption("theme",params.args[0])},map:function(cm,params,ctx){var mapArgs=params.args;!mapArgs||mapArgs.length<2?cm&&showConfirm(cm,"Invalid mapping: "+params.input):exCommandDispatcher.map(mapArgs[0],mapArgs[1],ctx)},imap:function(cm,params){this.map(cm,params,"insert")},nmap:function(cm,params){this.map(cm,params,"normal")},vmap:function(cm,params){this.map(cm,params,"visual")},unmap:function(cm,params,ctx){var mapArgs=params.args;!mapArgs||mapArgs.length<1?cm&&showConfirm(cm,"No such mapping: "+params.input):exCommandDispatcher.unmap(mapArgs[0],ctx)},move:function(cm,params){commandDispatcher.processCommand(cm,cm.state.vim,{type:"motion",motion:"moveToLineOrEdgeOfDocument",motionArgs:{forward:!1,explicitRepeat:!0,linewise:!0},repeatOverride:params.line+1})},set:function(cm,params){var setArgs=params.args,setCfg=params.setCfg||{};if(!setArgs||setArgs.length<1)cm&&showConfirm(cm,"Invalid mapping: "+params.input);else{var expr=setArgs[0].split("="),optionName=expr[0],value=expr[1],forceGet=!1;if("?"==optionName.charAt(optionName.length-1)){if(value)throw Error("Trailing characters: "+params.argString);optionName=optionName.substring(0,optionName.length-1);forceGet=!0}if(void 0===value&&"no"==optionName.substring(0,2)){optionName=optionName.substring(2);value=!1}var optionIsBoolean=options[optionName]&&"boolean"==options[optionName].type;optionIsBoolean&&void 0==value&&(value=!0);if(!optionIsBoolean&&void 0===value||forceGet){var oldValue=getOption(optionName,cm,setCfg);oldValue===!0||oldValue===!1?showConfirm(cm," "+(oldValue?"":"no")+optionName):showConfirm(cm," "+optionName+"="+oldValue)}else setOption(optionName,value,cm,setCfg)}},setlocal:function(cm,params){params.setCfg={scope:"local"};this.set(cm,params)},setglobal:function(cm,params){params.setCfg={scope:"global"};this.set(cm,params)},registers:function(cm,params){var regArgs=params.args,registers=vimGlobalState.registerController.registers,regInfo="----------Registers----------<br><br>";if(regArgs){var registerName;regArgs=regArgs.join("");for(var i=0;i<regArgs.length;i++){registerName=regArgs.charAt(i);if(vimGlobalState.registerController.isValidRegister(registerName)){var register=registers[registerName]||new Register;regInfo+='"'+registerName+" "+register.toString()+"<br>"}}}else for(var registerName in registers){var text=registers[registerName].toString();text.length&&(regInfo+='"'+registerName+" "+text+"<br>")}showConfirm(cm,regInfo)},sort:function(cm,params){function parseArgs(){if(params.argString){var args=new CodeMirror.StringStream(params.argString);args.eat("!")&&(reverse=!0);if(args.eol())return;if(!args.eatSpace())return"Invalid arguments";var opts=args.match(/[a-z]+/);if(opts){opts=opts[0];ignoreCase=-1!=opts.indexOf("i");unique=-1!=opts.indexOf("u");var decimal=-1!=opts.indexOf("d")&&1,hex=-1!=opts.indexOf("x")&&1,octal=-1!=opts.indexOf("o")&&1;if(decimal+hex+octal>1)return"Invalid arguments";number=decimal&&"decimal"||hex&&"hex"||octal&&"octal"}if(args.match(/\/.*\//))return"patterns not supported"}}function compareFn(a,b){if(reverse){var tmp;tmp=a;a=b;b=tmp}if(ignoreCase){a=a.toLowerCase();b=b.toLowerCase()}var anum=number&&numberRegex.exec(a),bnum=number&&numberRegex.exec(b);if(!anum)return b>a?-1:1;anum=parseInt((anum[1]+anum[2]).toLowerCase(),radix);bnum=parseInt((bnum[1]+bnum[2]).toLowerCase(),radix);return anum-bnum}var reverse,ignoreCase,unique,number,err=parseArgs();if(err)showConfirm(cm,err+": "+params.argString);else{var lineStart=params.line||cm.firstLine(),lineEnd=params.lineEnd||params.line||cm.lastLine();if(lineStart!=lineEnd){var curStart=Pos(lineStart,0),curEnd=Pos(lineEnd,lineLength(cm,lineEnd)),text=cm.getRange(curStart,curEnd).split("\n"),numberRegex="decimal"==number?/(-?)([\d]+)/:"hex"==number?/(-?)(?:0x)?([0-9a-f]+)/i:"octal"==number?/([0-7]+)/:null,radix="decimal"==number?10:"hex"==number?16:"octal"==number?8:null,numPart=[],textPart=[];if(number)for(var i=0;i<text.length;i++)numberRegex.exec(text[i])?numPart.push(text[i]):textPart.push(text[i]);else textPart=text;numPart.sort(compareFn);textPart.sort(compareFn);text=reverse?numPart.concat(textPart):textPart.concat(numPart);if(unique){var lastLine,textOld=text;text=[];for(var i=0;i<textOld.length;i++){textOld[i]!=lastLine&&text.push(textOld[i]);lastLine=textOld[i]}}cm.replaceRange(text.join("\n"),curStart,curEnd)}}},global:function(cm,params){var argString=params.argString;if(argString){var cmd,lineStart=void 0!==params.line?params.line:cm.firstLine(),lineEnd=params.lineEnd||params.line||cm.lastLine(),tokens=splitBySlash(argString),regexPart=argString;if(tokens.length){regexPart=tokens[0];cmd=tokens.slice(1,tokens.length).join("/")}if(regexPart)try{updateSearchQuery(cm,regexPart,!0,!0)}catch(e){showConfirm(cm,"Invalid regex: "+regexPart);return}for(var query=getSearchState(cm).getQuery(),matchedLines=[],content="",i=lineStart;lineEnd>=i;i++){var matched=query.test(cm.getLine(i));if(matched){matchedLines.push(i+1);content+=cm.getLine(i)+"<br>"}}if(cmd){var index=0,nextCommand=function(){if(index<matchedLines.length){var command=matchedLines[index]+cmd;exCommandDispatcher.processCommand(cm,command,{callback:nextCommand})}index++};nextCommand()}else showConfirm(cm,content)}else showConfirm(cm,"Regular Expression missing from global")},substitute:function(cm,params){if(!cm.getSearchCursor)throw new Error("Search feature not available. Requires searchcursor.js or any other getSearchCursor implementation.");var regexPart,trailing,flagsPart,count,argString=params.argString,tokens=argString?splitBySlash(argString):[],replacePart="",confirm=!1,global=!1;if(tokens.length){regexPart=tokens[0];replacePart=tokens[1];if(void 0!==replacePart){replacePart=getOption("pcre")?unescapeRegexReplace(replacePart):translateRegexReplace(replacePart);vimGlobalState.lastSubstituteReplacePart=replacePart}trailing=tokens[2]?tokens[2].split(" "):[]}else if(argString&&argString.length){showConfirm(cm,"Substitutions should be of the form :s/pattern/replace/");return}if(trailing){flagsPart=trailing[0];count=parseInt(trailing[1]);if(flagsPart){if(-1!=flagsPart.indexOf("c")){confirm=!0;flagsPart.replace("c","")}if(-1!=flagsPart.indexOf("g")){global=!0;flagsPart.replace("g","")}regexPart=regexPart+"/"+flagsPart}}if(regexPart)try{updateSearchQuery(cm,regexPart,!0,!0)}catch(e){showConfirm(cm,"Invalid regex: "+regexPart);return}replacePart=replacePart||vimGlobalState.lastSubstituteReplacePart;if(void 0!==replacePart){var state=getSearchState(cm),query=state.getQuery(),lineStart=void 0!==params.line?params.line:cm.getCursor().line,lineEnd=params.lineEnd||lineStart;lineStart==cm.firstLine()&&lineEnd==cm.lastLine()&&(lineEnd=1/0);if(count){lineStart=lineEnd;lineEnd=lineStart+count-1}var startPos=clipCursorToContent(cm,Pos(lineStart,0)),cursor=cm.getSearchCursor(query,startPos);doReplace(cm,confirm,global,lineStart,lineEnd,cursor,query,replacePart,params.callback)}else showConfirm(cm,"No previous substitute regular expression")},redo:CodeMirror.commands.redo,undo:CodeMirror.commands.undo,write:function(cm){CodeMirror.commands.save?CodeMirror.commands.save(cm):cm.save&&cm.save()},nohlsearch:function(cm){clearSearchHighlight(cm)},yank:function(cm){var cur=copyCursor(cm.getCursor()),line=cur.line,lineText=cm.getLine(line);vimGlobalState.registerController.pushText("0","yank",lineText,!0,!0)},delmarks:function(cm,params){if(params.argString&&trim(params.argString))for(var state=cm.state.vim,stream=new CodeMirror.StringStream(trim(params.argString));!stream.eol();){stream.eatSpace();var count=stream.pos;if(!stream.match(/[a-zA-Z]/,!1)){showConfirm(cm,"Invalid argument: "+params.argString.substring(count));return}var sym=stream.next();if(stream.match("-",!0)){if(!stream.match(/[a-zA-Z]/,!1)){showConfirm(cm,"Invalid argument: "+params.argString.substring(count));return}var startMark=sym,finishMark=stream.next();if(!(isLowerCase(startMark)&&isLowerCase(finishMark)||isUpperCase(startMark)&&isUpperCase(finishMark))){showConfirm(cm,"Invalid argument: "+startMark+"-");return}var start=startMark.charCodeAt(0),finish=finishMark.charCodeAt(0);if(start>=finish){showConfirm(cm,"Invalid argument: "+params.argString.substring(count));return}for(var j=0;finish-start>=j;j++){var mark=String.fromCharCode(start+j);delete state.marks[mark]}}else delete state.marks[sym]}else showConfirm(cm,"Argument required")}},exCommandDispatcher=new ExCommandDispatcher;CodeMirror.keyMap.vim={attach:attachVimMap,detach:detachVimMap,call:cmKey};defineOption("insertModeEscKeysTimeout",200,"number");CodeMirror.keyMap["vim-insert"]={"Ctrl-N":"autocomplete","Ctrl-P":"autocomplete",Enter:function(cm){var fn=CodeMirror.commands.newlineAndIndentContinueComment||CodeMirror.commands.newlineAndIndent;fn(cm)},fallthrough:["default"],attach:attachVimMap,detach:detachVimMap,call:cmKey};CodeMirror.keyMap["vim-replace"]={Backspace:"goCharLeft",fallthrough:["vim-insert"],attach:attachVimMap,detach:detachVimMap,call:cmKey};resetVimGlobalState();return vimApi};CodeMirror.Vim=Vim()});
1
+ !function(mod){"object"==typeof exports&&"object"==typeof module?mod(require("../lib/codemirror"),require("../addon/search/searchcursor"),require("../addon/dialog/dialog"),require("../addon/edit/matchbrackets.js")):"function"==typeof define&&define.amd?define(["../lib/codemirror","../addon/search/searchcursor","../addon/dialog/dialog","../addon/edit/matchbrackets"],mod):mod(CodeMirror)}(function(CodeMirror){"use strict";var defaultKeymap=[{keys:"<Left>",type:"keyToKey",toKeys:"h"},{keys:"<Right>",type:"keyToKey",toKeys:"l"},{keys:"<Up>",type:"keyToKey",toKeys:"k"},{keys:"<Down>",type:"keyToKey",toKeys:"j"},{keys:"<Space>",type:"keyToKey",toKeys:"l"},{keys:"<BS>",type:"keyToKey",toKeys:"h",context:"normal"},{keys:"<C-Space>",type:"keyToKey",toKeys:"W"},{keys:"<C-BS>",type:"keyToKey",toKeys:"B",context:"normal"},{keys:"<S-Space>",type:"keyToKey",toKeys:"w"},{keys:"<S-BS>",type:"keyToKey",toKeys:"b",context:"normal"},{keys:"<C-n>",type:"keyToKey",toKeys:"j"},{keys:"<C-p>",type:"keyToKey",toKeys:"k"},{keys:"<C-[>",type:"keyToKey",toKeys:"<Esc>"},{keys:"<C-c>",type:"keyToKey",toKeys:"<Esc>"},{keys:"<C-[>",type:"keyToKey",toKeys:"<Esc>",context:"insert"},{keys:"<C-c>",type:"keyToKey",toKeys:"<Esc>",context:"insert"},{keys:"s",type:"keyToKey",toKeys:"cl",context:"normal"},{keys:"s",type:"keyToKey",toKeys:"c",context:"visual"},{keys:"S",type:"keyToKey",toKeys:"cc",context:"normal"},{keys:"S",type:"keyToKey",toKeys:"VdO",context:"visual"},{keys:"<Home>",type:"keyToKey",toKeys:"0"},{keys:"<End>",type:"keyToKey",toKeys:"$"},{keys:"<PageUp>",type:"keyToKey",toKeys:"<C-b>"},{keys:"<PageDown>",type:"keyToKey",toKeys:"<C-f>"},{keys:"<CR>",type:"keyToKey",toKeys:"j^",context:"normal"},{keys:"<Ins>",type:"action",action:"toggleOverwrite",context:"insert"},{keys:"H",type:"motion",motion:"moveToTopLine",motionArgs:{linewise:!0,toJumplist:!0}},{keys:"M",type:"motion",motion:"moveToMiddleLine",motionArgs:{linewise:!0,toJumplist:!0}},{keys:"L",type:"motion",motion:"moveToBottomLine",motionArgs:{linewise:!0,toJumplist:!0}},{keys:"h",type:"motion",motion:"moveByCharacters",motionArgs:{forward:!1}},{keys:"l",type:"motion",motion:"moveByCharacters",motionArgs:{forward:!0}},{keys:"j",type:"motion",motion:"moveByLines",motionArgs:{forward:!0,linewise:!0}},{keys:"k",type:"motion",motion:"moveByLines",motionArgs:{forward:!1,linewise:!0}},{keys:"gj",type:"motion",motion:"moveByDisplayLines",motionArgs:{forward:!0}},{keys:"gk",type:"motion",motion:"moveByDisplayLines",motionArgs:{forward:!1}},{keys:"w",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!1}},{keys:"W",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!1,bigWord:!0}},{keys:"e",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!0,inclusive:!0}},{keys:"E",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!0,bigWord:!0,inclusive:!0}},{keys:"b",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!1}},{keys:"B",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!1,bigWord:!0}},{keys:"ge",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!0,inclusive:!0}},{keys:"gE",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!0,bigWord:!0,inclusive:!0}},{keys:"{",type:"motion",motion:"moveByParagraph",motionArgs:{forward:!1,toJumplist:!0}},{keys:"}",type:"motion",motion:"moveByParagraph",motionArgs:{forward:!0,toJumplist:!0}},{keys:"<C-f>",type:"motion",motion:"moveByPage",motionArgs:{forward:!0}},{keys:"<C-b>",type:"motion",motion:"moveByPage",motionArgs:{forward:!1}},{keys:"<C-d>",type:"motion",motion:"moveByScroll",motionArgs:{forward:!0,explicitRepeat:!0}},{keys:"<C-u>",type:"motion",motion:"moveByScroll",motionArgs:{forward:!1,explicitRepeat:!0}},{keys:"gg",type:"motion",motion:"moveToLineOrEdgeOfDocument",motionArgs:{forward:!1,explicitRepeat:!0,linewise:!0,toJumplist:!0}},{keys:"G",type:"motion",motion:"moveToLineOrEdgeOfDocument",motionArgs:{forward:!0,explicitRepeat:!0,linewise:!0,toJumplist:!0}},{keys:"0",type:"motion",motion:"moveToStartOfLine"},{keys:"^",type:"motion",motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:"+",type:"motion",motion:"moveByLines",motionArgs:{forward:!0,toFirstChar:!0}},{keys:"-",type:"motion",motion:"moveByLines",motionArgs:{forward:!1,toFirstChar:!0}},{keys:"_",type:"motion",motion:"moveByLines",motionArgs:{forward:!0,toFirstChar:!0,repeatOffset:-1}},{keys:"$",type:"motion",motion:"moveToEol",motionArgs:{inclusive:!0}},{keys:"%",type:"motion",motion:"moveToMatchedSymbol",motionArgs:{inclusive:!0,toJumplist:!0}},{keys:"f<character>",type:"motion",motion:"moveToCharacter",motionArgs:{forward:!0,inclusive:!0}},{keys:"F<character>",type:"motion",motion:"moveToCharacter",motionArgs:{forward:!1}},{keys:"t<character>",type:"motion",motion:"moveTillCharacter",motionArgs:{forward:!0,inclusive:!0}},{keys:"T<character>",type:"motion",motion:"moveTillCharacter",motionArgs:{forward:!1}},{keys:";",type:"motion",motion:"repeatLastCharacterSearch",motionArgs:{forward:!0}},{keys:",",type:"motion",motion:"repeatLastCharacterSearch",motionArgs:{forward:!1}},{keys:"'<character>",type:"motion",motion:"goToMark",motionArgs:{toJumplist:!0,linewise:!0}},{keys:"`<character>",type:"motion",motion:"goToMark",motionArgs:{toJumplist:!0}},{keys:"]`",type:"motion",motion:"jumpToMark",motionArgs:{forward:!0}},{keys:"[`",type:"motion",motion:"jumpToMark",motionArgs:{forward:!1}},{keys:"]'",type:"motion",motion:"jumpToMark",motionArgs:{forward:!0,linewise:!0}},{keys:"['",type:"motion",motion:"jumpToMark",motionArgs:{forward:!1,linewise:!0}},{keys:"]p",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!0,isEdit:!0,matchIndent:!0}},{keys:"[p",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!1,isEdit:!0,matchIndent:!0}},{keys:"]<character>",type:"motion",motion:"moveToSymbol",motionArgs:{forward:!0,toJumplist:!0}},{keys:"[<character>",type:"motion",motion:"moveToSymbol",motionArgs:{forward:!1,toJumplist:!0}},{keys:"|",type:"motion",motion:"moveToColumn"},{keys:"o",type:"motion",motion:"moveToOtherHighlightedEnd",context:"visual"},{keys:"O",type:"motion",motion:"moveToOtherHighlightedEnd",motionArgs:{sameLine:!0},context:"visual"},{keys:"d",type:"operator",operator:"delete"},{keys:"y",type:"operator",operator:"yank"},{keys:"c",type:"operator",operator:"change"},{keys:">",type:"operator",operator:"indent",operatorArgs:{indentRight:!0}},{keys:"<",type:"operator",operator:"indent",operatorArgs:{indentRight:!1}},{keys:"g~",type:"operator",operator:"changeCase"},{keys:"gu",type:"operator",operator:"changeCase",operatorArgs:{toLower:!0},isEdit:!0},{keys:"gU",type:"operator",operator:"changeCase",operatorArgs:{toLower:!1},isEdit:!0},{keys:"n",type:"motion",motion:"findNext",motionArgs:{forward:!0,toJumplist:!0}},{keys:"N",type:"motion",motion:"findNext",motionArgs:{forward:!1,toJumplist:!0}},{keys:"x",type:"operatorMotion",operator:"delete",motion:"moveByCharacters",motionArgs:{forward:!0},operatorMotionArgs:{visualLine:!1}},{keys:"X",type:"operatorMotion",operator:"delete",motion:"moveByCharacters",motionArgs:{forward:!1},operatorMotionArgs:{visualLine:!0}},{keys:"D",type:"operatorMotion",operator:"delete",motion:"moveToEol",motionArgs:{inclusive:!0},context:"normal"},{keys:"D",type:"operator",operator:"delete",operatorArgs:{linewise:!0},context:"visual"},{keys:"Y",type:"operatorMotion",operator:"yank",motion:"moveToEol",motionArgs:{inclusive:!0},context:"normal"},{keys:"Y",type:"operator",operator:"yank",operatorArgs:{linewise:!0},context:"visual"},{keys:"C",type:"operatorMotion",operator:"change",motion:"moveToEol",motionArgs:{inclusive:!0},context:"normal"},{keys:"C",type:"operator",operator:"change",operatorArgs:{linewise:!0},context:"visual"},{keys:"~",type:"operatorMotion",operator:"changeCase",motion:"moveByCharacters",motionArgs:{forward:!0},operatorArgs:{shouldMoveCursor:!0},context:"normal"},{keys:"~",type:"operator",operator:"changeCase",context:"visual"},{keys:"<C-w>",type:"operatorMotion",operator:"delete",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!1},context:"insert"},{keys:"<C-i>",type:"action",action:"jumpListWalk",actionArgs:{forward:!0}},{keys:"<C-o>",type:"action",action:"jumpListWalk",actionArgs:{forward:!1}},{keys:"<C-e>",type:"action",action:"scroll",actionArgs:{forward:!0,linewise:!0}},{keys:"<C-y>",type:"action",action:"scroll",actionArgs:{forward:!1,linewise:!0}},{keys:"a",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"charAfter"},context:"normal"},{keys:"A",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"eol"},context:"normal"},{keys:"A",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"endOfSelectedArea"},context:"visual"},{keys:"i",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"inplace"},context:"normal"},{keys:"I",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"firstNonBlank"},context:"normal"},{keys:"I",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"startOfSelectedArea"},context:"visual"},{keys:"o",type:"action",action:"newLineAndEnterInsertMode",isEdit:!0,interlaceInsertRepeat:!0,actionArgs:{after:!0},context:"normal"},{keys:"O",type:"action",action:"newLineAndEnterInsertMode",isEdit:!0,interlaceInsertRepeat:!0,actionArgs:{after:!1},context:"normal"},{keys:"v",type:"action",action:"toggleVisualMode"},{keys:"V",type:"action",action:"toggleVisualMode",actionArgs:{linewise:!0}},{keys:"<C-v>",type:"action",action:"toggleVisualMode",actionArgs:{blockwise:!0}},{keys:"<C-q>",type:"action",action:"toggleVisualMode",actionArgs:{blockwise:!0}},{keys:"gv",type:"action",action:"reselectLastSelection"},{keys:"J",type:"action",action:"joinLines",isEdit:!0},{keys:"p",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!0,isEdit:!0}},{keys:"P",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!1,isEdit:!0}},{keys:"r<character>",type:"action",action:"replace",isEdit:!0},{keys:"@<character>",type:"action",action:"replayMacro"},{keys:"q<character>",type:"action",action:"enterMacroRecordMode"},{keys:"R",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{replace:!0}},{keys:"u",type:"action",action:"undo",context:"normal"},{keys:"u",type:"operator",operator:"changeCase",operatorArgs:{toLower:!0},context:"visual",isEdit:!0},{keys:"U",type:"operator",operator:"changeCase",operatorArgs:{toLower:!1},context:"visual",isEdit:!0},{keys:"<C-r>",type:"action",action:"redo"},{keys:"m<character>",type:"action",action:"setMark"},{keys:'"<character>',type:"action",action:"setRegister"},{keys:"zz",type:"action",action:"scrollToCursor",actionArgs:{position:"center"}},{keys:"z.",type:"action",action:"scrollToCursor",actionArgs:{position:"center"},motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:"zt",type:"action",action:"scrollToCursor",actionArgs:{position:"top"}},{keys:"z<CR>",type:"action",action:"scrollToCursor",actionArgs:{position:"top"},motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:"z-",type:"action",action:"scrollToCursor",actionArgs:{position:"bottom"}},{keys:"zb",type:"action",action:"scrollToCursor",actionArgs:{position:"bottom"},motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:".",type:"action",action:"repeatLastEdit"},{keys:"<C-a>",type:"action",action:"incrementNumberToken",isEdit:!0,actionArgs:{increase:!0,backtrack:!1}},{keys:"<C-x>",type:"action",action:"incrementNumberToken",isEdit:!0,actionArgs:{increase:!1,backtrack:!1}},{keys:"<C-t>",type:"action",action:"indent",actionArgs:{indentRight:!0},context:"insert"},{keys:"<C-d>",type:"action",action:"indent",actionArgs:{indentRight:!1},context:"insert"},{keys:"a<character>",type:"motion",motion:"textObjectManipulation"},{keys:"i<character>",type:"motion",motion:"textObjectManipulation",motionArgs:{textObjectInner:!0}},{keys:"/",type:"search",searchArgs:{forward:!0,querySrc:"prompt",toJumplist:!0}},{keys:"?",type:"search",searchArgs:{forward:!1,querySrc:"prompt",toJumplist:!0}},{keys:"*",type:"search",searchArgs:{forward:!0,querySrc:"wordUnderCursor",wholeWordOnly:!0,toJumplist:!0}},{keys:"#",type:"search",searchArgs:{forward:!1,querySrc:"wordUnderCursor",wholeWordOnly:!0,toJumplist:!0}},{keys:"g*",type:"search",searchArgs:{forward:!0,querySrc:"wordUnderCursor",toJumplist:!0}},{keys:"g#",type:"search",searchArgs:{forward:!1,querySrc:"wordUnderCursor",toJumplist:!0}},{keys:":",type:"ex"}],defaultExCommandMap=[{name:"colorscheme",shortName:"colo"},{name:"map"},{name:"imap",shortName:"im"},{name:"nmap",shortName:"nm"},{name:"vmap",shortName:"vm"},{name:"unmap"},{name:"write",shortName:"w"},{name:"undo",shortName:"u"},{name:"redo",shortName:"red"},{name:"set",shortName:"se"},{name:"set",shortName:"se"},{name:"setlocal",shortName:"setl"},{name:"setglobal",shortName:"setg"},{name:"sort",shortName:"sor"},{name:"substitute",shortName:"s",possiblyAsync:!0},{name:"nohlsearch",shortName:"noh"},{name:"yank",shortName:"y"},{name:"delmarks",shortName:"delm"},{name:"registers",shortName:"reg",excludeFromCommandHistory:!0},{name:"global",shortName:"g"}],Pos=CodeMirror.Pos,Vim=function(){function enterVimMode(cm){cm.setOption("disableInput",!0);cm.setOption("showCursorWhenSelecting",!1);CodeMirror.signal(cm,"vim-mode-change",{mode:"normal"});cm.on("cursorActivity",onCursorActivity);maybeInitVimState(cm);CodeMirror.on(cm.getInputField(),"paste",getOnPasteFn(cm))}function leaveVimMode(cm){cm.setOption("disableInput",!1);cm.off("cursorActivity",onCursorActivity);CodeMirror.off(cm.getInputField(),"paste",getOnPasteFn(cm));cm.state.vim=null}function detachVimMap(cm,next){this==CodeMirror.keyMap.vim&&CodeMirror.rmClass(cm.getWrapperElement(),"cm-fat-cursor");next&&next.attach==attachVimMap||leaveVimMode(cm,!1)}function attachVimMap(cm,prev){this==CodeMirror.keyMap.vim&&CodeMirror.addClass(cm.getWrapperElement(),"cm-fat-cursor");prev&&prev.attach==attachVimMap||enterVimMode(cm)}function cmKey(key,cm){if(cm){if(this[key])return this[key];var vimKey=cmKeyToVimKey(key);if(!vimKey)return!1;var cmd=CodeMirror.Vim.findKey(cm,vimKey);"function"==typeof cmd&&CodeMirror.signal(cm,"vim-keypress",vimKey);return cmd}}function cmKeyToVimKey(key){if("'"==key.charAt(0))return key.charAt(1);var pieces=key.split(/-(?!$)/),lastPiece=pieces[pieces.length-1];if(1==pieces.length&&1==pieces[0].length)return!1;if(2==pieces.length&&"Shift"==pieces[0]&&1==lastPiece.length)return!1;for(var hasCharacter=!1,i=0;i<pieces.length;i++){var piece=pieces[i];piece in modifiers?pieces[i]=modifiers[piece]:hasCharacter=!0;piece in specialKeys&&(pieces[i]=specialKeys[piece])}if(!hasCharacter)return!1;isUpperCase(lastPiece)&&(pieces[pieces.length-1]=lastPiece.toLowerCase());return"<"+pieces.join("-")+">"}function getOnPasteFn(cm){var vim=cm.state.vim;vim.onPasteFn||(vim.onPasteFn=function(){if(!vim.insertMode){cm.setCursor(offsetCursor(cm.getCursor(),0,1));actions.enterInsertMode(cm,{},vim)}});return vim.onPasteFn}function makeKeyRange(start,size){for(var keys=[],i=start;i<start+size;i++)keys.push(String.fromCharCode(i));return keys}function isLine(cm,line){return line>=cm.firstLine()&&line<=cm.lastLine()}function isLowerCase(k){return/^[a-z]$/.test(k)}function isMatchableSymbol(k){return"()[]{}".indexOf(k)!=-1}function isNumber(k){return numberRegex.test(k)}function isUpperCase(k){return/^[A-Z]$/.test(k)}function isWhiteSpaceString(k){return/^\s*$/.test(k)}function inArray(val,arr){for(var i=0;i<arr.length;i++)if(arr[i]==val)return!0;return!1}function defineOption(name,defaultValue,type,aliases,callback){if(void 0===defaultValue&&!callback)throw Error("defaultValue is required unless callback is provided");type||(type="string");options[name]={type:type,defaultValue:defaultValue,callback:callback};if(aliases)for(var i=0;i<aliases.length;i++)options[aliases[i]]=options[name];defaultValue&&setOption(name,defaultValue)}function setOption(name,value,cm,cfg){var option=options[name];cfg=cfg||{};var scope=cfg.scope;if(!option)throw Error("Unknown option: "+name);if("boolean"==option.type){if(value&&value!==!0)throw Error("Invalid argument: "+name+"="+value);value!==!1&&(value=!0)}if(option.callback){"local"!==scope&&option.callback(value,void 0);"global"!==scope&&cm&&option.callback(value,cm)}else{"local"!==scope&&(option.value="boolean"==option.type?!!value:value);"global"!==scope&&cm&&(cm.state.vim.options[name]={value:value})}}function getOption(name,cm,cfg){var option=options[name];cfg=cfg||{};var scope=cfg.scope;if(!option)throw Error("Unknown option: "+name);if(!option.callback){var local="global"!==scope&&cm&&cm.state.vim.options[name];return(local||"local"!==scope&&option||{}).value}var local=cm&&option.callback(void 0,cm);return"global"!==scope&&void 0!==local?local:"local"!==scope?option.callback():void 0}function MacroModeState(){this.latestRegister=void 0;this.isPlaying=!1;this.isRecording=!1;this.replaySearchQueries=[];this.onRecordingDone=void 0;this.lastInsertModeChanges=createInsertModeChanges()}function maybeInitVimState(cm){cm.state.vim||(cm.state.vim={inputState:new InputState,lastEditInputState:void 0,lastEditActionCommand:void 0,lastHPos:-1,lastHSPos:-1,lastMotion:null,marks:{},fakeCursor:null,insertMode:!1,insertModeRepeat:void 0,visualMode:!1,visualLine:!1,visualBlock:!1,lastSelection:null,lastPastedText:null,sel:{},options:{}});return cm.state.vim}function resetVimGlobalState(){vimGlobalState={searchQuery:null,searchIsReversed:!1,lastSubstituteReplacePart:void 0,jumpList:createCircularJumpList(),macroModeState:new MacroModeState,lastCharacterSearch:{increment:0,forward:!0,selectedCharacter:""},registerController:new RegisterController({}),searchHistoryController:new HistoryController({}),exCommandHistoryController:new HistoryController({})};for(var optionName in options){var option=options[optionName];option.value=option.defaultValue}}function InputState(){this.prefixRepeat=[];this.motionRepeat=[];this.operator=null;this.operatorArgs=null;this.motion=null;this.motionArgs=null;this.keyBuffer=[];this.registerName=null}function clearInputState(cm,reason){cm.state.vim.inputState=new InputState;CodeMirror.signal(cm,"vim-command-done",reason)}function Register(text,linewise,blockwise){this.clear();this.keyBuffer=[text||""];this.insertModeChanges=[];this.searchQueries=[];this.linewise=!!linewise;this.blockwise=!!blockwise}function defineRegister(name,register){var registers=vimGlobalState.registerController.registers[name];if(!name||1!=name.length)throw Error("Register name must be 1 character");if(registers[name])throw Error("Register already defined "+name);registers[name]=register;validRegisters.push(name)}function RegisterController(registers){this.registers=registers;this.unnamedRegister=registers['"']=new Register;registers["."]=new Register;registers[":"]=new Register;registers["/"]=new Register}function HistoryController(){this.historyBuffer=[];this.iterator=0;this.initialPrefix=null}function defineMotion(name,fn){motions[name]=fn}function fillArray(val,times){for(var arr=[],i=0;i<times;i++)arr.push(val);return arr}function defineOperator(name,fn){operators[name]=fn}function defineAction(name,fn){actions[name]=fn}function clipCursorToContent(cm,cur,includeLineBreak){var line=Math.min(Math.max(cm.firstLine(),cur.line),cm.lastLine()),maxCh=lineLength(cm,line)-1;maxCh=includeLineBreak?maxCh+1:maxCh;var ch=Math.min(Math.max(0,cur.ch),maxCh);return Pos(line,ch)}function copyArgs(args){var ret={};for(var prop in args)args.hasOwnProperty(prop)&&(ret[prop]=args[prop]);return ret}function offsetCursor(cur,offsetLine,offsetCh){if("object"==typeof offsetLine){offsetCh=offsetLine.ch;offsetLine=offsetLine.line}return Pos(cur.line+offsetLine,cur.ch+offsetCh)}function getOffset(anchor,head){return{line:head.line-anchor.line,ch:head.line-anchor.line}}function commandMatches(keys,keyMap,context,inputState){for(var match,partial=[],full=[],i=0;i<keyMap.length;i++){var command=keyMap[i];if(!("insert"==context&&"insert"!=command.context||command.context&&command.context!=context||inputState.operator&&"action"==command.type)&&(match=commandMatch(keys,command.keys))){"partial"==match&&partial.push(command);"full"==match&&full.push(command)}}return{partial:partial.length&&partial,full:full.length&&full}}function commandMatch(pressed,mapped){if("<character>"==mapped.slice(-11)){var prefixLen=mapped.length-11,pressedPrefix=pressed.slice(0,prefixLen),mappedPrefix=mapped.slice(0,prefixLen);return pressedPrefix==mappedPrefix&&pressed.length>prefixLen?"full":0==mappedPrefix.indexOf(pressedPrefix)&&"partial"}return pressed==mapped?"full":0==mapped.indexOf(pressed)&&"partial"}function lastChar(keys){var match=/^.*(<[\w\-]+>)$/.exec(keys),selectedCharacter=match?match[1]:keys.slice(-1);if(selectedCharacter.length>1)switch(selectedCharacter){case"<CR>":selectedCharacter="\n";break;case"<Space>":selectedCharacter=" "}return selectedCharacter}function repeatFn(cm,fn,repeat){return function(){for(var i=0;i<repeat;i++)fn(cm)}}function copyCursor(cur){return Pos(cur.line,cur.ch)}function cursorEqual(cur1,cur2){return cur1.ch==cur2.ch&&cur1.line==cur2.line}function cursorIsBefore(cur1,cur2){return cur1.line<cur2.line||cur1.line==cur2.line&&cur1.ch<cur2.ch}function cursorMin(cur1,cur2){arguments.length>2&&(cur2=cursorMin.apply(void 0,Array.prototype.slice.call(arguments,1)));return cursorIsBefore(cur1,cur2)?cur1:cur2}function cursorMax(cur1,cur2){arguments.length>2&&(cur2=cursorMax.apply(void 0,Array.prototype.slice.call(arguments,1)));return cursorIsBefore(cur1,cur2)?cur2:cur1}function cursorIsBetween(cur1,cur2,cur3){var cur1before2=cursorIsBefore(cur1,cur2),cur2before3=cursorIsBefore(cur2,cur3);return cur1before2&&cur2before3}function lineLength(cm,lineNum){return cm.getLine(lineNum).length}function trim(s){return s.trim?s.trim():s.replace(/^\s+|\s+$/g,"")}function escapeRegex(s){return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g,"\\$1")}function extendLineToColumn(cm,lineNum,column){var endCh=lineLength(cm,lineNum),spaces=new Array(column-endCh+1).join(" ");cm.setCursor(Pos(lineNum,endCh));cm.replaceRange(spaces,cm.getCursor())}function selectBlock(cm,selectionEnd){var selections=[],ranges=cm.listSelections(),head=copyCursor(cm.clipPos(selectionEnd)),isClipped=!cursorEqual(selectionEnd,head),curHead=cm.getCursor("head"),primIndex=getIndex(ranges,curHead),wasClipped=cursorEqual(ranges[primIndex].head,ranges[primIndex].anchor),max=ranges.length-1,index=max-primIndex>primIndex?max:0,base=ranges[index].anchor,firstLine=Math.min(base.line,head.line),lastLine=Math.max(base.line,head.line),baseCh=base.ch,headCh=head.ch,dir=ranges[index].head.ch-baseCh,newDir=headCh-baseCh;if(dir>0&&newDir<=0){baseCh++;isClipped||headCh--}else if(dir<0&&newDir>=0){baseCh--;wasClipped||headCh++}else if(dir<0&&newDir==-1){baseCh--;headCh++}for(var line=firstLine;line<=lastLine;line++){var range={anchor:new Pos(line,baseCh),head:new Pos(line,headCh)};selections.push(range)}primIndex=head.line==lastLine?selections.length-1:0;cm.setSelections(selections);selectionEnd.ch=headCh;base.ch=baseCh;return base}function selectForInsert(cm,head,height){for(var sel=[],i=0;i<height;i++){var lineHead=offsetCursor(head,i,0);sel.push({anchor:lineHead,head:lineHead})}cm.setSelections(sel,0)}function getIndex(ranges,cursor,end){for(var i=0;i<ranges.length;i++){var atAnchor="head"!=end&&cursorEqual(ranges[i].anchor,cursor),atHead="anchor"!=end&&cursorEqual(ranges[i].head,cursor);if(atAnchor||atHead)return i}return-1}function getSelectedAreaRange(cm,vim){var lastSelection=vim.lastSelection,getCurrentSelectedAreaRange=function(){var selections=cm.listSelections(),start=selections[0],end=selections[selections.length-1],selectionStart=cursorIsBefore(start.anchor,start.head)?start.anchor:start.head,selectionEnd=cursorIsBefore(end.anchor,end.head)?end.head:end.anchor;return[selectionStart,selectionEnd]},getLastSelectedAreaRange=function(){var selectionStart=cm.getCursor(),selectionEnd=cm.getCursor(),block=lastSelection.visualBlock;if(block){var width=block.width,height=block.height;selectionEnd=Pos(selectionStart.line+height,selectionStart.ch+width);for(var selections=[],i=selectionStart.line;i<selectionEnd.line;i++){var anchor=Pos(i,selectionStart.ch),head=Pos(i,selectionEnd.ch),range={anchor:anchor,head:head};selections.push(range)}cm.setSelections(selections)}else{var start=lastSelection.anchorMark.find(),end=lastSelection.headMark.find(),line=end.line-start.line,ch=end.ch-start.ch;selectionEnd={line:selectionEnd.line+line,ch:line?selectionEnd.ch:ch+selectionEnd.ch};if(lastSelection.visualLine){selectionStart=Pos(selectionStart.line,0);selectionEnd=Pos(selectionEnd.line,lineLength(cm,selectionEnd.line))}cm.setSelection(selectionStart,selectionEnd)}return[selectionStart,selectionEnd]};return vim.visualMode?getCurrentSelectedAreaRange():getLastSelectedAreaRange()}function updateLastSelection(cm,vim){var anchor=vim.sel.anchor,head=vim.sel.head;if(vim.lastPastedText){head=cm.posFromIndex(cm.indexFromPos(anchor)+vim.lastPastedText.length);vim.lastPastedText=null}vim.lastSelection={anchorMark:cm.setBookmark(anchor),headMark:cm.setBookmark(head),anchor:copyCursor(anchor),head:copyCursor(head),visualMode:vim.visualMode,visualLine:vim.visualLine,visualBlock:vim.visualBlock}}function expandSelection(cm,start,end){var tmp,sel=cm.state.vim.sel,head=sel.head,anchor=sel.anchor;if(cursorIsBefore(end,start)){tmp=end;end=start;start=tmp}if(cursorIsBefore(head,anchor)){head=cursorMin(start,head);anchor=cursorMax(anchor,end)}else{anchor=cursorMin(start,anchor);head=cursorMax(head,end);head=offsetCursor(head,0,-1);head.ch==-1&&head.line!=cm.firstLine()&&(head=Pos(head.line-1,lineLength(cm,head.line-1)))}return[anchor,head]}function updateCmSelection(cm,sel,mode){var vim=cm.state.vim;sel=sel||vim.sel;var mode=mode||vim.visualLine?"line":vim.visualBlock?"block":"char",cmSel=makeCmSelection(cm,sel,mode);cm.setSelections(cmSel.ranges,cmSel.primary);updateFakeCursor(cm)}function makeCmSelection(cm,sel,mode,exclusive){var head=copyCursor(sel.head),anchor=copyCursor(sel.anchor);if("char"==mode){var headOffset=exclusive||cursorIsBefore(sel.head,sel.anchor)?0:1,anchorOffset=cursorIsBefore(sel.head,sel.anchor)?1:0;head=offsetCursor(sel.head,0,headOffset);anchor=offsetCursor(sel.anchor,0,anchorOffset);return{ranges:[{anchor:anchor,head:head}],primary:0}}if("line"==mode){if(cursorIsBefore(sel.head,sel.anchor)){head.ch=0;anchor.ch=lineLength(cm,anchor.line)}else{anchor.ch=0;var lastLine=cm.lastLine();head.line>lastLine&&(head.line=lastLine);head.ch=lineLength(cm,head.line)}return{ranges:[{anchor:anchor,head:head}],primary:0}}if("block"==mode){for(var top=Math.min(anchor.line,head.line),left=Math.min(anchor.ch,head.ch),bottom=Math.max(anchor.line,head.line),right=Math.max(anchor.ch,head.ch)+1,height=bottom-top+1,primary=head.line==top?0:height-1,ranges=[],i=0;i<height;i++)ranges.push({anchor:Pos(top+i,left),head:Pos(top+i,right)});return{ranges:ranges,primary:primary}}}function getHead(cm){var cur=cm.getCursor("head");1==cm.getSelection().length&&(cur=cursorMin(cur,cm.getCursor("anchor")));return cur}function exitVisualMode(cm,moveHead){var vim=cm.state.vim;moveHead!==!1&&cm.setCursor(clipCursorToContent(cm,vim.sel.head));updateLastSelection(cm,vim);vim.visualMode=!1;vim.visualLine=!1;vim.visualBlock=!1;CodeMirror.signal(cm,"vim-mode-change",{mode:"normal"});vim.fakeCursor&&vim.fakeCursor.clear()}function clipToLine(cm,curStart,curEnd){var selection=cm.getRange(curStart,curEnd);if(/\n\s*$/.test(selection)){var lines=selection.split("\n");lines.pop();for(var line,line=lines.pop();lines.length>0&&line&&isWhiteSpaceString(line);line=lines.pop()){curEnd.line--;curEnd.ch=0}if(line){curEnd.line--;curEnd.ch=lineLength(cm,curEnd.line)}else curEnd.ch=0}}function expandSelectionToLine(_cm,curStart,curEnd){curStart.ch=0;curEnd.ch=0;curEnd.line++}function findFirstNonWhiteSpaceCharacter(text){if(!text)return 0;var firstNonWS=text.search(/\S/);return firstNonWS==-1?text.length:firstNonWS}function expandWordUnderCursor(cm,inclusive,_forward,bigWord,noSymbol){for(var cur=getHead(cm),line=cm.getLine(cur.line),idx=cur.ch,test=noSymbol?wordCharTest[0]:bigWordCharTest[0];!test(line.charAt(idx));){idx++;if(idx>=line.length)return null}if(bigWord)test=bigWordCharTest[0];else{test=wordCharTest[0];test(line.charAt(idx))||(test=wordCharTest[1])}for(var end=idx,start=idx;test(line.charAt(end))&&end<line.length;)end++;for(;test(line.charAt(start))&&start>=0;)start--;start++;if(inclusive){for(var wordEnd=end;/\s/.test(line.charAt(end))&&end<line.length;)end++;if(wordEnd==end){for(var wordStart=start;/\s/.test(line.charAt(start-1))&&start>0;)start--;start||(start=wordStart)}}return{start:Pos(cur.line,start),end:Pos(cur.line,end)}}function recordJumpPosition(cm,oldCur,newCur){cursorEqual(oldCur,newCur)||vimGlobalState.jumpList.add(cm,oldCur,newCur)}function recordLastCharacterSearch(increment,args){vimGlobalState.lastCharacterSearch.increment=increment;vimGlobalState.lastCharacterSearch.forward=args.forward;vimGlobalState.lastCharacterSearch.selectedCharacter=args.selectedCharacter}function findSymbol(cm,repeat,forward,symb){var cur=copyCursor(cm.getCursor()),increment=forward?1:-1,endLine=forward?cm.lineCount():-1,curCh=cur.ch,line=cur.line,lineText=cm.getLine(line),state={lineText:lineText,nextCh:lineText.charAt(curCh),lastCh:null,index:curCh,symb:symb,reverseSymb:(forward?{")":"(","}":"{"}:{"(":")","{":"}"})[symb],forward:forward,depth:0,curMoveThrough:!1},mode=symbolToMode[symb];if(!mode)return cur;var init=findSymbolModes[mode].init,isComplete=findSymbolModes[mode].isComplete;init&&init(state);for(;line!==endLine&&repeat;){state.index+=increment;state.nextCh=state.lineText.charAt(state.index);if(!state.nextCh){line+=increment;state.lineText=cm.getLine(line)||"";if(increment>0)state.index=0;else{var lineLen=state.lineText.length;state.index=lineLen>0?lineLen-1:0}state.nextCh=state.lineText.charAt(state.index)}if(isComplete(state)){cur.line=line;cur.ch=state.index;repeat--}}return state.nextCh||state.curMoveThrough?Pos(line,state.index):cur}function findWord(cm,cur,forward,bigWord,emptyLineIsWord){var lineNum=cur.line,pos=cur.ch,line=cm.getLine(lineNum),dir=forward?1:-1,charTests=bigWord?bigWordCharTest:wordCharTest;if(emptyLineIsWord&&""==line){lineNum+=dir;line=cm.getLine(lineNum);if(!isLine(cm,lineNum))return null;pos=forward?0:line.length}for(;;){if(emptyLineIsWord&&""==line)return{from:0,to:0,line:lineNum};for(var stop=dir>0?line.length:-1,wordStart=stop,wordEnd=stop;pos!=stop;){for(var foundWord=!1,i=0;i<charTests.length&&!foundWord;++i)if(charTests[i](line.charAt(pos))){wordStart=pos;for(;pos!=stop&&charTests[i](line.charAt(pos));)pos+=dir;wordEnd=pos;foundWord=wordStart!=wordEnd;if(wordStart==cur.ch&&lineNum==cur.line&&wordEnd==wordStart+dir)continue;return{from:Math.min(wordStart,wordEnd+1),to:Math.max(wordStart,wordEnd),line:lineNum}}foundWord||(pos+=dir)}lineNum+=dir;if(!isLine(cm,lineNum))return null;line=cm.getLine(lineNum);pos=dir>0?0:line.length}}function moveToWord(cm,cur,repeat,forward,wordEnd,bigWord){var curStart=copyCursor(cur),words=[];(forward&&!wordEnd||!forward&&wordEnd)&&repeat++;for(var emptyLineIsWord=!(forward&&wordEnd),i=0;i<repeat;i++){var word=findWord(cm,cur,forward,bigWord,emptyLineIsWord);if(!word){var eodCh=lineLength(cm,cm.lastLine());words.push(forward?{line:cm.lastLine(),from:eodCh,to:eodCh}:{line:0,from:0,to:0});break}words.push(word);cur=Pos(word.line,forward?word.to-1:word.from)}var shortCircuit=words.length!=repeat,firstWord=words[0],lastWord=words.pop();if(forward&&!wordEnd){shortCircuit||firstWord.from==curStart.ch&&firstWord.line==curStart.line||(lastWord=words.pop());return Pos(lastWord.line,lastWord.from)}if(forward&&wordEnd)return Pos(lastWord.line,lastWord.to-1);if(!forward&&wordEnd){shortCircuit||firstWord.to==curStart.ch&&firstWord.line==curStart.line||(lastWord=words.pop());return Pos(lastWord.line,lastWord.to)}return Pos(lastWord.line,lastWord.from)}function moveToCharacter(cm,repeat,forward,character){for(var idx,cur=cm.getCursor(),start=cur.ch,i=0;i<repeat;i++){
2
+ var line=cm.getLine(cur.line);idx=charIdxInLine(start,line,character,forward,!0);if(idx==-1)return null;start=idx}return Pos(cm.getCursor().line,idx)}function moveToColumn(cm,repeat){var line=cm.getCursor().line;return clipCursorToContent(cm,Pos(line,repeat-1))}function updateMark(cm,vim,markName,pos){if(inArray(markName,validMarks)){vim.marks[markName]&&vim.marks[markName].clear();vim.marks[markName]=cm.setBookmark(pos)}}function charIdxInLine(start,line,character,forward,includeChar){var idx;if(forward){idx=line.indexOf(character,start+1);idx==-1||includeChar||(idx-=1)}else{idx=line.lastIndexOf(character,start-1);idx==-1||includeChar||(idx+=1)}return idx}function findParagraph(cm,head,repeat,dir,inclusive){function isEmpty(i){return!cm.getLine(i)}function isBoundary(i,dir,any){return any?isEmpty(i)!=isEmpty(i+dir):!isEmpty(i)&&isEmpty(i+dir)}var start,end,line=head.line,min=cm.firstLine(),max=cm.lastLine(),i=line;if(dir){for(;min<=i&&i<=max&&repeat>0;){isBoundary(i,dir)&&repeat--;i+=dir}return new Pos(i,0)}var vim=cm.state.vim;if(vim.visualLine&&isBoundary(line,1,!0)){var anchor=vim.sel.anchor;isBoundary(anchor.line,-1,!0)&&(inclusive&&anchor.line==line||(line+=1))}var startState=isEmpty(line);for(i=line;i<=max&&repeat;i++)isBoundary(i,1,!0)&&(inclusive&&isEmpty(i)==startState||repeat--);end=new Pos(i,0);i>max&&!startState?startState=!0:inclusive=!1;for(i=line;i>min&&(inclusive&&isEmpty(i)!=startState&&i!=line||!isBoundary(i,-1,!0));i--);start=new Pos(i,0);return{start:start,end:end}}function selectCompanionObject(cm,head,symb,inclusive){var start,end,cur=head,bracketRegexp={"(":/[()]/,")":/[()]/,"[":/[[\]]/,"]":/[[\]]/,"{":/[{}]/,"}":/[{}]/}[symb],openSym={"(":"(",")":"(","[":"[","]":"[","{":"{","}":"{"}[symb],curChar=cm.getLine(cur.line).charAt(cur.ch),offset=curChar===openSym?1:0;start=cm.scanForBracket(Pos(cur.line,cur.ch+offset),-1,null,{bracketRegex:bracketRegexp});end=cm.scanForBracket(Pos(cur.line,cur.ch+offset),1,null,{bracketRegex:bracketRegexp});if(!start||!end)return{start:cur,end:cur};start=start.pos;end=end.pos;if(start.line==end.line&&start.ch>end.ch||start.line>end.line){var tmp=start;start=end;end=tmp}inclusive?end.ch+=1:start.ch+=1;return{start:start,end:end}}function findBeginningAndEnd(cm,head,symb,inclusive){var start,end,i,len,cur=copyCursor(head),line=cm.getLine(cur.line),chars=line.split(""),firstIndex=chars.indexOf(symb);if(cur.ch<firstIndex)cur.ch=firstIndex;else if(firstIndex<cur.ch&&chars[cur.ch]==symb){end=cur.ch;--cur.ch}if(chars[cur.ch]!=symb||end)for(i=cur.ch;i>-1&&!start;i--)chars[i]==symb&&(start=i+1);else start=cur.ch+1;if(start&&!end)for(i=start,len=chars.length;i<len&&!end;i++)chars[i]==symb&&(end=i);if(!start||!end)return{start:cur,end:cur};if(inclusive){--start;++end}return{start:Pos(cur.line,start),end:Pos(cur.line,end)}}function SearchState(){}function getSearchState(cm){var vim=cm.state.vim;return vim.searchState_||(vim.searchState_=new SearchState)}function dialog(cm,template,shortText,onClose,options){cm.openDialog?cm.openDialog(template,onClose,{bottom:!0,value:options.value,onKeyDown:options.onKeyDown,onKeyUp:options.onKeyUp,selectValueOnOpen:!1}):onClose(prompt(shortText,""))}function splitBySlash(argString){var slashes=findUnescapedSlashes(argString)||[];if(!slashes.length)return[];var tokens=[];if(0===slashes[0]){for(var i=0;i<slashes.length;i++)"number"==typeof slashes[i]&&tokens.push(argString.substring(slashes[i]+1,slashes[i+1]));return tokens}}function findUnescapedSlashes(str){for(var escapeNextChar=!1,slashes=[],i=0;i<str.length;i++){var c=str.charAt(i);escapeNextChar||"/"!=c||slashes.push(i);escapeNextChar=!escapeNextChar&&"\\"==c}return slashes}function translateRegex(str){for(var specials="|(){",unescape="}",escapeNextChar=!1,out=[],i=-1;i<str.length;i++){var c=str.charAt(i)||"",n=str.charAt(i+1)||"",specialComesNext=n&&specials.indexOf(n)!=-1;if(escapeNextChar){"\\"===c&&specialComesNext||out.push(c);escapeNextChar=!1}else if("\\"===c){escapeNextChar=!0;n&&unescape.indexOf(n)!=-1&&(specialComesNext=!0);specialComesNext&&"\\"!==n||out.push(c)}else{out.push(c);specialComesNext&&"\\"!==n&&out.push("\\")}}return out.join("")}function translateRegexReplace(str){for(var escapeNextChar=!1,out=[],i=-1;i<str.length;i++){var c=str.charAt(i)||"",n=str.charAt(i+1)||"";if(charUnescapes[c+n]){out.push(charUnescapes[c+n]);i++}else if(escapeNextChar){out.push(c);escapeNextChar=!1}else if("\\"===c){escapeNextChar=!0;isNumber(n)||"$"===n?out.push("$"):"/"!==n&&"\\"!==n&&out.push("\\")}else{"$"===c&&out.push("$");out.push(c);"/"===n&&out.push("\\")}}return out.join("")}function unescapeRegexReplace(str){for(var stream=new CodeMirror.StringStream(str),output=[];!stream.eol();){for(;stream.peek()&&"\\"!=stream.peek();)output.push(stream.next());var matched=!1;for(var matcher in unescapes)if(stream.match(matcher,!0)){matched=!0;output.push(unescapes[matcher]);break}matched||output.push(stream.next())}return output.join("")}function parseQuery(query,ignoreCase,smartCase){var lastSearchRegister=vimGlobalState.registerController.getRegister("/");lastSearchRegister.setText(query);if(query instanceof RegExp)return query;var regexPart,forceIgnoreCase,slashes=findUnescapedSlashes(query);if(slashes.length){regexPart=query.substring(0,slashes[0]);var flagsPart=query.substring(slashes[0]);forceIgnoreCase=flagsPart.indexOf("i")!=-1}else regexPart=query;if(!regexPart)return null;getOption("pcre")||(regexPart=translateRegex(regexPart));smartCase&&(ignoreCase=/^[^A-Z]*$/.test(regexPart));var regexp=new RegExp(regexPart,ignoreCase||forceIgnoreCase?"i":void 0);return regexp}function showConfirm(cm,text){cm.openNotification?cm.openNotification('<span style="color: red">'+text+"</span>",{bottom:!0,duration:5e3}):alert(text)}function makePrompt(prefix,desc){var raw='<span style="font-family: monospace; white-space: pre">'+(prefix||"")+'<input type="text"></span>';desc&&(raw+=' <span style="color: #888">'+desc+"</span>");return raw}function showPrompt(cm,options){var shortText=(options.prefix||"")+" "+(options.desc||""),prompt=makePrompt(options.prefix,options.desc);dialog(cm,prompt,shortText,options.onClose,options)}function regexEqual(r1,r2){if(r1 instanceof RegExp&&r2 instanceof RegExp){for(var props=["global","multiline","ignoreCase","source"],i=0;i<props.length;i++){var prop=props[i];if(r1[prop]!==r2[prop])return!1}return!0}return!1}function updateSearchQuery(cm,rawQuery,ignoreCase,smartCase){if(rawQuery){var state=getSearchState(cm),query=parseQuery(rawQuery,!!ignoreCase,!!smartCase);if(query){highlightSearchMatches(cm,query);if(regexEqual(query,state.getQuery()))return query;state.setQuery(query);return query}}}function searchOverlay(query){if("^"==query.source.charAt(0))var matchSol=!0;return{token:function(stream){if(!matchSol||stream.sol()){var match=stream.match(query,!1);if(match){if(0==match[0].length){stream.next();return"searching"}if(!stream.sol()){stream.backUp(1);if(!query.exec(stream.next()+match[0])){stream.next();return null}}stream.match(query);return"searching"}for(;!stream.eol();){stream.next();if(stream.match(query,!1))break}}else stream.skipToEnd()},query:query}}function highlightSearchMatches(cm,query){var searchState=getSearchState(cm),overlay=searchState.getOverlay();if(!overlay||query!=overlay.query){overlay&&cm.removeOverlay(overlay);overlay=searchOverlay(query);cm.addOverlay(overlay);if(cm.showMatchesOnScrollbar){searchState.getScrollbarAnnotate()&&searchState.getScrollbarAnnotate().clear();searchState.setScrollbarAnnotate(cm.showMatchesOnScrollbar(query))}searchState.setOverlay(overlay)}}function findNext(cm,prev,query,repeat){void 0===repeat&&(repeat=1);return cm.operation(function(){for(var pos=cm.getCursor(),cursor=cm.getSearchCursor(query,pos),i=0;i<repeat;i++){var found=cursor.find(prev);0==i&&found&&cursorEqual(cursor.from(),pos)&&(found=cursor.find(prev));if(!found){cursor=cm.getSearchCursor(query,prev?Pos(cm.lastLine()):Pos(cm.firstLine(),0));if(!cursor.find(prev))return}}return cursor.from()})}function clearSearchHighlight(cm){var state=getSearchState(cm);cm.removeOverlay(getSearchState(cm).getOverlay());state.setOverlay(null);if(state.getScrollbarAnnotate()){state.getScrollbarAnnotate().clear();state.setScrollbarAnnotate(null)}}function isInRange(pos,start,end){"number"!=typeof pos&&(pos=pos.line);return start instanceof Array?inArray(pos,start):end?pos>=start&&pos<=end:pos==start}function getUserVisibleLines(cm){var scrollInfo=cm.getScrollInfo(),occludeToleranceTop=6,occludeToleranceBottom=10,from=cm.coordsChar({left:0,top:occludeToleranceTop+scrollInfo.top},"local"),bottomY=scrollInfo.clientHeight-occludeToleranceBottom+scrollInfo.top,to=cm.coordsChar({left:0,top:bottomY},"local");return{top:from.line,bottom:to.line}}function doReplace(cm,confirm,global,lineStart,lineEnd,searchCursor,query,replaceWith,callback){function replaceAll(){cm.operation(function(){for(;!done;){replace();next()}stop()})}function replace(){var text=cm.getRange(searchCursor.from(),searchCursor.to()),newText=text.replace(query,replaceWith);searchCursor.replace(newText)}function next(){for(;searchCursor.findNext()&&isInRange(searchCursor.from(),lineStart,lineEnd);)if(global||!lastPos||searchCursor.from().line!=lastPos.line){cm.scrollIntoView(searchCursor.from(),30);cm.setSelection(searchCursor.from(),searchCursor.to());lastPos=searchCursor.from();done=!1;return}done=!0}function stop(close){close&&close();cm.focus();if(lastPos){cm.setCursor(lastPos);var vim=cm.state.vim;vim.exMode=!1;vim.lastHPos=vim.lastHSPos=lastPos.ch}callback&&callback()}function onPromptKeyDown(e,_value,close){CodeMirror.e_stop(e);var keyName=CodeMirror.keyName(e);switch(keyName){case"Y":replace();next();break;case"N":next();break;case"A":var savedCallback=callback;callback=void 0;cm.operation(replaceAll);callback=savedCallback;break;case"L":replace();case"Q":case"Esc":case"Ctrl-C":case"Ctrl-[":stop(close)}done&&stop(close);return!0}cm.state.vim.exMode=!0;var done=!1,lastPos=searchCursor.from();next();if(done)showConfirm(cm,"No matches for "+query.source);else if(confirm)showPrompt(cm,{prefix:"replace with <strong>"+replaceWith+"</strong> (y/n/a/q/l)",onKeyDown:onPromptKeyDown});else{replaceAll();callback&&callback()}}function exitInsertMode(cm){var vim=cm.state.vim,macroModeState=vimGlobalState.macroModeState,insertModeChangeRegister=vimGlobalState.registerController.getRegister("."),isPlaying=macroModeState.isPlaying,lastChange=macroModeState.lastInsertModeChanges,text=[];if(!isPlaying){for(var selLength=lastChange.inVisualBlock?vim.lastSelection.visualBlock.height:1,changes=lastChange.changes,text=[],i=0;i<changes.length;){text.push(changes[i]);changes[i]instanceof InsertModeKey?i++:i+=selLength}lastChange.changes=text;cm.off("change",onChange);CodeMirror.off(cm.getInputField(),"keydown",onKeyEventTargetKeyDown)}if(!isPlaying&&vim.insertModeRepeat>1){repeatLastEdit(cm,vim,vim.insertModeRepeat-1,!0);vim.lastEditInputState.repeatOverride=vim.insertModeRepeat}delete vim.insertModeRepeat;vim.insertMode=!1;cm.setCursor(cm.getCursor().line,cm.getCursor().ch-1);cm.setOption("keyMap","vim");cm.setOption("disableInput",!0);cm.toggleOverwrite(!1);insertModeChangeRegister.setText(lastChange.changes.join(""));CodeMirror.signal(cm,"vim-mode-change",{mode:"normal"});macroModeState.isRecording&&logInsertModeChange(macroModeState)}function _mapCommand(command){defaultKeymap.unshift(command)}function mapCommand(keys,type,name,args,extra){var command={keys:keys,type:type};command[type]=name;command[type+"Args"]=args;for(var key in extra)command[key]=extra[key];_mapCommand(command)}function executeMacroRegister(cm,vim,macroModeState,registerName){var register=vimGlobalState.registerController.getRegister(registerName);if(":"!=registerName){var keyBuffer=register.keyBuffer,imc=0;macroModeState.isPlaying=!0;macroModeState.replaySearchQueries=register.searchQueries.slice(0);for(var i=0;i<keyBuffer.length;i++)for(var match,key,text=keyBuffer[i];text;){match=/<\w+-.+?>|<\w+>|./.exec(text);key=match[0];text=text.substring(match.index+key.length);CodeMirror.Vim.handleKey(cm,key,"macro");if(vim.insertMode){var changes=register.insertModeChanges[imc++].changes;vimGlobalState.macroModeState.lastInsertModeChanges.changes=changes;repeatInsertModeChanges(cm,changes,1);exitInsertMode(cm)}}macroModeState.isPlaying=!1}else{register.keyBuffer[0]&&exCommandDispatcher.processCommand(cm,register.keyBuffer[0]);macroModeState.isPlaying=!1}}function logKey(macroModeState,key){if(!macroModeState.isPlaying){var registerName=macroModeState.latestRegister,register=vimGlobalState.registerController.getRegister(registerName);register&&register.pushText(key)}}function logInsertModeChange(macroModeState){if(!macroModeState.isPlaying){var registerName=macroModeState.latestRegister,register=vimGlobalState.registerController.getRegister(registerName);register&&register.pushInsertModeChanges&&register.pushInsertModeChanges(macroModeState.lastInsertModeChanges)}}function logSearchQuery(macroModeState,query){if(!macroModeState.isPlaying){var registerName=macroModeState.latestRegister,register=vimGlobalState.registerController.getRegister(registerName);register&&register.pushSearchQuery&&register.pushSearchQuery(query)}}function onChange(_cm,changeObj){var macroModeState=vimGlobalState.macroModeState,lastChange=macroModeState.lastInsertModeChanges;if(!macroModeState.isPlaying)for(;changeObj;){lastChange.expectCursorActivityForChange=!0;if("+input"==changeObj.origin||"paste"==changeObj.origin||void 0===changeObj.origin){var text=changeObj.text.join("\n");if(lastChange.maybeReset){lastChange.changes=[];lastChange.maybeReset=!1}lastChange.changes.push(text)}changeObj=changeObj.next}}function onCursorActivity(cm){var vim=cm.state.vim;if(vim.insertMode){var macroModeState=vimGlobalState.macroModeState;if(macroModeState.isPlaying)return;var lastChange=macroModeState.lastInsertModeChanges;lastChange.expectCursorActivityForChange?lastChange.expectCursorActivityForChange=!1:lastChange.maybeReset=!0}else cm.curOp.isVimOp||handleExternalSelection(cm,vim);vim.visualMode&&updateFakeCursor(cm)}function updateFakeCursor(cm){var vim=cm.state.vim,from=clipCursorToContent(cm,copyCursor(vim.sel.head)),to=offsetCursor(from,0,1);vim.fakeCursor&&vim.fakeCursor.clear();vim.fakeCursor=cm.markText(from,to,{className:"cm-animate-fat-cursor"})}function handleExternalSelection(cm,vim){var anchor=cm.getCursor("anchor"),head=cm.getCursor("head");if(vim.visualMode&&!cm.somethingSelected())exitVisualMode(cm,!1);else if(!vim.visualMode&&!vim.insertMode&&cm.somethingSelected()){vim.visualMode=!0;vim.visualLine=!1;CodeMirror.signal(cm,"vim-mode-change",{mode:"visual"})}if(vim.visualMode){var headOffset=cursorIsBefore(head,anchor)?0:-1,anchorOffset=cursorIsBefore(head,anchor)?-1:0;head=offsetCursor(head,0,headOffset);anchor=offsetCursor(anchor,0,anchorOffset);vim.sel={anchor:anchor,head:head};updateMark(cm,vim,"<",cursorMin(head,anchor));updateMark(cm,vim,">",cursorMax(head,anchor))}else vim.insertMode||(vim.lastHPos=cm.getCursor().ch)}function InsertModeKey(keyName){this.keyName=keyName}function onKeyEventTargetKeyDown(e){function onKeyFound(){if(lastChange.maybeReset){lastChange.changes=[];lastChange.maybeReset=!1}lastChange.changes.push(new InsertModeKey(keyName));return!0}var macroModeState=vimGlobalState.macroModeState,lastChange=macroModeState.lastInsertModeChanges,keyName=CodeMirror.keyName(e);keyName&&(keyName.indexOf("Delete")==-1&&keyName.indexOf("Backspace")==-1||CodeMirror.lookupKey(keyName,"vim-insert",onKeyFound))}function repeatLastEdit(cm,vim,repeat,repeatForInsert){function repeatCommand(){isAction?commandDispatcher.processAction(cm,vim,vim.lastEditActionCommand):commandDispatcher.evalInput(cm,vim)}function repeatInsert(repeat){if(macroModeState.lastInsertModeChanges.changes.length>0){repeat=vim.lastEditActionCommand?repeat:1;var changeObject=macroModeState.lastInsertModeChanges;repeatInsertModeChanges(cm,changeObject.changes,repeat)}}var macroModeState=vimGlobalState.macroModeState;macroModeState.isPlaying=!0;var isAction=!!vim.lastEditActionCommand,cachedInputState=vim.inputState;vim.inputState=vim.lastEditInputState;if(isAction&&vim.lastEditActionCommand.interlaceInsertRepeat)for(var i=0;i<repeat;i++){repeatCommand();repeatInsert(1)}else{repeatForInsert||repeatCommand();repeatInsert(repeat)}vim.inputState=cachedInputState;vim.insertMode&&!repeatForInsert&&exitInsertMode(cm);macroModeState.isPlaying=!1}function repeatInsertModeChanges(cm,changes,repeat){function keyHandler(binding){"string"==typeof binding?CodeMirror.commands[binding](cm):binding(cm);return!0}var head=cm.getCursor("head"),inVisualBlock=vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock;if(inVisualBlock){var vim=cm.state.vim,lastSel=vim.lastSelection,offset=getOffset(lastSel.anchor,lastSel.head);selectForInsert(cm,head,offset.line+1);repeat=cm.listSelections().length;cm.setCursor(head)}for(var i=0;i<repeat;i++){inVisualBlock&&cm.setCursor(offsetCursor(head,i,0));for(var j=0;j<changes.length;j++){var change=changes[j];if(change instanceof InsertModeKey)CodeMirror.lookupKey(change.keyName,"vim-insert",keyHandler);else{var cur=cm.getCursor();cm.replaceRange(change,cur,cur)}}}inVisualBlock&&cm.setCursor(offsetCursor(head,0,1))}CodeMirror.defineOption("vimMode",!1,function(cm,val,prev){val&&"vim"!=cm.getOption("keyMap")?cm.setOption("keyMap","vim"):!val&&prev!=CodeMirror.Init&&/^vim/.test(cm.getOption("keyMap"))&&cm.setOption("keyMap","default")});var modifiers={Shift:"S",Ctrl:"C",Alt:"A",Cmd:"D",Mod:"A"},specialKeys={Enter:"CR",Backspace:"BS",Delete:"Del",Insert:"Ins"},numberRegex=/[\d]/,wordCharTest=[CodeMirror.isWordChar,function(ch){return ch&&!CodeMirror.isWordChar(ch)&&!/\s/.test(ch)}],bigWordCharTest=[function(ch){return/\S/.test(ch)}],upperCaseAlphabet=makeKeyRange(65,26),lowerCaseAlphabet=makeKeyRange(97,26),numbers=makeKeyRange(48,10),validMarks=[].concat(upperCaseAlphabet,lowerCaseAlphabet,numbers,["<",">"]),validRegisters=[].concat(upperCaseAlphabet,lowerCaseAlphabet,numbers,["-",'"',".",":","/"]),options={};defineOption("filetype",void 0,"string",["ft"],function(name,cm){if(void 0!==cm){if(void 0===name){var mode=cm.getOption("mode");return"null"==mode?"":mode}var mode=""==name?"null":name;cm.setOption("mode",mode)}});var createCircularJumpList=function(){function add(cm,oldCur,newCur){function useNextSlot(cursor){var next=++pointer%size,trashMark=buffer[next];trashMark&&trashMark.clear();buffer[next]=cm.setBookmark(cursor)}var current=pointer%size,curMark=buffer[current];if(curMark){var markPos=curMark.find();markPos&&!cursorEqual(markPos,oldCur)&&useNextSlot(oldCur)}else useNextSlot(oldCur);useNextSlot(newCur);head=pointer;tail=pointer-size+1;tail<0&&(tail=0)}function move(cm,offset){pointer+=offset;pointer>head?pointer=head:pointer<tail&&(pointer=tail);var mark=buffer[(size+pointer)%size];if(mark&&!mark.find()){var newCur,inc=offset>0?1:-1,oldCur=cm.getCursor();do{pointer+=inc;mark=buffer[(size+pointer)%size];if(mark&&(newCur=mark.find())&&!cursorEqual(oldCur,newCur))break}while(pointer<head&&pointer>tail)}return mark}var size=100,pointer=-1,head=0,tail=0,buffer=new Array(size);return{cachedCursor:void 0,add:add,move:move}},createInsertModeChanges=function(c){return c?{changes:c.changes,expectCursorActivityForChange:c.expectCursorActivityForChange}:{changes:[],expectCursorActivityForChange:!1}};MacroModeState.prototype={exitMacroRecordMode:function(){var macroModeState=vimGlobalState.macroModeState;macroModeState.onRecordingDone&&macroModeState.onRecordingDone();macroModeState.onRecordingDone=void 0;macroModeState.isRecording=!1},enterMacroRecordMode:function(cm,registerName){var register=vimGlobalState.registerController.getRegister(registerName);if(register){register.clear();this.latestRegister=registerName;cm.openDialog&&(this.onRecordingDone=cm.openDialog("(recording)["+registerName+"]",null,{bottom:!0}));this.isRecording=!0}}};var vimGlobalState,lastInsertModeKeyTimer,vimApi={buildKeyMap:function(){},getRegisterController:function(){return vimGlobalState.registerController},resetVimGlobalState_:resetVimGlobalState,getVimGlobalState_:function(){return vimGlobalState},maybeInitVimState_:maybeInitVimState,suppressErrorLogging:!1,InsertModeKey:InsertModeKey,map:function(lhs,rhs,ctx){exCommandDispatcher.map(lhs,rhs,ctx)},unmap:function(lhs,ctx){exCommandDispatcher.unmap(lhs,ctx)},setOption:setOption,getOption:getOption,defineOption:defineOption,defineEx:function(name,prefix,func){if(prefix){if(0!==name.indexOf(prefix))throw new Error('(Vim.defineEx) "'+prefix+'" is not a prefix of "'+name+'", command not registered')}else prefix=name;exCommands[name]=func;exCommandDispatcher.commandMap_[prefix]={name:name,shortName:prefix,type:"api"}},handleKey:function(cm,key,origin){var command=this.findKey(cm,key,origin);if("function"==typeof command)return command()},findKey:function(cm,key,origin){function handleMacroRecording(){var macroModeState=vimGlobalState.macroModeState;if(macroModeState.isRecording){if("q"==key){macroModeState.exitMacroRecordMode();clearInputState(cm);return!0}"mapping"!=origin&&logKey(macroModeState,key)}}function handleEsc(){if("<Esc>"==key){clearInputState(cm);vim.visualMode?exitVisualMode(cm):vim.insertMode&&exitInsertMode(cm);return!0}}function doKeyToKey(keys){for(var match;keys;){match=/<\w+-.+?>|<\w+>|./.exec(keys);key=match[0];keys=keys.substring(match.index+key.length);CodeMirror.Vim.handleKey(cm,key,"mapping")}}function handleKeyInsertMode(){if(handleEsc())return!0;for(var keys=vim.inputState.keyBuffer=vim.inputState.keyBuffer+key,keysAreChars=1==key.length,match=commandDispatcher.matchCommand(keys,defaultKeymap,vim.inputState,"insert");keys.length>1&&"full"!=match.type;){var keys=vim.inputState.keyBuffer=keys.slice(1),thisMatch=commandDispatcher.matchCommand(keys,defaultKeymap,vim.inputState,"insert");"none"!=thisMatch.type&&(match=thisMatch)}if("none"==match.type){clearInputState(cm);return!1}if("partial"==match.type){lastInsertModeKeyTimer&&window.clearTimeout(lastInsertModeKeyTimer);lastInsertModeKeyTimer=window.setTimeout(function(){vim.insertMode&&vim.inputState.keyBuffer&&clearInputState(cm)},getOption("insertModeEscKeysTimeout"));return!keysAreChars}lastInsertModeKeyTimer&&window.clearTimeout(lastInsertModeKeyTimer);if(keysAreChars){for(var selections=cm.listSelections(),i=0;i<selections.length;i++){var here=selections[i].head;cm.replaceRange("",offsetCursor(here,0,-(keys.length-1)),here,"+input")}vimGlobalState.macroModeState.lastInsertModeChanges.changes.pop()}clearInputState(cm);return match.command}function handleKeyNonInsertMode(){if(handleMacroRecording()||handleEsc())return!0;var keys=vim.inputState.keyBuffer=vim.inputState.keyBuffer+key;if(/^[1-9]\d*$/.test(keys))return!0;var keysMatcher=/^(\d*)(.*)$/.exec(keys);if(!keysMatcher){clearInputState(cm);return!1}var context=vim.visualMode?"visual":"normal",match=commandDispatcher.matchCommand(keysMatcher[2]||keysMatcher[1],defaultKeymap,vim.inputState,context);if("none"==match.type){clearInputState(cm);return!1}if("partial"==match.type)return!0;vim.inputState.keyBuffer="";var keysMatcher=/^(\d*)(.*)$/.exec(keys);keysMatcher[1]&&"0"!=keysMatcher[1]&&vim.inputState.pushRepeatDigit(keysMatcher[1]);return match.command}var command,vim=maybeInitVimState(cm);command=vim.insertMode?handleKeyInsertMode():handleKeyNonInsertMode();return command===!1?void 0:command===!0?function(){return!0}:function(){return cm.operation(function(){cm.curOp.isVimOp=!0;try{"keyToKey"==command.type?doKeyToKey(command.toKeys):commandDispatcher.processCommand(cm,vim,command)}catch(e){cm.state.vim=void 0;maybeInitVimState(cm);CodeMirror.Vim.suppressErrorLogging||console.log(e);throw e}return!0})}},handleEx:function(cm,input){exCommandDispatcher.processCommand(cm,input)},defineMotion:defineMotion,defineAction:defineAction,defineOperator:defineOperator,mapCommand:mapCommand,_mapCommand:_mapCommand,defineRegister:defineRegister,exitVisualMode:exitVisualMode,exitInsertMode:exitInsertMode};InputState.prototype.pushRepeatDigit=function(n){this.operator?this.motionRepeat=this.motionRepeat.concat(n):this.prefixRepeat=this.prefixRepeat.concat(n)};InputState.prototype.getRepeat=function(){var repeat=0;if(this.prefixRepeat.length>0||this.motionRepeat.length>0){repeat=1;this.prefixRepeat.length>0&&(repeat*=parseInt(this.prefixRepeat.join(""),10));this.motionRepeat.length>0&&(repeat*=parseInt(this.motionRepeat.join(""),10))}return repeat};Register.prototype={setText:function(text,linewise,blockwise){this.keyBuffer=[text||""];this.linewise=!!linewise;this.blockwise=!!blockwise},pushText:function(text,linewise){if(linewise){this.linewise||this.keyBuffer.push("\n");this.linewise=!0}this.keyBuffer.push(text)},pushInsertModeChanges:function(changes){this.insertModeChanges.push(createInsertModeChanges(changes))},pushSearchQuery:function(query){this.searchQueries.push(query)},clear:function(){this.keyBuffer=[];this.insertModeChanges=[];this.searchQueries=[];this.linewise=!1},toString:function(){return this.keyBuffer.join("")}};RegisterController.prototype={pushText:function(registerName,operator,text,linewise,blockwise){linewise&&"\n"==text.charAt(0)&&(text=text.slice(1)+"\n");linewise&&"\n"!==text.charAt(text.length-1)&&(text+="\n");var register=this.isValidRegister(registerName)?this.getRegister(registerName):null;if(register){var append=isUpperCase(registerName);append?register.pushText(text,linewise):register.setText(text,linewise,blockwise);this.unnamedRegister.setText(register.toString(),linewise)}else{switch(operator){case"yank":this.registers[0]=new Register(text,linewise,blockwise);break;case"delete":case"change":if(text.indexOf("\n")==-1)this.registers["-"]=new Register(text,linewise);else{this.shiftNumericRegisters_();this.registers[1]=new Register(text,linewise)}}this.unnamedRegister.setText(text,linewise,blockwise)}},getRegister:function(name){if(!this.isValidRegister(name))return this.unnamedRegister;name=name.toLowerCase();this.registers[name]||(this.registers[name]=new Register);return this.registers[name]},isValidRegister:function(name){return name&&inArray(name,validRegisters)},shiftNumericRegisters_:function(){for(var i=9;i>=2;i--)this.registers[i]=this.getRegister(""+(i-1))}};HistoryController.prototype={nextMatch:function(input,up){var historyBuffer=this.historyBuffer,dir=up?-1:1;null===this.initialPrefix&&(this.initialPrefix=input);for(var i=this.iterator+dir;up?i>=0:i<historyBuffer.length;i+=dir)for(var element=historyBuffer[i],j=0;j<=element.length;j++)if(this.initialPrefix==element.substring(0,j)){this.iterator=i;return element}if(i>=historyBuffer.length){this.iterator=historyBuffer.length;return this.initialPrefix}if(i<0)return input},pushInput:function(input){var index=this.historyBuffer.indexOf(input);index>-1&&this.historyBuffer.splice(index,1);input.length&&this.historyBuffer.push(input)},reset:function(){this.initialPrefix=null;this.iterator=this.historyBuffer.length}};var commandDispatcher={matchCommand:function(keys,keyMap,inputState,context){var matches=commandMatches(keys,keyMap,context,inputState);if(!matches.full&&!matches.partial)return{type:"none"};if(!matches.full&&matches.partial)return{type:"partial"};for(var bestMatch,i=0;i<matches.full.length;i++){var match=matches.full[i];bestMatch||(bestMatch=match)}"<character>"==bestMatch.keys.slice(-11)&&(inputState.selectedCharacter=lastChar(keys));return{type:"full",command:bestMatch}},processCommand:function(cm,vim,command){vim.inputState.repeatOverride=command.repeatOverride;switch(command.type){case"motion":this.processMotion(cm,vim,command);break;case"operator":this.processOperator(cm,vim,command);break;case"operatorMotion":this.processOperatorMotion(cm,vim,command);break;case"action":this.processAction(cm,vim,command);break;case"search":this.processSearch(cm,vim,command);break;case"ex":case"keyToEx":this.processEx(cm,vim,command)}},processMotion:function(cm,vim,command){vim.inputState.motion=command.motion;vim.inputState.motionArgs=copyArgs(command.motionArgs);this.evalInput(cm,vim)},processOperator:function(cm,vim,command){var inputState=vim.inputState;if(inputState.operator){if(inputState.operator==command.operator){inputState.motion="expandToLine";inputState.motionArgs={linewise:!0};this.evalInput(cm,vim);return}clearInputState(cm)}inputState.operator=command.operator;inputState.operatorArgs=copyArgs(command.operatorArgs);vim.visualMode&&this.evalInput(cm,vim)},processOperatorMotion:function(cm,vim,command){var visualMode=vim.visualMode,operatorMotionArgs=copyArgs(command.operatorMotionArgs);operatorMotionArgs&&visualMode&&operatorMotionArgs.visualLine&&(vim.visualLine=!0);this.processOperator(cm,vim,command);visualMode||this.processMotion(cm,vim,command)},processAction:function(cm,vim,command){var inputState=vim.inputState,repeat=inputState.getRepeat(),repeatIsExplicit=!!repeat,actionArgs=copyArgs(command.actionArgs)||{};inputState.selectedCharacter&&(actionArgs.selectedCharacter=inputState.selectedCharacter);command.operator&&this.processOperator(cm,vim,command);command.motion&&this.processMotion(cm,vim,command);(command.motion||command.operator)&&this.evalInput(cm,vim);actionArgs.repeat=repeat||1;actionArgs.repeatIsExplicit=repeatIsExplicit;actionArgs.registerName=inputState.registerName;clearInputState(cm);vim.lastMotion=null;command.isEdit&&this.recordLastEdit(vim,inputState,command);actions[command.action](cm,actionArgs,vim)},processSearch:function(cm,vim,command){function handleQuery(query,ignoreCase,smartCase){vimGlobalState.searchHistoryController.pushInput(query);vimGlobalState.searchHistoryController.reset();try{updateSearchQuery(cm,query,ignoreCase,smartCase)}catch(e){showConfirm(cm,"Invalid regex: "+query);clearInputState(cm);return}commandDispatcher.processMotion(cm,vim,{type:"motion",motion:"findNext",motionArgs:{forward:!0,toJumplist:command.searchArgs.toJumplist}})}function onPromptClose(query){cm.scrollTo(originalScrollPos.left,originalScrollPos.top);handleQuery(query,!0,!0);var macroModeState=vimGlobalState.macroModeState;macroModeState.isRecording&&logSearchQuery(macroModeState,query)}function onPromptKeyUp(e,query,close){var up,keyName=CodeMirror.keyName(e);if("Up"==keyName||"Down"==keyName){up="Up"==keyName;query=vimGlobalState.searchHistoryController.nextMatch(query,up)||"";close(query)}else"Left"!=keyName&&"Right"!=keyName&&"Ctrl"!=keyName&&"Alt"!=keyName&&"Shift"!=keyName&&vimGlobalState.searchHistoryController.reset();var parsedQuery;try{parsedQuery=updateSearchQuery(cm,query,!0,!0)}catch(e){}if(parsedQuery)cm.scrollIntoView(findNext(cm,!forward,parsedQuery),30);else{clearSearchHighlight(cm);cm.scrollTo(originalScrollPos.left,originalScrollPos.top)}}function onPromptKeyDown(e,query,close){var keyName=CodeMirror.keyName(e);if("Esc"==keyName||"Ctrl-C"==keyName||"Ctrl-["==keyName||"Backspace"==keyName&&""==query){vimGlobalState.searchHistoryController.pushInput(query);vimGlobalState.searchHistoryController.reset();updateSearchQuery(cm,originalQuery);clearSearchHighlight(cm);cm.scrollTo(originalScrollPos.left,originalScrollPos.top);CodeMirror.e_stop(e);clearInputState(cm);close();cm.focus()}else if("Ctrl-U"==keyName){CodeMirror.e_stop(e);close("")}}if(cm.getSearchCursor){var forward=command.searchArgs.forward,wholeWordOnly=command.searchArgs.wholeWordOnly;getSearchState(cm).setReversed(!forward);var promptPrefix=forward?"/":"?",originalQuery=getSearchState(cm).getQuery(),originalScrollPos=cm.getScrollInfo();switch(command.searchArgs.querySrc){case"prompt":var macroModeState=vimGlobalState.macroModeState;if(macroModeState.isPlaying){var query=macroModeState.replaySearchQueries.shift();handleQuery(query,!0,!1)}else showPrompt(cm,{onClose:onPromptClose,prefix:promptPrefix,desc:searchPromptDesc,onKeyUp:onPromptKeyUp,onKeyDown:onPromptKeyDown});break;case"wordUnderCursor":var word=expandWordUnderCursor(cm,!1,!0,!1,!0),isKeyword=!0;if(!word){word=expandWordUnderCursor(cm,!1,!0,!1,!1);isKeyword=!1}if(!word)return;var query=cm.getLine(word.start.line).substring(word.start.ch,word.end.ch);
3
+ query=isKeyword&&wholeWordOnly?"\\b"+query+"\\b":escapeRegex(query);vimGlobalState.jumpList.cachedCursor=cm.getCursor();cm.setCursor(word.start);handleQuery(query,!0,!1)}}},processEx:function(cm,vim,command){function onPromptClose(input){vimGlobalState.exCommandHistoryController.pushInput(input);vimGlobalState.exCommandHistoryController.reset();exCommandDispatcher.processCommand(cm,input)}function onPromptKeyDown(e,input,close){var up,keyName=CodeMirror.keyName(e);if("Esc"==keyName||"Ctrl-C"==keyName||"Ctrl-["==keyName||"Backspace"==keyName&&""==input){vimGlobalState.exCommandHistoryController.pushInput(input);vimGlobalState.exCommandHistoryController.reset();CodeMirror.e_stop(e);clearInputState(cm);close();cm.focus()}if("Up"==keyName||"Down"==keyName){up="Up"==keyName;input=vimGlobalState.exCommandHistoryController.nextMatch(input,up)||"";close(input)}else if("Ctrl-U"==keyName){CodeMirror.e_stop(e);close("")}else"Left"!=keyName&&"Right"!=keyName&&"Ctrl"!=keyName&&"Alt"!=keyName&&"Shift"!=keyName&&vimGlobalState.exCommandHistoryController.reset()}"keyToEx"==command.type?exCommandDispatcher.processCommand(cm,command.exArgs.input):vim.visualMode?showPrompt(cm,{onClose:onPromptClose,prefix:":",value:"'<,'>",onKeyDown:onPromptKeyDown}):showPrompt(cm,{onClose:onPromptClose,prefix:":",onKeyDown:onPromptKeyDown})},evalInput:function(cm,vim){var newHead,newAnchor,repeat,inputState=vim.inputState,motion=inputState.motion,motionArgs=inputState.motionArgs||{},operator=inputState.operator,operatorArgs=inputState.operatorArgs||{},registerName=inputState.registerName,sel=vim.sel,origHead=copyCursor(vim.visualMode?clipCursorToContent(cm,sel.head):cm.getCursor("head")),origAnchor=copyCursor(vim.visualMode?clipCursorToContent(cm,sel.anchor):cm.getCursor("anchor")),oldHead=copyCursor(origHead),oldAnchor=copyCursor(origAnchor);operator&&this.recordLastEdit(vim,inputState);repeat=void 0!==inputState.repeatOverride?inputState.repeatOverride:inputState.getRepeat();if(repeat>0&&motionArgs.explicitRepeat)motionArgs.repeatIsExplicit=!0;else if(motionArgs.noRepeat||!motionArgs.explicitRepeat&&0===repeat){repeat=1;motionArgs.repeatIsExplicit=!1}inputState.selectedCharacter&&(motionArgs.selectedCharacter=operatorArgs.selectedCharacter=inputState.selectedCharacter);motionArgs.repeat=repeat;clearInputState(cm);if(motion){var motionResult=motions[motion](cm,origHead,motionArgs,vim);vim.lastMotion=motions[motion];if(!motionResult)return;if(motionArgs.toJumplist){var jumpList=vimGlobalState.jumpList,cachedCursor=jumpList.cachedCursor;if(cachedCursor){recordJumpPosition(cm,cachedCursor,motionResult);delete jumpList.cachedCursor}else recordJumpPosition(cm,origHead,motionResult)}if(motionResult instanceof Array){newAnchor=motionResult[0];newHead=motionResult[1]}else newHead=motionResult;newHead||(newHead=copyCursor(origHead));if(vim.visualMode){vim.visualBlock&&newHead.ch===1/0||(newHead=clipCursorToContent(cm,newHead,vim.visualBlock));newAnchor&&(newAnchor=clipCursorToContent(cm,newAnchor,!0));newAnchor=newAnchor||oldAnchor;sel.anchor=newAnchor;sel.head=newHead;updateCmSelection(cm);updateMark(cm,vim,"<",cursorIsBefore(newAnchor,newHead)?newAnchor:newHead);updateMark(cm,vim,">",cursorIsBefore(newAnchor,newHead)?newHead:newAnchor)}else if(!operator){newHead=clipCursorToContent(cm,newHead);cm.setCursor(newHead.line,newHead.ch)}}if(operator){if(operatorArgs.lastSel){newAnchor=oldAnchor;var lastSel=operatorArgs.lastSel,lineOffset=Math.abs(lastSel.head.line-lastSel.anchor.line),chOffset=Math.abs(lastSel.head.ch-lastSel.anchor.ch);newHead=lastSel.visualLine?Pos(oldAnchor.line+lineOffset,oldAnchor.ch):lastSel.visualBlock?Pos(oldAnchor.line+lineOffset,oldAnchor.ch+chOffset):lastSel.head.line==lastSel.anchor.line?Pos(oldAnchor.line,oldAnchor.ch+chOffset):Pos(oldAnchor.line+lineOffset,oldAnchor.ch);vim.visualMode=!0;vim.visualLine=lastSel.visualLine;vim.visualBlock=lastSel.visualBlock;sel=vim.sel={anchor:newAnchor,head:newHead};updateCmSelection(cm)}else vim.visualMode&&(operatorArgs.lastSel={anchor:copyCursor(sel.anchor),head:copyCursor(sel.head),visualBlock:vim.visualBlock,visualLine:vim.visualLine});var curStart,curEnd,linewise,mode,cmSel;if(vim.visualMode){curStart=cursorMin(sel.head,sel.anchor);curEnd=cursorMax(sel.head,sel.anchor);linewise=vim.visualLine||operatorArgs.linewise;mode=vim.visualBlock?"block":linewise?"line":"char";cmSel=makeCmSelection(cm,{anchor:curStart,head:curEnd},mode);if(linewise){var ranges=cmSel.ranges;if("block"==mode)for(var i=0;i<ranges.length;i++)ranges[i].head.ch=lineLength(cm,ranges[i].head.line);else"line"==mode&&(ranges[0].head=Pos(ranges[0].head.line+1,0))}}else{curStart=copyCursor(newAnchor||oldAnchor);curEnd=copyCursor(newHead||oldHead);if(cursorIsBefore(curEnd,curStart)){var tmp=curStart;curStart=curEnd;curEnd=tmp}linewise=motionArgs.linewise||operatorArgs.linewise;linewise?expandSelectionToLine(cm,curStart,curEnd):motionArgs.forward&&clipToLine(cm,curStart,curEnd);mode="char";var exclusive=!motionArgs.inclusive||linewise;cmSel=makeCmSelection(cm,{anchor:curStart,head:curEnd},mode,exclusive)}cm.setSelections(cmSel.ranges,cmSel.primary);vim.lastMotion=null;operatorArgs.repeat=repeat;operatorArgs.registerName=registerName;operatorArgs.linewise=linewise;var operatorMoveTo=operators[operator](cm,operatorArgs,cmSel.ranges,oldAnchor,newHead);vim.visualMode&&exitVisualMode(cm,null!=operatorMoveTo);operatorMoveTo&&cm.setCursor(operatorMoveTo)}},recordLastEdit:function(vim,inputState,actionCommand){var macroModeState=vimGlobalState.macroModeState;if(!macroModeState.isPlaying){vim.lastEditInputState=inputState;vim.lastEditActionCommand=actionCommand;macroModeState.lastInsertModeChanges.changes=[];macroModeState.lastInsertModeChanges.expectCursorActivityForChange=!1}}},motions={moveToTopLine:function(cm,_head,motionArgs){var line=getUserVisibleLines(cm).top+motionArgs.repeat-1;return Pos(line,findFirstNonWhiteSpaceCharacter(cm.getLine(line)))},moveToMiddleLine:function(cm){var range=getUserVisibleLines(cm),line=Math.floor(.5*(range.top+range.bottom));return Pos(line,findFirstNonWhiteSpaceCharacter(cm.getLine(line)))},moveToBottomLine:function(cm,_head,motionArgs){var line=getUserVisibleLines(cm).bottom-motionArgs.repeat+1;return Pos(line,findFirstNonWhiteSpaceCharacter(cm.getLine(line)))},expandToLine:function(_cm,head,motionArgs){var cur=head;return Pos(cur.line+motionArgs.repeat-1,1/0)},findNext:function(cm,_head,motionArgs){var state=getSearchState(cm),query=state.getQuery();if(query){var prev=!motionArgs.forward;prev=state.isReversed()?!prev:prev;highlightSearchMatches(cm,query);return findNext(cm,prev,query,motionArgs.repeat)}},goToMark:function(cm,_head,motionArgs,vim){var mark=vim.marks[motionArgs.selectedCharacter];if(mark){var pos=mark.find();return motionArgs.linewise?{line:pos.line,ch:findFirstNonWhiteSpaceCharacter(cm.getLine(pos.line))}:pos}return null},moveToOtherHighlightedEnd:function(cm,_head,motionArgs,vim){if(vim.visualBlock&&motionArgs.sameLine){var sel=vim.sel;return[clipCursorToContent(cm,Pos(sel.anchor.line,sel.head.ch)),clipCursorToContent(cm,Pos(sel.head.line,sel.anchor.ch))]}return[vim.sel.head,vim.sel.anchor]},jumpToMark:function(cm,head,motionArgs,vim){for(var best=head,i=0;i<motionArgs.repeat;i++){var cursor=best;for(var key in vim.marks)if(isLowerCase(key)){var mark=vim.marks[key].find(),isWrongDirection=motionArgs.forward?cursorIsBefore(mark,cursor):cursorIsBefore(cursor,mark);if(!(isWrongDirection||motionArgs.linewise&&mark.line==cursor.line)){var equal=cursorEqual(cursor,best),between=motionArgs.forward?cursorIsBetween(cursor,mark,best):cursorIsBetween(best,mark,cursor);(equal||between)&&(best=mark)}}}motionArgs.linewise&&(best=Pos(best.line,findFirstNonWhiteSpaceCharacter(cm.getLine(best.line))));return best},moveByCharacters:function(_cm,head,motionArgs){var cur=head,repeat=motionArgs.repeat,ch=motionArgs.forward?cur.ch+repeat:cur.ch-repeat;return Pos(cur.line,ch)},moveByLines:function(cm,head,motionArgs,vim){var cur=head,endCh=cur.ch;switch(vim.lastMotion){case this.moveByLines:case this.moveByDisplayLines:case this.moveByScroll:case this.moveToColumn:case this.moveToEol:endCh=vim.lastHPos;break;default:vim.lastHPos=endCh}var repeat=motionArgs.repeat+(motionArgs.repeatOffset||0),line=motionArgs.forward?cur.line+repeat:cur.line-repeat,first=cm.firstLine(),last=cm.lastLine();if(line<first&&cur.line==first)return this.moveToStartOfLine(cm,head,motionArgs,vim);if(line>last&&cur.line==last)return this.moveToEol(cm,head,motionArgs,vim);if(motionArgs.toFirstChar){endCh=findFirstNonWhiteSpaceCharacter(cm.getLine(line));vim.lastHPos=endCh}vim.lastHSPos=cm.charCoords(Pos(line,endCh),"div").left;return Pos(line,endCh)},moveByDisplayLines:function(cm,head,motionArgs,vim){var cur=head;switch(vim.lastMotion){case this.moveByDisplayLines:case this.moveByScroll:case this.moveByLines:case this.moveToColumn:case this.moveToEol:break;default:vim.lastHSPos=cm.charCoords(cur,"div").left}var repeat=motionArgs.repeat,res=cm.findPosV(cur,motionArgs.forward?repeat:-repeat,"line",vim.lastHSPos);if(res.hitSide)if(motionArgs.forward)var lastCharCoords=cm.charCoords(res,"div"),goalCoords={top:lastCharCoords.top+8,left:vim.lastHSPos},res=cm.coordsChar(goalCoords,"div");else{var resCoords=cm.charCoords(Pos(cm.firstLine(),0),"div");resCoords.left=vim.lastHSPos;res=cm.coordsChar(resCoords,"div")}vim.lastHPos=res.ch;return res},moveByPage:function(cm,head,motionArgs){var curStart=head,repeat=motionArgs.repeat;return cm.findPosV(curStart,motionArgs.forward?repeat:-repeat,"page")},moveByParagraph:function(cm,head,motionArgs){var dir=motionArgs.forward?1:-1;return findParagraph(cm,head,motionArgs.repeat,dir)},moveByScroll:function(cm,head,motionArgs,vim){var scrollbox=cm.getScrollInfo(),curEnd=null,repeat=motionArgs.repeat;repeat||(repeat=scrollbox.clientHeight/(2*cm.defaultTextHeight()));var orig=cm.charCoords(head,"local");motionArgs.repeat=repeat;var curEnd=motions.moveByDisplayLines(cm,head,motionArgs,vim);if(!curEnd)return null;var dest=cm.charCoords(curEnd,"local");cm.scrollTo(null,scrollbox.top+dest.top-orig.top);return curEnd},moveByWords:function(cm,head,motionArgs){return moveToWord(cm,head,motionArgs.repeat,!!motionArgs.forward,!!motionArgs.wordEnd,!!motionArgs.bigWord)},moveTillCharacter:function(cm,_head,motionArgs){var repeat=motionArgs.repeat,curEnd=moveToCharacter(cm,repeat,motionArgs.forward,motionArgs.selectedCharacter),increment=motionArgs.forward?-1:1;recordLastCharacterSearch(increment,motionArgs);if(!curEnd)return null;curEnd.ch+=increment;return curEnd},moveToCharacter:function(cm,head,motionArgs){var repeat=motionArgs.repeat;recordLastCharacterSearch(0,motionArgs);return moveToCharacter(cm,repeat,motionArgs.forward,motionArgs.selectedCharacter)||head},moveToSymbol:function(cm,head,motionArgs){var repeat=motionArgs.repeat;return findSymbol(cm,repeat,motionArgs.forward,motionArgs.selectedCharacter)||head},moveToColumn:function(cm,head,motionArgs,vim){var repeat=motionArgs.repeat;vim.lastHPos=repeat-1;vim.lastHSPos=cm.charCoords(head,"div").left;return moveToColumn(cm,repeat)},moveToEol:function(cm,head,motionArgs,vim){var cur=head;vim.lastHPos=1/0;var retval=Pos(cur.line+motionArgs.repeat-1,1/0),end=cm.clipPos(retval);end.ch--;vim.lastHSPos=cm.charCoords(end,"div").left;return retval},moveToFirstNonWhiteSpaceCharacter:function(cm,head){var cursor=head;return Pos(cursor.line,findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line)))},moveToMatchedSymbol:function(cm,head){var symbol,cursor=head,line=cursor.line,ch=cursor.ch,lineText=cm.getLine(line);do{symbol=lineText.charAt(ch++);if(symbol&&isMatchableSymbol(symbol)){var style=cm.getTokenTypeAt(Pos(line,ch));if("string"!==style&&"comment"!==style)break}}while(symbol);if(symbol){var matched=cm.findMatchingBracket(Pos(line,ch));return matched.to}return cursor},moveToStartOfLine:function(_cm,head){return Pos(head.line,0)},moveToLineOrEdgeOfDocument:function(cm,_head,motionArgs){var lineNum=motionArgs.forward?cm.lastLine():cm.firstLine();motionArgs.repeatIsExplicit&&(lineNum=motionArgs.repeat-cm.getOption("firstLineNumber"));return Pos(lineNum,findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum)))},textObjectManipulation:function(cm,head,motionArgs,vim){var mirroredPairs={"(":")",")":"(","{":"}","}":"{","[":"]","]":"["},selfPaired={"'":!0,'"':!0},character=motionArgs.selectedCharacter;"b"==character?character="(":"B"==character&&(character="{");var tmp,inclusive=!motionArgs.textObjectInner;if(mirroredPairs[character])tmp=selectCompanionObject(cm,head,character,inclusive);else if(selfPaired[character])tmp=findBeginningAndEnd(cm,head,character,inclusive);else if("W"===character)tmp=expandWordUnderCursor(cm,inclusive,!0,!0);else if("w"===character)tmp=expandWordUnderCursor(cm,inclusive,!0,!1);else{if("p"!==character)return null;tmp=findParagraph(cm,head,motionArgs.repeat,0,inclusive);motionArgs.linewise=!0;if(vim.visualMode)vim.visualLine||(vim.visualLine=!0);else{var operatorArgs=vim.inputState.operatorArgs;operatorArgs&&(operatorArgs.linewise=!0);tmp.end.line--}}return cm.state.vim.visualMode?expandSelection(cm,tmp.start,tmp.end):[tmp.start,tmp.end]},repeatLastCharacterSearch:function(cm,head,motionArgs){var lastSearch=vimGlobalState.lastCharacterSearch,repeat=motionArgs.repeat,forward=motionArgs.forward===lastSearch.forward,increment=(lastSearch.increment?1:0)*(forward?-1:1);cm.moveH(-increment,"char");motionArgs.inclusive=!!forward;var curEnd=moveToCharacter(cm,repeat,forward,lastSearch.selectedCharacter);if(!curEnd){cm.moveH(increment,"char");return head}curEnd.ch+=increment;return curEnd}},operators={change:function(cm,args,ranges){var finalHead,text,vim=cm.state.vim;vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock=vim.visualBlock;if(vim.visualMode){text=cm.getSelection();var replacement=fillArray("",ranges.length);cm.replaceSelections(replacement);finalHead=cursorMin(ranges[0].head,ranges[0].anchor)}else{var anchor=ranges[0].anchor,head=ranges[0].head;text=cm.getRange(anchor,head);var lastState=vim.lastEditInputState||{};if("moveByWords"==lastState.motion&&!isWhiteSpaceString(text)){var match=/\s+$/.exec(text);if(match&&lastState.motionArgs&&lastState.motionArgs.forward){head=offsetCursor(head,0,-match[0].length);text=text.slice(0,-match[0].length)}}var prevLineEnd=new Pos(anchor.line-1,Number.MAX_VALUE),wasLastLine=cm.firstLine()==cm.lastLine();head.line>cm.lastLine()&&args.linewise&&!wasLastLine?cm.replaceRange("",prevLineEnd,head):cm.replaceRange("",anchor,head);if(args.linewise){if(!wasLastLine){cm.setCursor(prevLineEnd);CodeMirror.commands.newlineAndIndent(cm)}anchor.ch=Number.MAX_VALUE}finalHead=anchor}vimGlobalState.registerController.pushText(args.registerName,"change",text,args.linewise,ranges.length>1);actions.enterInsertMode(cm,{head:finalHead},cm.state.vim)},"delete":function(cm,args,ranges){var finalHead,text,vim=cm.state.vim;if(vim.visualBlock){text=cm.getSelection();var replacement=fillArray("",ranges.length);cm.replaceSelections(replacement);finalHead=ranges[0].anchor}else{var anchor=ranges[0].anchor,head=ranges[0].head;args.linewise&&head.line!=cm.firstLine()&&anchor.line==cm.lastLine()&&anchor.line==head.line-1&&(anchor.line==cm.firstLine()?anchor.ch=0:anchor=Pos(anchor.line-1,lineLength(cm,anchor.line-1)));text=cm.getRange(anchor,head);cm.replaceRange("",anchor,head);finalHead=anchor;args.linewise&&(finalHead=motions.moveToFirstNonWhiteSpaceCharacter(cm,anchor))}vimGlobalState.registerController.pushText(args.registerName,"delete",text,args.linewise,vim.visualBlock);return clipCursorToContent(cm,finalHead)},indent:function(cm,args,ranges){var vim=cm.state.vim,startLine=ranges[0].anchor.line,endLine=vim.visualBlock?ranges[ranges.length-1].anchor.line:ranges[0].head.line,repeat=vim.visualMode?args.repeat:1;args.linewise&&endLine--;for(var i=startLine;i<=endLine;i++)for(var j=0;j<repeat;j++)cm.indentLine(i,args.indentRight);return motions.moveToFirstNonWhiteSpaceCharacter(cm,ranges[0].anchor)},changeCase:function(cm,args,ranges,oldAnchor,newHead){for(var selections=cm.getSelections(),swapped=[],toLower=args.toLower,j=0;j<selections.length;j++){var toSwap=selections[j],text="";if(toLower===!0)text=toSwap.toLowerCase();else if(toLower===!1)text=toSwap.toUpperCase();else for(var i=0;i<toSwap.length;i++){var character=toSwap.charAt(i);text+=isUpperCase(character)?character.toLowerCase():character.toUpperCase()}swapped.push(text)}cm.replaceSelections(swapped);return args.shouldMoveCursor?newHead:!cm.state.vim.visualMode&&args.linewise&&ranges[0].anchor.line+1==ranges[0].head.line?motions.moveToFirstNonWhiteSpaceCharacter(cm,oldAnchor):args.linewise?oldAnchor:cursorMin(ranges[0].anchor,ranges[0].head)},yank:function(cm,args,ranges,oldAnchor){var vim=cm.state.vim,text=cm.getSelection(),endPos=vim.visualMode?cursorMin(vim.sel.anchor,vim.sel.head,ranges[0].head,ranges[0].anchor):oldAnchor;vimGlobalState.registerController.pushText(args.registerName,"yank",text,args.linewise,vim.visualBlock);return endPos}},actions={jumpListWalk:function(cm,actionArgs,vim){if(!vim.visualMode){var repeat=actionArgs.repeat,forward=actionArgs.forward,jumpList=vimGlobalState.jumpList,mark=jumpList.move(cm,forward?repeat:-repeat),markPos=mark?mark.find():void 0;markPos=markPos?markPos:cm.getCursor();cm.setCursor(markPos)}},scroll:function(cm,actionArgs,vim){if(!vim.visualMode){var repeat=actionArgs.repeat||1,lineHeight=cm.defaultTextHeight(),top=cm.getScrollInfo().top,delta=lineHeight*repeat,newPos=actionArgs.forward?top+delta:top-delta,cursor=copyCursor(cm.getCursor()),cursorCoords=cm.charCoords(cursor,"local");if(actionArgs.forward)if(newPos>cursorCoords.top){cursor.line+=(newPos-cursorCoords.top)/lineHeight;cursor.line=Math.ceil(cursor.line);cm.setCursor(cursor);cursorCoords=cm.charCoords(cursor,"local");cm.scrollTo(null,cursorCoords.top)}else cm.scrollTo(null,newPos);else{var newBottom=newPos+cm.getScrollInfo().clientHeight;if(newBottom<cursorCoords.bottom){cursor.line-=(cursorCoords.bottom-newBottom)/lineHeight;cursor.line=Math.floor(cursor.line);cm.setCursor(cursor);cursorCoords=cm.charCoords(cursor,"local");cm.scrollTo(null,cursorCoords.bottom-cm.getScrollInfo().clientHeight)}else cm.scrollTo(null,newPos)}}},scrollToCursor:function(cm,actionArgs){var lineNum=cm.getCursor().line,charCoords=cm.charCoords(Pos(lineNum,0),"local"),height=cm.getScrollInfo().clientHeight,y=charCoords.top,lineHeight=charCoords.bottom-y;switch(actionArgs.position){case"center":y=y-height/2+lineHeight;break;case"bottom":y=y-height+lineHeight}cm.scrollTo(null,y)},replayMacro:function(cm,actionArgs,vim){var registerName=actionArgs.selectedCharacter,repeat=actionArgs.repeat,macroModeState=vimGlobalState.macroModeState;"@"==registerName&&(registerName=macroModeState.latestRegister);for(;repeat--;)executeMacroRegister(cm,vim,macroModeState,registerName)},enterMacroRecordMode:function(cm,actionArgs){var macroModeState=vimGlobalState.macroModeState,registerName=actionArgs.selectedCharacter;macroModeState.enterMacroRecordMode(cm,registerName)},toggleOverwrite:function(cm){if(cm.state.overwrite){cm.toggleOverwrite(!1);cm.setOption("keyMap","vim-insert");CodeMirror.signal(cm,"vim-mode-change",{mode:"insert"})}else{cm.toggleOverwrite(!0);cm.setOption("keyMap","vim-replace");CodeMirror.signal(cm,"vim-mode-change",{mode:"replace"})}},enterInsertMode:function(cm,actionArgs,vim){if(!cm.getOption("readOnly")){vim.insertMode=!0;vim.insertModeRepeat=actionArgs&&actionArgs.repeat||1;var insertAt=actionArgs?actionArgs.insertAt:null,sel=vim.sel,head=actionArgs.head||cm.getCursor("head"),height=cm.listSelections().length;if("eol"==insertAt)head=Pos(head.line,lineLength(cm,head.line));else if("charAfter"==insertAt)head=offsetCursor(head,0,1);else if("firstNonBlank"==insertAt)head=motions.moveToFirstNonWhiteSpaceCharacter(cm,head);else if("startOfSelectedArea"==insertAt)if(vim.visualBlock){head=Pos(Math.min(sel.head.line,sel.anchor.line),Math.min(sel.head.ch,sel.anchor.ch));height=Math.abs(sel.head.line-sel.anchor.line)+1}else head=sel.head.line<sel.anchor.line?sel.head:Pos(sel.anchor.line,0);else if("endOfSelectedArea"==insertAt)if(vim.visualBlock){head=Pos(Math.min(sel.head.line,sel.anchor.line),Math.max(sel.head.ch+1,sel.anchor.ch));height=Math.abs(sel.head.line-sel.anchor.line)+1}else head=sel.head.line>=sel.anchor.line?offsetCursor(sel.head,0,1):Pos(sel.anchor.line,0);else if("inplace"==insertAt&&vim.visualMode)return;cm.setOption("disableInput",!1);if(actionArgs&&actionArgs.replace){cm.toggleOverwrite(!0);cm.setOption("keyMap","vim-replace");CodeMirror.signal(cm,"vim-mode-change",{mode:"replace"})}else{cm.toggleOverwrite(!1);cm.setOption("keyMap","vim-insert");CodeMirror.signal(cm,"vim-mode-change",{mode:"insert"})}if(!vimGlobalState.macroModeState.isPlaying){cm.on("change",onChange);CodeMirror.on(cm.getInputField(),"keydown",onKeyEventTargetKeyDown)}vim.visualMode&&exitVisualMode(cm);selectForInsert(cm,head,height)}},toggleVisualMode:function(cm,actionArgs,vim){var head,repeat=actionArgs.repeat,anchor=cm.getCursor();if(vim.visualMode)if(vim.visualLine^actionArgs.linewise||vim.visualBlock^actionArgs.blockwise){vim.visualLine=!!actionArgs.linewise;vim.visualBlock=!!actionArgs.blockwise;CodeMirror.signal(cm,"vim-mode-change",{mode:"visual",subMode:vim.visualLine?"linewise":vim.visualBlock?"blockwise":""});updateCmSelection(cm)}else exitVisualMode(cm);else{vim.visualMode=!0;vim.visualLine=!!actionArgs.linewise;vim.visualBlock=!!actionArgs.blockwise;head=clipCursorToContent(cm,Pos(anchor.line,anchor.ch+repeat-1),!0);vim.sel={anchor:anchor,head:head};CodeMirror.signal(cm,"vim-mode-change",{mode:"visual",subMode:vim.visualLine?"linewise":vim.visualBlock?"blockwise":""});updateCmSelection(cm);updateMark(cm,vim,"<",cursorMin(anchor,head));updateMark(cm,vim,">",cursorMax(anchor,head))}},reselectLastSelection:function(cm,_actionArgs,vim){var lastSelection=vim.lastSelection;vim.visualMode&&updateLastSelection(cm,vim);if(lastSelection){var anchor=lastSelection.anchorMark.find(),head=lastSelection.headMark.find();if(!anchor||!head)return;vim.sel={anchor:anchor,head:head};vim.visualMode=!0;vim.visualLine=lastSelection.visualLine;vim.visualBlock=lastSelection.visualBlock;updateCmSelection(cm);updateMark(cm,vim,"<",cursorMin(anchor,head));updateMark(cm,vim,">",cursorMax(anchor,head));CodeMirror.signal(cm,"vim-mode-change",{mode:"visual",subMode:vim.visualLine?"linewise":vim.visualBlock?"blockwise":""})}},joinLines:function(cm,actionArgs,vim){var curStart,curEnd;if(vim.visualMode){curStart=cm.getCursor("anchor");curEnd=cm.getCursor("head");if(cursorIsBefore(curEnd,curStart)){var tmp=curEnd;curEnd=curStart;curStart=tmp}curEnd.ch=lineLength(cm,curEnd.line)-1}else{var repeat=Math.max(actionArgs.repeat,2);curStart=cm.getCursor();curEnd=clipCursorToContent(cm,Pos(curStart.line+repeat-1,1/0))}for(var finalCh=0,i=curStart.line;i<curEnd.line;i++){finalCh=lineLength(cm,curStart.line);var tmp=Pos(curStart.line+1,lineLength(cm,curStart.line+1)),text=cm.getRange(curStart,tmp);text=text.replace(/\n\s*/g," ");cm.replaceRange(text,curStart,tmp)}var curFinalPos=Pos(curStart.line,finalCh);vim.visualMode&&exitVisualMode(cm,!1);cm.setCursor(curFinalPos)},newLineAndEnterInsertMode:function(cm,actionArgs,vim){vim.insertMode=!0;var insertAt=copyCursor(cm.getCursor());if(insertAt.line!==cm.firstLine()||actionArgs.after){insertAt.line=actionArgs.after?insertAt.line:insertAt.line-1;insertAt.ch=lineLength(cm,insertAt.line);cm.setCursor(insertAt);var newlineFn=CodeMirror.commands.newlineAndIndentContinueComment||CodeMirror.commands.newlineAndIndent;newlineFn(cm)}else{cm.replaceRange("\n",Pos(cm.firstLine(),0));cm.setCursor(cm.firstLine(),0)}this.enterInsertMode(cm,{repeat:actionArgs.repeat},vim)},paste:function(cm,actionArgs,vim){var cur=copyCursor(cm.getCursor()),register=vimGlobalState.registerController.getRegister(actionArgs.registerName),text=register.toString();if(text){if(actionArgs.matchIndent){var tabSize=cm.getOption("tabSize"),whitespaceLength=function(str){var tabs=str.split("\t").length-1,spaces=str.split(" ").length-1;return tabs*tabSize+1*spaces},currentLine=cm.getLine(cm.getCursor().line),indent=whitespaceLength(currentLine.match(/^\s*/)[0]),chompedText=text.replace(/\n$/,""),wasChomped=text!==chompedText,firstIndent=whitespaceLength(text.match(/^\s*/)[0]),text=chompedText.replace(/^\s*/gm,function(wspace){var newIndent=indent+(whitespaceLength(wspace)-firstIndent);if(newIndent<0)return"";if(cm.getOption("indentWithTabs")){var quotient=Math.floor(newIndent/tabSize);return Array(quotient+1).join("\t")}return Array(newIndent+1).join(" ")});text+=wasChomped?"\n":""}if(actionArgs.repeat>1)var text=Array(actionArgs.repeat+1).join(text);var linewise=register.linewise,blockwise=register.blockwise;if(linewise)if(vim.visualMode)text=vim.visualLine?text.slice(0,-1):"\n"+text.slice(0,text.length-1)+"\n";else if(actionArgs.after){text="\n"+text.slice(0,text.length-1);cur.ch=lineLength(cm,cur.line)}else cur.ch=0;else{if(blockwise){text=text.split("\n");for(var i=0;i<text.length;i++)text[i]=""==text[i]?" ":text[i]}cur.ch+=actionArgs.after?1:0}var curPosFinal,idx;if(vim.visualMode){vim.lastPastedText=text;var lastSelectionCurEnd,selectedArea=getSelectedAreaRange(cm,vim),selectionStart=selectedArea[0],selectionEnd=selectedArea[1],selectedText=cm.getSelection(),selections=cm.listSelections(),emptyStrings=new Array(selections.length).join("1").split("1");vim.lastSelection&&(lastSelectionCurEnd=vim.lastSelection.headMark.find());vimGlobalState.registerController.unnamedRegister.setText(selectedText);if(blockwise){cm.replaceSelections(emptyStrings);selectionEnd=Pos(selectionStart.line+text.length-1,selectionStart.ch);cm.setCursor(selectionStart);selectBlock(cm,selectionEnd);cm.replaceSelections(text);curPosFinal=selectionStart}else if(vim.visualBlock){cm.replaceSelections(emptyStrings);cm.setCursor(selectionStart);cm.replaceRange(text,selectionStart,selectionStart);curPosFinal=selectionStart}else{cm.replaceRange(text,selectionStart,selectionEnd);curPosFinal=cm.posFromIndex(cm.indexFromPos(selectionStart)+text.length-1)}lastSelectionCurEnd&&(vim.lastSelection.headMark=cm.setBookmark(lastSelectionCurEnd));linewise&&(curPosFinal.ch=0)}else if(blockwise){cm.setCursor(cur);for(var i=0;i<text.length;i++){var line=cur.line+i;line>cm.lastLine()&&cm.replaceRange("\n",Pos(line,0));var lastCh=lineLength(cm,line);lastCh<cur.ch&&extendLineToColumn(cm,line,cur.ch)}cm.setCursor(cur);selectBlock(cm,Pos(cur.line+text.length-1,cur.ch));cm.replaceSelections(text);curPosFinal=cur}else{cm.replaceRange(text,cur);if(linewise&&actionArgs.after)curPosFinal=Pos(cur.line+1,findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line+1)));else if(linewise&&!actionArgs.after)curPosFinal=Pos(cur.line,findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line)));else if(!linewise&&actionArgs.after){idx=cm.indexFromPos(cur);curPosFinal=cm.posFromIndex(idx+text.length-1)}else{idx=cm.indexFromPos(cur);curPosFinal=cm.posFromIndex(idx+text.length)}}vim.visualMode&&exitVisualMode(cm,!1);cm.setCursor(curPosFinal)}},undo:function(cm,actionArgs){cm.operation(function(){repeatFn(cm,CodeMirror.commands.undo,actionArgs.repeat)();cm.setCursor(cm.getCursor("anchor"))})},redo:function(cm,actionArgs){repeatFn(cm,CodeMirror.commands.redo,actionArgs.repeat)()},setRegister:function(_cm,actionArgs,vim){vim.inputState.registerName=actionArgs.selectedCharacter},setMark:function(cm,actionArgs,vim){var markName=actionArgs.selectedCharacter;updateMark(cm,vim,markName,cm.getCursor())},replace:function(cm,actionArgs,vim){var replaceTo,curEnd,replaceWith=actionArgs.selectedCharacter,curStart=cm.getCursor(),selections=cm.listSelections();if(vim.visualMode){curStart=cm.getCursor("start");curEnd=cm.getCursor("end")}else{var line=cm.getLine(curStart.line);replaceTo=curStart.ch+actionArgs.repeat;replaceTo>line.length&&(replaceTo=line.length);curEnd=Pos(curStart.line,replaceTo)}if("\n"==replaceWith){vim.visualMode||cm.replaceRange("",curStart,curEnd);(CodeMirror.commands.newlineAndIndentContinueComment||CodeMirror.commands.newlineAndIndent)(cm)}else{var replaceWithStr=cm.getRange(curStart,curEnd);replaceWithStr=replaceWithStr.replace(/[^\n]/g,replaceWith);if(vim.visualBlock){var spaces=new Array(cm.getOption("tabSize")+1).join(" ");replaceWithStr=cm.getSelection();replaceWithStr=replaceWithStr.replace(/\t/g,spaces).replace(/[^\n]/g,replaceWith).split("\n");cm.replaceSelections(replaceWithStr)}else cm.replaceRange(replaceWithStr,curStart,curEnd);if(vim.visualMode){curStart=cursorIsBefore(selections[0].anchor,selections[0].head)?selections[0].anchor:selections[0].head;cm.setCursor(curStart);exitVisualMode(cm,!1)}else cm.setCursor(offsetCursor(curEnd,0,-1))}},incrementNumberToken:function(cm,actionArgs){for(var match,start,end,numberStr,token,cur=cm.getCursor(),lineStr=cm.getLine(cur.line),re=/-?\d+/g;null!==(match=re.exec(lineStr));){token=match[0];start=match.index;end=start+token.length;if(cur.ch<end)break}if((actionArgs.backtrack||!(end<=cur.ch))&&token){var increment=actionArgs.increase?1:-1,number=parseInt(token)+increment*actionArgs.repeat,from=Pos(cur.line,start),to=Pos(cur.line,end);numberStr=number.toString();cm.replaceRange(numberStr,from,to);cm.setCursor(Pos(cur.line,start+numberStr.length-1))}},repeatLastEdit:function(cm,actionArgs,vim){var lastEditInputState=vim.lastEditInputState;if(lastEditInputState){var repeat=actionArgs.repeat;repeat&&actionArgs.repeatIsExplicit?vim.lastEditInputState.repeatOverride=repeat:repeat=vim.lastEditInputState.repeatOverride||repeat;repeatLastEdit(cm,vim,repeat,!1)}},indent:function(cm,actionArgs){cm.indentLine(cm.getCursor().line,actionArgs.indentRight)},exitInsertMode:exitInsertMode},symbolToMode={"(":"bracket",")":"bracket","{":"bracket","}":"bracket","[":"section","]":"section","*":"comment","/":"comment",m:"method",M:"method","#":"preprocess"},findSymbolModes={bracket:{isComplete:function(state){if(state.nextCh===state.symb){state.depth++;if(state.depth>=1)return!0}else state.nextCh===state.reverseSymb&&state.depth--;return!1}},section:{init:function(state){state.curMoveThrough=!0;state.symb=(state.forward?"]":"[")===state.symb?"{":"}"},isComplete:function(state){return 0===state.index&&state.nextCh===state.symb}},comment:{isComplete:function(state){var found="*"===state.lastCh&&"/"===state.nextCh;state.lastCh=state.nextCh;return found}},method:{init:function(state){state.symb="m"===state.symb?"{":"}";state.reverseSymb="{"===state.symb?"}":"{"},isComplete:function(state){return state.nextCh===state.symb}},preprocess:{init:function(state){state.index=0},isComplete:function(state){if("#"===state.nextCh){var token=state.lineText.match(/#(\w+)/)[1];if("endif"===token){if(state.forward&&0===state.depth)return!0;state.depth++}else if("if"===token){if(!state.forward&&0===state.depth)return!0;state.depth--}if("else"===token&&0===state.depth)return!0}return!1}}};defineOption("pcre",!0,"boolean");SearchState.prototype={getQuery:function(){return vimGlobalState.query},setQuery:function(query){vimGlobalState.query=query},getOverlay:function(){return this.searchOverlay},setOverlay:function(overlay){this.searchOverlay=overlay},isReversed:function(){return vimGlobalState.isReversed},setReversed:function(reversed){vimGlobalState.isReversed=reversed},getScrollbarAnnotate:function(){return this.annotate},setScrollbarAnnotate:function(annotate){this.annotate=annotate}};var charUnescapes={"\\n":"\n","\\r":"\r","\\t":"\t"},unescapes={"\\/":"/","\\\\":"\\","\\n":"\n","\\r":"\r","\\t":"\t"},searchPromptDesc="(Javascript regexp)",ExCommandDispatcher=function(){this.buildCommandMap_()};ExCommandDispatcher.prototype={processCommand:function(cm,input,opt_params){var that=this;cm.operation(function(){cm.curOp.isVimOp=!0;that._processCommand(cm,input,opt_params)})},_processCommand:function(cm,input,opt_params){var vim=cm.state.vim,commandHistoryRegister=vimGlobalState.registerController.getRegister(":"),previousCommand=commandHistoryRegister.toString();vim.visualMode&&exitVisualMode(cm);
4
+ var inputStream=new CodeMirror.StringStream(input);commandHistoryRegister.setText(input);var params=opt_params||{};params.input=input;try{this.parseInput_(cm,inputStream,params)}catch(e){showConfirm(cm,e);throw e}var command,commandName;if(params.commandName){command=this.matchCommand_(params.commandName);if(command){commandName=command.name;command.excludeFromCommandHistory&&commandHistoryRegister.setText(previousCommand);this.parseCommandArgs_(inputStream,params,command);if("exToKey"==command.type){for(var i=0;i<command.toKeys.length;i++)CodeMirror.Vim.handleKey(cm,command.toKeys[i],"mapping");return}if("exToEx"==command.type){this.processCommand(cm,command.toInput);return}}}else void 0!==params.line&&(commandName="move");if(commandName)try{exCommands[commandName](cm,params);command&&command.possiblyAsync||!params.callback||params.callback()}catch(e){showConfirm(cm,e);throw e}else showConfirm(cm,'Not an editor command ":'+input+'"')},parseInput_:function(cm,inputStream,result){inputStream.eatWhile(":");if(inputStream.eat("%")){result.line=cm.firstLine();result.lineEnd=cm.lastLine()}else{result.line=this.parseLineSpec_(cm,inputStream);void 0!==result.line&&inputStream.eat(",")&&(result.lineEnd=this.parseLineSpec_(cm,inputStream))}var commandMatch=inputStream.match(/^(\w+)/);commandMatch?result.commandName=commandMatch[1]:result.commandName=inputStream.match(/.*/)[0];return result},parseLineSpec_:function(cm,inputStream){var numberMatch=inputStream.match(/^(\d+)/);if(numberMatch)return parseInt(numberMatch[1],10)-1;switch(inputStream.next()){case".":return cm.getCursor().line;case"$":return cm.lastLine();case"'":var mark=cm.state.vim.marks[inputStream.next()];if(mark&&mark.find())return mark.find().line;throw new Error("Mark not set");default:inputStream.backUp(1);return}},parseCommandArgs_:function(inputStream,params,command){if(!inputStream.eol()){params.argString=inputStream.match(/.*/)[0];var delim=command.argDelimiter||/\s+/,args=trim(params.argString).split(delim);args.length&&args[0]&&(params.args=args)}},matchCommand_:function(commandName){for(var i=commandName.length;i>0;i--){var prefix=commandName.substring(0,i);if(this.commandMap_[prefix]){var command=this.commandMap_[prefix];if(0===command.name.indexOf(commandName))return command}}return null},buildCommandMap_:function(){this.commandMap_={};for(var i=0;i<defaultExCommandMap.length;i++){var command=defaultExCommandMap[i],key=command.shortName||command.name;this.commandMap_[key]=command}},map:function(lhs,rhs,ctx){if(":"!=lhs&&":"==lhs.charAt(0)){if(ctx)throw Error("Mode not supported for ex mappings");var commandName=lhs.substring(1);":"!=rhs&&":"==rhs.charAt(0)?this.commandMap_[commandName]={name:commandName,type:"exToEx",toInput:rhs.substring(1),user:!0}:this.commandMap_[commandName]={name:commandName,type:"exToKey",toKeys:rhs,user:!0}}else if(":"!=rhs&&":"==rhs.charAt(0)){var mapping={keys:lhs,type:"keyToEx",exArgs:{input:rhs.substring(1)},user:!0};ctx&&(mapping.context=ctx);defaultKeymap.unshift(mapping)}else{var mapping={keys:lhs,type:"keyToKey",toKeys:rhs,user:!0};ctx&&(mapping.context=ctx);defaultKeymap.unshift(mapping)}},unmap:function(lhs,ctx){if(":"!=lhs&&":"==lhs.charAt(0)){if(ctx)throw Error("Mode not supported for ex mappings");var commandName=lhs.substring(1);if(this.commandMap_[commandName]&&this.commandMap_[commandName].user){delete this.commandMap_[commandName];return}}else for(var keys=lhs,i=0;i<defaultKeymap.length;i++)if(keys==defaultKeymap[i].keys&&defaultKeymap[i].context===ctx&&defaultKeymap[i].user){defaultKeymap.splice(i,1);return}throw Error("No such mapping.")}};var exCommands={colorscheme:function(cm,params){!params.args||params.args.length<1?showConfirm(cm,cm.getOption("theme")):cm.setOption("theme",params.args[0])},map:function(cm,params,ctx){var mapArgs=params.args;!mapArgs||mapArgs.length<2?cm&&showConfirm(cm,"Invalid mapping: "+params.input):exCommandDispatcher.map(mapArgs[0],mapArgs[1],ctx)},imap:function(cm,params){this.map(cm,params,"insert")},nmap:function(cm,params){this.map(cm,params,"normal")},vmap:function(cm,params){this.map(cm,params,"visual")},unmap:function(cm,params,ctx){var mapArgs=params.args;!mapArgs||mapArgs.length<1?cm&&showConfirm(cm,"No such mapping: "+params.input):exCommandDispatcher.unmap(mapArgs[0],ctx)},move:function(cm,params){commandDispatcher.processCommand(cm,cm.state.vim,{type:"motion",motion:"moveToLineOrEdgeOfDocument",motionArgs:{forward:!1,explicitRepeat:!0,linewise:!0},repeatOverride:params.line+1})},set:function(cm,params){var setArgs=params.args,setCfg=params.setCfg||{};if(!setArgs||setArgs.length<1)cm&&showConfirm(cm,"Invalid mapping: "+params.input);else{var expr=setArgs[0].split("="),optionName=expr[0],value=expr[1],forceGet=!1;if("?"==optionName.charAt(optionName.length-1)){if(value)throw Error("Trailing characters: "+params.argString);optionName=optionName.substring(0,optionName.length-1);forceGet=!0}if(void 0===value&&"no"==optionName.substring(0,2)){optionName=optionName.substring(2);value=!1}var optionIsBoolean=options[optionName]&&"boolean"==options[optionName].type;optionIsBoolean&&void 0==value&&(value=!0);if(!optionIsBoolean&&void 0===value||forceGet){var oldValue=getOption(optionName,cm,setCfg);oldValue===!0||oldValue===!1?showConfirm(cm," "+(oldValue?"":"no")+optionName):showConfirm(cm," "+optionName+"="+oldValue)}else setOption(optionName,value,cm,setCfg)}},setlocal:function(cm,params){params.setCfg={scope:"local"};this.set(cm,params)},setglobal:function(cm,params){params.setCfg={scope:"global"};this.set(cm,params)},registers:function(cm,params){var regArgs=params.args,registers=vimGlobalState.registerController.registers,regInfo="----------Registers----------<br><br>";if(regArgs){var registerName;regArgs=regArgs.join("");for(var i=0;i<regArgs.length;i++){registerName=regArgs.charAt(i);if(vimGlobalState.registerController.isValidRegister(registerName)){var register=registers[registerName]||new Register;regInfo+='"'+registerName+" "+register.toString()+"<br>"}}}else for(var registerName in registers){var text=registers[registerName].toString();text.length&&(regInfo+='"'+registerName+" "+text+"<br>")}showConfirm(cm,regInfo)},sort:function(cm,params){function parseArgs(){if(params.argString){var args=new CodeMirror.StringStream(params.argString);args.eat("!")&&(reverse=!0);if(args.eol())return;if(!args.eatSpace())return"Invalid arguments";var opts=args.match(/[a-z]+/);if(opts){opts=opts[0];ignoreCase=opts.indexOf("i")!=-1;unique=opts.indexOf("u")!=-1;var decimal=opts.indexOf("d")!=-1&&1,hex=opts.indexOf("x")!=-1&&1,octal=opts.indexOf("o")!=-1&&1;if(decimal+hex+octal>1)return"Invalid arguments";number=decimal&&"decimal"||hex&&"hex"||octal&&"octal"}if(args.match(/\/.*\//))return"patterns not supported"}}function compareFn(a,b){if(reverse){var tmp;tmp=a;a=b;b=tmp}if(ignoreCase){a=a.toLowerCase();b=b.toLowerCase()}var anum=number&&numberRegex.exec(a),bnum=number&&numberRegex.exec(b);if(!anum)return a<b?-1:1;anum=parseInt((anum[1]+anum[2]).toLowerCase(),radix);bnum=parseInt((bnum[1]+bnum[2]).toLowerCase(),radix);return anum-bnum}var reverse,ignoreCase,unique,number,err=parseArgs();if(err)showConfirm(cm,err+": "+params.argString);else{var lineStart=params.line||cm.firstLine(),lineEnd=params.lineEnd||params.line||cm.lastLine();if(lineStart!=lineEnd){var curStart=Pos(lineStart,0),curEnd=Pos(lineEnd,lineLength(cm,lineEnd)),text=cm.getRange(curStart,curEnd).split("\n"),numberRegex="decimal"==number?/(-?)([\d]+)/:"hex"==number?/(-?)(?:0x)?([0-9a-f]+)/i:"octal"==number?/([0-7]+)/:null,radix="decimal"==number?10:"hex"==number?16:"octal"==number?8:null,numPart=[],textPart=[];if(number)for(var i=0;i<text.length;i++)numberRegex.exec(text[i])?numPart.push(text[i]):textPart.push(text[i]);else textPart=text;numPart.sort(compareFn);textPart.sort(compareFn);text=reverse?numPart.concat(textPart):textPart.concat(numPart);if(unique){var lastLine,textOld=text;text=[];for(var i=0;i<textOld.length;i++){textOld[i]!=lastLine&&text.push(textOld[i]);lastLine=textOld[i]}}cm.replaceRange(text.join("\n"),curStart,curEnd)}}},global:function(cm,params){var argString=params.argString;if(argString){var cmd,lineStart=void 0!==params.line?params.line:cm.firstLine(),lineEnd=params.lineEnd||params.line||cm.lastLine(),tokens=splitBySlash(argString),regexPart=argString;if(tokens.length){regexPart=tokens[0];cmd=tokens.slice(1,tokens.length).join("/")}if(regexPart)try{updateSearchQuery(cm,regexPart,!0,!0)}catch(e){showConfirm(cm,"Invalid regex: "+regexPart);return}for(var query=getSearchState(cm).getQuery(),matchedLines=[],content="",i=lineStart;i<=lineEnd;i++){var matched=query.test(cm.getLine(i));if(matched){matchedLines.push(i+1);content+=cm.getLine(i)+"<br>"}}if(cmd){var index=0,nextCommand=function(){if(index<matchedLines.length){var command=matchedLines[index]+cmd;exCommandDispatcher.processCommand(cm,command,{callback:nextCommand})}index++};nextCommand()}else showConfirm(cm,content)}else showConfirm(cm,"Regular Expression missing from global")},substitute:function(cm,params){if(!cm.getSearchCursor)throw new Error("Search feature not available. Requires searchcursor.js or any other getSearchCursor implementation.");var regexPart,trailing,flagsPart,count,argString=params.argString,tokens=argString?splitBySlash(argString):[],replacePart="",confirm=!1,global=!1;if(tokens.length){regexPart=tokens[0];replacePart=tokens[1];if(void 0!==replacePart){replacePart=getOption("pcre")?unescapeRegexReplace(replacePart):translateRegexReplace(replacePart);vimGlobalState.lastSubstituteReplacePart=replacePart}trailing=tokens[2]?tokens[2].split(" "):[]}else if(argString&&argString.length){showConfirm(cm,"Substitutions should be of the form :s/pattern/replace/");return}if(trailing){flagsPart=trailing[0];count=parseInt(trailing[1]);if(flagsPart){if(flagsPart.indexOf("c")!=-1){confirm=!0;flagsPart.replace("c","")}if(flagsPart.indexOf("g")!=-1){global=!0;flagsPart.replace("g","")}regexPart=regexPart+"/"+flagsPart}}if(regexPart)try{updateSearchQuery(cm,regexPart,!0,!0)}catch(e){showConfirm(cm,"Invalid regex: "+regexPart);return}replacePart=replacePart||vimGlobalState.lastSubstituteReplacePart;if(void 0!==replacePart){var state=getSearchState(cm),query=state.getQuery(),lineStart=void 0!==params.line?params.line:cm.getCursor().line,lineEnd=params.lineEnd||lineStart;lineStart==cm.firstLine()&&lineEnd==cm.lastLine()&&(lineEnd=1/0);if(count){lineStart=lineEnd;lineEnd=lineStart+count-1}var startPos=clipCursorToContent(cm,Pos(lineStart,0)),cursor=cm.getSearchCursor(query,startPos);doReplace(cm,confirm,global,lineStart,lineEnd,cursor,query,replacePart,params.callback)}else showConfirm(cm,"No previous substitute regular expression")},redo:CodeMirror.commands.redo,undo:CodeMirror.commands.undo,write:function(cm){CodeMirror.commands.save?CodeMirror.commands.save(cm):cm.save&&cm.save()},nohlsearch:function(cm){clearSearchHighlight(cm)},yank:function(cm){var cur=copyCursor(cm.getCursor()),line=cur.line,lineText=cm.getLine(line);vimGlobalState.registerController.pushText("0","yank",lineText,!0,!0)},delmarks:function(cm,params){if(params.argString&&trim(params.argString))for(var state=cm.state.vim,stream=new CodeMirror.StringStream(trim(params.argString));!stream.eol();){stream.eatSpace();var count=stream.pos;if(!stream.match(/[a-zA-Z]/,!1)){showConfirm(cm,"Invalid argument: "+params.argString.substring(count));return}var sym=stream.next();if(stream.match("-",!0)){if(!stream.match(/[a-zA-Z]/,!1)){showConfirm(cm,"Invalid argument: "+params.argString.substring(count));return}var startMark=sym,finishMark=stream.next();if(!(isLowerCase(startMark)&&isLowerCase(finishMark)||isUpperCase(startMark)&&isUpperCase(finishMark))){showConfirm(cm,"Invalid argument: "+startMark+"-");return}var start=startMark.charCodeAt(0),finish=finishMark.charCodeAt(0);if(start>=finish){showConfirm(cm,"Invalid argument: "+params.argString.substring(count));return}for(var j=0;j<=finish-start;j++){var mark=String.fromCharCode(start+j);delete state.marks[mark]}}else delete state.marks[sym]}else showConfirm(cm,"Argument required")}},exCommandDispatcher=new ExCommandDispatcher;CodeMirror.keyMap.vim={attach:attachVimMap,detach:detachVimMap,call:cmKey};defineOption("insertModeEscKeysTimeout",200,"number");CodeMirror.keyMap["vim-insert"]={fallthrough:["default"],attach:attachVimMap,detach:detachVimMap,call:cmKey};CodeMirror.keyMap["vim-replace"]={Backspace:"goCharLeft",fallthrough:["vim-insert"],attach:attachVimMap,detach:detachVimMap,call:cmKey};resetVimGlobalState();return vimApi};CodeMirror.Vim=Vim()});
js/esites_editor/dist/js/vendor/codemirror/lib/codemirror.css CHANGED
@@ -1 +1 @@
1
- .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;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-ruler{border-left:1px solid #ccc;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:0 0!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{-webkit-user-select:none;-moz-user-select:none;user-select:none}.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:none;font-variant-ligatures:none}.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-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}.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}
1
+ .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:0 0!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{-webkit-user-select:none;-moz-user-select:none;user-select:none}.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-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}
js/esites_editor/dist/js/vendor/codemirror/lib/codemirror.js CHANGED
@@ -1,7 +1,8 @@
1
- !function(mod){if("object"==typeof exports&&"object"==typeof module)module.exports=mod();else{if("function"==typeof define&&define.amd)return define([],mod);(this||window).CodeMirror=mod()}}(function(){"use strict";function CodeMirror(place,options){if(!(this instanceof CodeMirror))return new CodeMirror(place,options);this.options=options=options?copyObj(options):{};copyObj(defaults,options,!1);setGuttersForLineNumbers(options);var doc=options.value;"string"==typeof doc&&(doc=new Doc(doc,options.mode,null,options.lineSeparator));this.doc=doc;var input=new CodeMirror.inputStyles[options.inputStyle](this),display=this.display=new Display(place,doc,input);display.wrapper.CodeMirror=this;updateGutters(this);themeChanged(this);options.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap");options.autofocus&&!mobile&&display.input.focus();initScrollbars(this);this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,delayingBlurEvent:!1,focused:!1,suppressEdits:!1,pasteIncoming:!1,cutIncoming:!1,selectingText:!1,draggingText:!1,highlight:new Delayed,keySeq:null,specialChars:null};var cm=this;ie&&11>ie_version&&setTimeout(function(){cm.display.input.reset(!0)},20);registerEventHandlers(this);ensureGlobalHandlers();startOperation(this);this.curOp.forceUpdate=!0;attachDoc(this,doc);options.autofocus&&!mobile||cm.hasFocus()?setTimeout(bind(onFocus,this),20):onBlur(this);for(var opt in optionHandlers)optionHandlers.hasOwnProperty(opt)&&optionHandlers[opt](this,options[opt],Init);maybeUpdateLineNumberWidth(this);options.finishInit&&options.finishInit(this);for(var i=0;i<initHooks.length;++i)initHooks[i](this);endOperation(this);webkit&&options.lineWrapping&&"optimizelegibility"==getComputedStyle(display.lineDiv).textRendering&&(display.lineDiv.style.textRendering="auto")}function Display(place,doc,input){var d=this;this.input=input;d.scrollbarFiller=elt("div",null,"CodeMirror-scrollbar-filler");d.scrollbarFiller.setAttribute("cm-not-content","true");d.gutterFiller=elt("div",null,"CodeMirror-gutter-filler");d.gutterFiller.setAttribute("cm-not-content","true");d.lineDiv=elt("div",null,"CodeMirror-code");d.selectionDiv=elt("div",null,null,"position: relative; z-index: 1");d.cursorDiv=elt("div",null,"CodeMirror-cursors");d.measure=elt("div",null,"CodeMirror-measure");d.lineMeasure=elt("div",null,"CodeMirror-measure");d.lineSpace=elt("div",[d.measure,d.lineMeasure,d.selectionDiv,d.cursorDiv,d.lineDiv],null,"position: relative; outline: none");d.mover=elt("div",[elt("div",[d.lineSpace],"CodeMirror-lines")],null,"position: relative");d.sizer=elt("div",[d.mover],"CodeMirror-sizer");d.sizerWidth=null;d.heightForcer=elt("div",null,null,"position: absolute; height: "+scrollerGap+"px; width: 1px;");d.gutters=elt("div",null,"CodeMirror-gutters");d.lineGutter=null;d.scroller=elt("div",[d.sizer,d.heightForcer,d.gutters],"CodeMirror-scroll");d.scroller.setAttribute("tabIndex","-1");d.wrapper=elt("div",[d.scrollbarFiller,d.gutterFiller,d.scroller],"CodeMirror");if(ie&&8>ie_version){d.gutters.style.zIndex=-1;d.scroller.style.paddingRight=0}webkit||gecko&&mobile||(d.scroller.draggable=!0);place&&(place.appendChild?place.appendChild(d.wrapper):place(d.wrapper));d.viewFrom=d.viewTo=doc.first;d.reportedViewFrom=d.reportedViewTo=doc.first;d.view=[];d.renderedView=null;d.externalMeasured=null;d.viewOffset=0;d.lastWrapHeight=d.lastWrapWidth=0;d.updateLineNumbers=null;d.nativeBarWidth=d.barHeight=d.barWidth=0;d.scrollbarsClipped=!1;d.lineNumWidth=d.lineNumInnerWidth=d.lineNumChars=null;d.alignWidgets=!1;d.cachedCharWidth=d.cachedTextHeight=d.cachedPaddingH=null;d.maxLine=null;d.maxLineLength=0;d.maxLineChanged=!1;d.wheelDX=d.wheelDY=d.wheelStartX=d.wheelStartY=null;d.shift=!1;d.selForContextMenu=null;d.activeTouch=null;input.init(d)}function loadMode(cm){cm.doc.mode=CodeMirror.getMode(cm.options,cm.doc.modeOption);resetModeState(cm)}function resetModeState(cm){cm.doc.iter(function(line){line.stateAfter&&(line.stateAfter=null);line.styles&&(line.styles=null)});cm.doc.frontier=cm.doc.first;startWorker(cm,100);cm.state.modeGen++;cm.curOp&&regChange(cm)}function wrappingChanged(cm){if(cm.options.lineWrapping){addClass(cm.display.wrapper,"CodeMirror-wrap");cm.display.sizer.style.minWidth="";cm.display.sizerWidth=null}else{rmClass(cm.display.wrapper,"CodeMirror-wrap");findMaxLine(cm)}estimateLineHeights(cm);regChange(cm);clearCaches(cm);setTimeout(function(){updateScrollbars(cm)},100)}function estimateHeight(cm){var th=textHeight(cm.display),wrapping=cm.options.lineWrapping,perLine=wrapping&&Math.max(5,cm.display.scroller.clientWidth/charWidth(cm.display)-3);return function(line){if(lineIsHidden(cm.doc,line))return 0;var widgetsHeight=0;if(line.widgets)for(var i=0;i<line.widgets.length;i++)line.widgets[i].height&&(widgetsHeight+=line.widgets[i].height);return wrapping?widgetsHeight+(Math.ceil(line.text.length/perLine)||1)*th:widgetsHeight+th}}function estimateLineHeights(cm){var doc=cm.doc,est=estimateHeight(cm);doc.iter(function(line){var estHeight=est(line);estHeight!=line.height&&updateLineHeight(line,estHeight)})}function themeChanged(cm){cm.display.wrapper.className=cm.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+cm.options.theme.replace(/(^|\s)\s*/g," cm-s-");clearCaches(cm)}function guttersChanged(cm){updateGutters(cm);regChange(cm);setTimeout(function(){alignHorizontally(cm)},20)}function updateGutters(cm){var gutters=cm.display.gutters,specs=cm.options.gutters;removeChildren(gutters);for(var i=0;i<specs.length;++i){var gutterClass=specs[i],gElt=gutters.appendChild(elt("div",null,"CodeMirror-gutter "+gutterClass));if("CodeMirror-linenumbers"==gutterClass){cm.display.lineGutter=gElt;gElt.style.width=(cm.display.lineNumWidth||1)+"px"}}gutters.style.display=i?"":"none";updateGutterSpace(cm)}function updateGutterSpace(cm){var width=cm.display.gutters.offsetWidth;cm.display.sizer.style.marginLeft=width+"px"}function lineLength(line){if(0==line.height)return 0;for(var merged,len=line.text.length,cur=line;merged=collapsedSpanAtStart(cur);){var found=merged.find(0,!0);cur=found.from.line;len+=found.from.ch-found.to.ch}cur=line;for(;merged=collapsedSpanAtEnd(cur);){var found=merged.find(0,!0);len-=cur.text.length-found.from.ch;cur=found.to.line;len+=cur.text.length-found.to.ch}return len}function findMaxLine(cm){var d=cm.display,doc=cm.doc;d.maxLine=getLine(doc,doc.first);d.maxLineLength=lineLength(d.maxLine);d.maxLineChanged=!0;doc.iter(function(line){var len=lineLength(line);if(len>d.maxLineLength){d.maxLineLength=len;d.maxLine=line}})}function setGuttersForLineNumbers(options){var found=indexOf(options.gutters,"CodeMirror-linenumbers");if(-1==found&&options.lineNumbers)options.gutters=options.gutters.concat(["CodeMirror-linenumbers"]);else if(found>-1&&!options.lineNumbers){options.gutters=options.gutters.slice(0);options.gutters.splice(found,1)}}function measureForScrollbars(cm){var d=cm.display,gutterW=d.gutters.offsetWidth,docH=Math.round(cm.doc.height+paddingVert(cm.display));return{clientHeight:d.scroller.clientHeight,viewHeight:d.wrapper.clientHeight,scrollWidth:d.scroller.scrollWidth,clientWidth:d.scroller.clientWidth,viewWidth:d.wrapper.clientWidth,barLeft:cm.options.fixedGutter?gutterW:0,docHeight:docH,scrollHeight:docH+scrollGap(cm)+d.barHeight,nativeBarWidth:d.nativeBarWidth,gutterWidth:gutterW}}function NativeScrollbars(place,scroll,cm){this.cm=cm;var vert=this.vert=elt("div",[elt("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),horiz=this.horiz=elt("div",[elt("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");place(vert);place(horiz);on(vert,"scroll",function(){vert.clientHeight&&scroll(vert.scrollTop,"vertical")});on(horiz,"scroll",function(){horiz.clientWidth&&scroll(horiz.scrollLeft,"horizontal")});this.checkedZeroWidth=!1;ie&&8>ie_version&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px")}function NullScrollbars(){}function initScrollbars(cm){if(cm.display.scrollbars){cm.display.scrollbars.clear();cm.display.scrollbars.addClass&&rmClass(cm.display.wrapper,cm.display.scrollbars.addClass)}cm.display.scrollbars=new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node){cm.display.wrapper.insertBefore(node,cm.display.scrollbarFiller);on(node,"mousedown",function(){cm.state.focused&&setTimeout(function(){cm.display.input.focus()},0)});node.setAttribute("cm-not-content","true")},function(pos,axis){"horizontal"==axis?setScrollLeft(cm,pos):setScrollTop(cm,pos)},cm);cm.display.scrollbars.addClass&&addClass(cm.display.wrapper,cm.display.scrollbars.addClass)}function updateScrollbars(cm,measure){measure||(measure=measureForScrollbars(cm));var startWidth=cm.display.barWidth,startHeight=cm.display.barHeight;updateScrollbarsInner(cm,measure);for(var i=0;4>i&&startWidth!=cm.display.barWidth||startHeight!=cm.display.barHeight;i++){startWidth!=cm.display.barWidth&&cm.options.lineWrapping&&updateHeightsInViewport(cm);updateScrollbarsInner(cm,measureForScrollbars(cm));startWidth=cm.display.barWidth;startHeight=cm.display.barHeight}}function updateScrollbarsInner(cm,measure){var d=cm.display,sizes=d.scrollbars.update(measure);d.sizer.style.paddingRight=(d.barWidth=sizes.right)+"px";d.sizer.style.paddingBottom=(d.barHeight=sizes.bottom)+"px";d.heightForcer.style.borderBottom=sizes.bottom+"px solid transparent";if(sizes.right&&sizes.bottom){d.scrollbarFiller.style.display="block";d.scrollbarFiller.style.height=sizes.bottom+"px";d.scrollbarFiller.style.width=sizes.right+"px"}else d.scrollbarFiller.style.display="";if(sizes.bottom&&cm.options.coverGutterNextToScrollbar&&cm.options.fixedGutter){d.gutterFiller.style.display="block";d.gutterFiller.style.height=sizes.bottom+"px";d.gutterFiller.style.width=measure.gutterWidth+"px"}else d.gutterFiller.style.display=""}function visibleLines(display,doc,viewport){var top=viewport&&null!=viewport.top?Math.max(0,viewport.top):display.scroller.scrollTop;top=Math.floor(top-paddingTop(display));var bottom=viewport&&null!=viewport.bottom?viewport.bottom:top+display.wrapper.clientHeight,from=lineAtHeight(doc,top),to=lineAtHeight(doc,bottom);if(viewport&&viewport.ensure){var ensureFrom=viewport.ensure.from.line,ensureTo=viewport.ensure.to.line;if(from>ensureFrom){from=ensureFrom;to=lineAtHeight(doc,heightAtLine(getLine(doc,ensureFrom))+display.wrapper.clientHeight)}else if(Math.min(ensureTo,doc.lastLine())>=to){from=lineAtHeight(doc,heightAtLine(getLine(doc,ensureTo))-display.wrapper.clientHeight);to=ensureTo}}return{from:from,to:Math.max(to,from+1)}}function alignHorizontally(cm){var display=cm.display,view=display.view;if(display.alignWidgets||display.gutters.firstChild&&cm.options.fixedGutter){for(var comp=compensateForHScroll(display)-display.scroller.scrollLeft+cm.doc.scrollLeft,gutterW=display.gutters.offsetWidth,left=comp+"px",i=0;i<view.length;i++)if(!view[i].hidden){cm.options.fixedGutter&&view[i].gutter&&(view[i].gutter.style.left=left);var align=view[i].alignable;if(align)for(var j=0;j<align.length;j++)align[j].style.left=left}cm.options.fixedGutter&&(display.gutters.style.left=comp+gutterW+"px")}}function maybeUpdateLineNumberWidth(cm){if(!cm.options.lineNumbers)return!1;var doc=cm.doc,last=lineNumberFor(cm.options,doc.first+doc.size-1),display=cm.display;if(last.length!=display.lineNumChars){var test=display.measure.appendChild(elt("div",[elt("div",last)],"CodeMirror-linenumber CodeMirror-gutter-elt")),innerW=test.firstChild.offsetWidth,padding=test.offsetWidth-innerW;display.lineGutter.style.width="";display.lineNumInnerWidth=Math.max(innerW,display.lineGutter.offsetWidth-padding)+1;display.lineNumWidth=display.lineNumInnerWidth+padding;display.lineNumChars=display.lineNumInnerWidth?last.length:-1;display.lineGutter.style.width=display.lineNumWidth+"px";updateGutterSpace(cm);return!0}return!1}function lineNumberFor(options,i){return String(options.lineNumberFormatter(i+options.firstLineNumber))}function compensateForHScroll(display){return display.scroller.getBoundingClientRect().left-display.sizer.getBoundingClientRect().left}function DisplayUpdate(cm,viewport,force){var display=cm.display;this.viewport=viewport;this.visible=visibleLines(display,cm.doc,viewport);this.editorIsHidden=!display.wrapper.offsetWidth;this.wrapperHeight=display.wrapper.clientHeight;this.wrapperWidth=display.wrapper.clientWidth;this.oldDisplayWidth=displayWidth(cm);this.force=force;this.dims=getDimensions(cm);this.events=[]}function maybeClipScrollbars(cm){var display=cm.display;if(!display.scrollbarsClipped&&display.scroller.offsetWidth){display.nativeBarWidth=display.scroller.offsetWidth-display.scroller.clientWidth;display.heightForcer.style.height=scrollGap(cm)+"px";display.sizer.style.marginBottom=-display.nativeBarWidth+"px";display.sizer.style.borderRightWidth=scrollGap(cm)+"px";display.scrollbarsClipped=!0}}function updateDisplayIfNeeded(cm,update){var display=cm.display,doc=cm.doc;if(update.editorIsHidden){resetView(cm);return!1}if(!update.force&&update.visible.from>=display.viewFrom&&update.visible.to<=display.viewTo&&(null==display.updateLineNumbers||display.updateLineNumbers>=display.viewTo)&&display.renderedView==display.view&&0==countDirtyView(cm))return!1;if(maybeUpdateLineNumberWidth(cm)){resetView(cm);update.dims=getDimensions(cm)}var end=doc.first+doc.size,from=Math.max(update.visible.from-cm.options.viewportMargin,doc.first),to=Math.min(end,update.visible.to+cm.options.viewportMargin);display.viewFrom<from&&from-display.viewFrom<20&&(from=Math.max(doc.first,display.viewFrom));display.viewTo>to&&display.viewTo-to<20&&(to=Math.min(end,display.viewTo));if(sawCollapsedSpans){from=visualLineNo(cm.doc,from);to=visualLineEndNo(cm.doc,to)}var different=from!=display.viewFrom||to!=display.viewTo||display.lastWrapHeight!=update.wrapperHeight||display.lastWrapWidth!=update.wrapperWidth;adjustView(cm,from,to);display.viewOffset=heightAtLine(getLine(cm.doc,display.viewFrom));cm.display.mover.style.top=display.viewOffset+"px";var toUpdate=countDirtyView(cm);if(!different&&0==toUpdate&&!update.force&&display.renderedView==display.view&&(null==display.updateLineNumbers||display.updateLineNumbers>=display.viewTo))return!1;var focused=activeElt();toUpdate>4&&(display.lineDiv.style.display="none");patchDisplay(cm,display.updateLineNumbers,update.dims);toUpdate>4&&(display.lineDiv.style.display="");display.renderedView=display.view;focused&&activeElt()!=focused&&focused.offsetHeight&&focused.focus();removeChildren(display.cursorDiv);removeChildren(display.selectionDiv);display.gutters.style.height=display.sizer.style.minHeight=0;if(different){display.lastWrapHeight=update.wrapperHeight;display.lastWrapWidth=update.wrapperWidth;startWorker(cm,400)}display.updateLineNumbers=null;return!0}function postUpdateDisplay(cm,update){for(var viewport=update.viewport,first=!0;;first=!1){if(!first||!cm.options.lineWrapping||update.oldDisplayWidth==displayWidth(cm)){viewport&&null!=viewport.top&&(viewport={top:Math.min(cm.doc.height+paddingVert(cm.display)-displayHeight(cm),viewport.top)});update.visible=visibleLines(cm.display,cm.doc,viewport);if(update.visible.from>=cm.display.viewFrom&&update.visible.to<=cm.display.viewTo)break}if(!updateDisplayIfNeeded(cm,update))break;updateHeightsInViewport(cm);var barMeasure=measureForScrollbars(cm);updateSelection(cm);updateScrollbars(cm,barMeasure);setDocumentHeight(cm,barMeasure)}update.signal(cm,"update",cm);if(cm.display.viewFrom!=cm.display.reportedViewFrom||cm.display.viewTo!=cm.display.reportedViewTo){update.signal(cm,"viewportChange",cm,cm.display.viewFrom,cm.display.viewTo);cm.display.reportedViewFrom=cm.display.viewFrom;cm.display.reportedViewTo=cm.display.viewTo}}function updateDisplaySimple(cm,viewport){var update=new DisplayUpdate(cm,viewport);if(updateDisplayIfNeeded(cm,update)){updateHeightsInViewport(cm);postUpdateDisplay(cm,update);var barMeasure=measureForScrollbars(cm);updateSelection(cm);updateScrollbars(cm,barMeasure);setDocumentHeight(cm,barMeasure);update.finish()}}function setDocumentHeight(cm,measure){cm.display.sizer.style.minHeight=measure.docHeight+"px";cm.display.heightForcer.style.top=measure.docHeight+"px";cm.display.gutters.style.height=measure.docHeight+cm.display.barHeight+scrollGap(cm)+"px"}function updateHeightsInViewport(cm){for(var display=cm.display,prevBottom=display.lineDiv.offsetTop,i=0;i<display.view.length;i++){var height,cur=display.view[i];if(!cur.hidden){if(ie&&8>ie_version){var bot=cur.node.offsetTop+cur.node.offsetHeight;height=bot-prevBottom;prevBottom=bot}else{var box=cur.node.getBoundingClientRect();height=box.bottom-box.top}var diff=cur.line.height-height;2>height&&(height=textHeight(display));if(diff>.001||-.001>diff){updateLineHeight(cur.line,height);updateWidgetHeight(cur.line);if(cur.rest)for(var j=0;j<cur.rest.length;j++)updateWidgetHeight(cur.rest[j])}}}}function updateWidgetHeight(line){if(line.widgets)for(var i=0;i<line.widgets.length;++i)line.widgets[i].height=line.widgets[i].node.parentNode.offsetHeight}function getDimensions(cm){for(var d=cm.display,left={},width={},gutterLeft=d.gutters.clientLeft,n=d.gutters.firstChild,i=0;n;n=n.nextSibling,++i){left[cm.options.gutters[i]]=n.offsetLeft+n.clientLeft+gutterLeft;width[cm.options.gutters[i]]=n.clientWidth}return{fixedPos:compensateForHScroll(d),gutterTotalWidth:d.gutters.offsetWidth,gutterLeft:left,gutterWidth:width,wrapperWidth:d.wrapper.clientWidth}}function patchDisplay(cm,updateNumbersFrom,dims){function rm(node){var next=node.nextSibling;webkit&&mac&&cm.display.currentWheelTarget==node?node.style.display="none":node.parentNode.removeChild(node);return next}for(var display=cm.display,lineNumbers=cm.options.lineNumbers,container=display.lineDiv,cur=container.firstChild,view=display.view,lineN=display.viewFrom,i=0;i<view.length;i++){var lineView=view[i];if(lineView.hidden);else if(lineView.node&&lineView.node.parentNode==container){for(;cur!=lineView.node;)cur=rm(cur);var updateNumber=lineNumbers&&null!=updateNumbersFrom&&lineN>=updateNumbersFrom&&lineView.lineNumber;if(lineView.changes){indexOf(lineView.changes,"gutter")>-1&&(updateNumber=!1);updateLineForChanges(cm,lineView,lineN,dims)}if(updateNumber){removeChildren(lineView.lineNumber);lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options,lineN)))}cur=lineView.node.nextSibling}else{var node=buildLineElement(cm,lineView,lineN,dims);container.insertBefore(node,cur)}lineN+=lineView.size}for(;cur;)cur=rm(cur)}function updateLineForChanges(cm,lineView,lineN,dims){for(var j=0;j<lineView.changes.length;j++){var type=lineView.changes[j];"text"==type?updateLineText(cm,lineView):"gutter"==type?updateLineGutter(cm,lineView,lineN,dims):"class"==type?updateLineClasses(lineView):"widget"==type&&updateLineWidgets(cm,lineView,dims)}lineView.changes=null}function ensureLineWrapped(lineView){if(lineView.node==lineView.text){lineView.node=elt("div",null,null,"position: relative");lineView.text.parentNode&&lineView.text.parentNode.replaceChild(lineView.node,lineView.text);lineView.node.appendChild(lineView.text);ie&&8>ie_version&&(lineView.node.style.zIndex=2)}return lineView.node}function updateLineBackground(lineView){var cls=lineView.bgClass?lineView.bgClass+" "+(lineView.line.bgClass||""):lineView.line.bgClass;cls&&(cls+=" CodeMirror-linebackground");if(lineView.background)if(cls)lineView.background.className=cls;else{lineView.background.parentNode.removeChild(lineView.background);lineView.background=null}else if(cls){var wrap=ensureLineWrapped(lineView);lineView.background=wrap.insertBefore(elt("div",null,cls),wrap.firstChild)}}function getLineContent(cm,lineView){var ext=cm.display.externalMeasured;if(ext&&ext.line==lineView.line){cm.display.externalMeasured=null;lineView.measure=ext.measure;return ext.built}return buildLineContent(cm,lineView)}function updateLineText(cm,lineView){var cls=lineView.text.className,built=getLineContent(cm,lineView);lineView.text==lineView.node&&(lineView.node=built.pre);lineView.text.parentNode.replaceChild(built.pre,lineView.text);lineView.text=built.pre;if(built.bgClass!=lineView.bgClass||built.textClass!=lineView.textClass){lineView.bgClass=built.bgClass;lineView.textClass=built.textClass;updateLineClasses(lineView)}else cls&&(lineView.text.className=cls)}function updateLineClasses(lineView){updateLineBackground(lineView);lineView.line.wrapClass?ensureLineWrapped(lineView).className=lineView.line.wrapClass:lineView.node!=lineView.text&&(lineView.node.className="");var textClass=lineView.textClass?lineView.textClass+" "+(lineView.line.textClass||""):lineView.line.textClass;lineView.text.className=textClass||""}function updateLineGutter(cm,lineView,lineN,dims){if(lineView.gutter){lineView.node.removeChild(lineView.gutter);lineView.gutter=null}if(lineView.gutterBackground){lineView.node.removeChild(lineView.gutterBackground);lineView.gutterBackground=null}if(lineView.line.gutterClass){var wrap=ensureLineWrapped(lineView);lineView.gutterBackground=elt("div",null,"CodeMirror-gutter-background "+lineView.line.gutterClass,"left: "+(cm.options.fixedGutter?dims.fixedPos:-dims.gutterTotalWidth)+"px; width: "+dims.gutterTotalWidth+"px");wrap.insertBefore(lineView.gutterBackground,lineView.text)}var markers=lineView.line.gutterMarkers;if(cm.options.lineNumbers||markers){var wrap=ensureLineWrapped(lineView),gutterWrap=lineView.gutter=elt("div",null,"CodeMirror-gutter-wrapper","left: "+(cm.options.fixedGutter?dims.fixedPos:-dims.gutterTotalWidth)+"px");cm.display.input.setUneditable(gutterWrap);wrap.insertBefore(gutterWrap,lineView.text);lineView.line.gutterClass&&(gutterWrap.className+=" "+lineView.line.gutterClass);!cm.options.lineNumbers||markers&&markers["CodeMirror-linenumbers"]||(lineView.lineNumber=gutterWrap.appendChild(elt("div",lineNumberFor(cm.options,lineN),"CodeMirror-linenumber CodeMirror-gutter-elt","left: "+dims.gutterLeft["CodeMirror-linenumbers"]+"px; width: "+cm.display.lineNumInnerWidth+"px")));if(markers)for(var k=0;k<cm.options.gutters.length;++k){var id=cm.options.gutters[k],found=markers.hasOwnProperty(id)&&markers[id];found&&gutterWrap.appendChild(elt("div",[found],"CodeMirror-gutter-elt","left: "+dims.gutterLeft[id]+"px; width: "+dims.gutterWidth[id]+"px"))}}}function updateLineWidgets(cm,lineView,dims){lineView.alignable&&(lineView.alignable=null);for(var next,node=lineView.node.firstChild;node;node=next){var next=node.nextSibling;"CodeMirror-linewidget"==node.className&&lineView.node.removeChild(node)}insertLineWidgets(cm,lineView,dims)}function buildLineElement(cm,lineView,lineN,dims){var built=getLineContent(cm,lineView);lineView.text=lineView.node=built.pre;built.bgClass&&(lineView.bgClass=built.bgClass);built.textClass&&(lineView.textClass=built.textClass);updateLineClasses(lineView);updateLineGutter(cm,lineView,lineN,dims);insertLineWidgets(cm,lineView,dims);return lineView.node}function insertLineWidgets(cm,lineView,dims){insertLineWidgetsFor(cm,lineView.line,lineView,dims,!0);if(lineView.rest)for(var i=0;i<lineView.rest.length;i++)insertLineWidgetsFor(cm,lineView.rest[i],lineView,dims,!1)}function insertLineWidgetsFor(cm,line,lineView,dims,allowAbove){if(line.widgets)for(var wrap=ensureLineWrapped(lineView),i=0,ws=line.widgets;i<ws.length;++i){var widget=ws[i],node=elt("div",[widget.node],"CodeMirror-linewidget");widget.handleMouseEvents||node.setAttribute("cm-ignore-events","true");positionLineWidget(widget,node,lineView,dims);cm.display.input.setUneditable(node);allowAbove&&widget.above?wrap.insertBefore(node,lineView.gutter||lineView.text):wrap.appendChild(node);signalLater(widget,"redraw")}}function positionLineWidget(widget,node,lineView,dims){if(widget.noHScroll){(lineView.alignable||(lineView.alignable=[])).push(node);var width=dims.wrapperWidth;node.style.left=dims.fixedPos+"px";if(!widget.coverGutter){width-=dims.gutterTotalWidth;node.style.paddingLeft=dims.gutterTotalWidth+"px"}node.style.width=width+"px"}if(widget.coverGutter){node.style.zIndex=5;node.style.position="relative";widget.noHScroll||(node.style.marginLeft=-dims.gutterTotalWidth+"px")}}function copyPos(x){return Pos(x.line,x.ch)}function maxPos(a,b){return cmp(a,b)<0?b:a}function minPos(a,b){return cmp(a,b)<0?a:b}function ensureFocus(cm){if(!cm.state.focused){cm.display.input.focus();onFocus(cm)}}function applyTextInput(cm,inserted,deleted,sel,origin){var doc=cm.doc;cm.display.shift=!1;sel||(sel=doc.sel);var paste=cm.state.pasteIncoming||"paste"==origin,textLines=doc.splitLines(inserted),multiPaste=null;if(paste&&sel.ranges.length>1)if(lastCopied&&lastCopied.join("\n")==inserted){if(sel.ranges.length%lastCopied.length==0){multiPaste=[];for(var i=0;i<lastCopied.length;i++)multiPaste.push(doc.splitLines(lastCopied[i]))}}else textLines.length==sel.ranges.length&&(multiPaste=map(textLines,function(l){return[l]}));for(var i=sel.ranges.length-1;i>=0;i--){var range=sel.ranges[i],from=range.from(),to=range.to();range.empty()&&(deleted&&deleted>0?from=Pos(from.line,from.ch-deleted):cm.state.overwrite&&!paste&&(to=Pos(to.line,Math.min(getLine(doc,to.line).text.length,to.ch+lst(textLines).length))));var updateInput=cm.curOp.updateInput,changeEvent={from:from,to:to,text:multiPaste?multiPaste[i%multiPaste.length]:textLines,origin:origin||(paste?"paste":cm.state.cutIncoming?"cut":"+input")};makeChange(cm.doc,changeEvent);signalLater(cm,"inputRead",cm,changeEvent)}inserted&&!paste&&triggerElectric(cm,inserted);ensureCursorVisible(cm);cm.curOp.updateInput=updateInput;cm.curOp.typing=!0;cm.state.pasteIncoming=cm.state.cutIncoming=!1}function handlePaste(e,cm){var pasted=e.clipboardData&&e.clipboardData.getData("text/plain");if(pasted){e.preventDefault();cm.isReadOnly()||cm.options.disableInput||runInOp(cm,function(){applyTextInput(cm,pasted,0,null,"paste")});return!0}}function triggerElectric(cm,inserted){if(cm.options.electricChars&&cm.options.smartIndent)for(var sel=cm.doc.sel,i=sel.ranges.length-1;i>=0;i--){var range=sel.ranges[i];if(!(range.head.ch>100||i&&sel.ranges[i-1].head.line==range.head.line)){var mode=cm.getModeAt(range.head),indented=!1;if(mode.electricChars){for(var j=0;j<mode.electricChars.length;j++)if(inserted.indexOf(mode.electricChars.charAt(j))>-1){indented=indentLine(cm,range.head.line,"smart");break}}else mode.electricInput&&mode.electricInput.test(getLine(cm.doc,range.head.line).text.slice(0,range.head.ch))&&(indented=indentLine(cm,range.head.line,"smart"));indented&&signalLater(cm,"electricInput",cm,range.head.line)}}}function copyableRanges(cm){for(var text=[],ranges=[],i=0;i<cm.doc.sel.ranges.length;i++){var line=cm.doc.sel.ranges[i].head.line,lineRange={anchor:Pos(line,0),head:Pos(line+1,0)};ranges.push(lineRange);text.push(cm.getRange(lineRange.anchor,lineRange.head))}return{text:text,ranges:ranges}}function disableBrowserMagic(field){field.setAttribute("autocorrect","off");field.setAttribute("autocapitalize","off");field.setAttribute("spellcheck","false")}function TextareaInput(cm){this.cm=cm;this.prevInput="";this.pollingFast=!1;this.polling=new Delayed;this.inaccurateSelection=!1;this.hasSelection=!1;this.composing=null}function hiddenTextarea(){var te=elt("textarea",null,null,"position: absolute; padding: 0; width: 1px; height: 1em; outline: none"),div=elt("div",[te],null,"overflow: hidden; position: relative; width: 3px; height: 0px;");webkit?te.style.width="1000px":te.setAttribute("wrap","off");ios&&(te.style.border="1px solid black");disableBrowserMagic(te);return div}function ContentEditableInput(cm){this.cm=cm;this.lastAnchorNode=this.lastAnchorOffset=this.lastFocusNode=this.lastFocusOffset=null;this.polling=new Delayed;this.gracePeriod=!1}function posToDOM(cm,pos){var view=findViewForLine(cm,pos.line);if(!view||view.hidden)return null;var line=getLine(cm.doc,pos.line),info=mapFromLineView(view,line,pos.line),order=getOrder(line),side="left";if(order){var partPos=getBidiPartAt(order,pos.ch);side=partPos%2?"right":"left"}var result=nodeAndOffsetInLineMap(info.map,pos.ch,side);result.offset="right"==result.collapse?result.end:result.start;return result}function badPos(pos,bad){bad&&(pos.bad=!0);return pos}function domToPos(cm,node,offset){var lineNode;if(node==cm.display.lineDiv){lineNode=cm.display.lineDiv.childNodes[offset];if(!lineNode)return badPos(cm.clipPos(Pos(cm.display.viewTo-1)),!0);node=null;offset=0}else for(lineNode=node;;lineNode=lineNode.parentNode){if(!lineNode||lineNode==cm.display.lineDiv)return null;if(lineNode.parentNode&&lineNode.parentNode==cm.display.lineDiv)break}for(var i=0;i<cm.display.view.length;i++){var lineView=cm.display.view[i];if(lineView.node==lineNode)return locateNodeInLineView(lineView,node,offset)}}function locateNodeInLineView(lineView,node,offset){function find(textNode,topNode,offset){for(var i=-1;i<(maps?maps.length:0);i++)for(var map=0>i?measure.map:maps[i],j=0;j<map.length;j+=3){var curNode=map[j+2];if(curNode==textNode||curNode==topNode){var line=lineNo(0>i?lineView.line:lineView.rest[i]),ch=map[j]+offset;(0>offset||curNode!=textNode)&&(ch=map[j+(offset?1:0)]);return Pos(line,ch)}}}var wrapper=lineView.text.firstChild,bad=!1;if(!node||!contains(wrapper,node))return badPos(Pos(lineNo(lineView.line),0),!0);if(node==wrapper){bad=!0;node=wrapper.childNodes[offset];offset=0;if(!node){var line=lineView.rest?lst(lineView.rest):lineView.line;return badPos(Pos(lineNo(line),line.text.length),bad)}}var textNode=3==node.nodeType?node:null,topNode=node;if(!textNode&&1==node.childNodes.length&&3==node.firstChild.nodeType){textNode=node.firstChild;offset&&(offset=textNode.nodeValue.length)}for(;topNode.parentNode!=wrapper;)topNode=topNode.parentNode;var measure=lineView.measure,maps=measure.maps,found=find(textNode,topNode,offset);if(found)return badPos(found,bad);for(var after=topNode.nextSibling,dist=textNode?textNode.nodeValue.length-offset:0;after;after=after.nextSibling){found=find(after,after.firstChild,0);if(found)return badPos(Pos(found.line,found.ch-dist),bad);dist+=after.textContent.length}for(var before=topNode.previousSibling,dist=offset;before;before=before.previousSibling){found=find(before,before.firstChild,-1);if(found)return badPos(Pos(found.line,found.ch+dist),bad);dist+=after.textContent.length}}function domTextBetween(cm,from,to,fromLine,toLine){function recognizeMarker(id){return function(marker){return marker.id==id}}function walk(node){if(1==node.nodeType){var cmText=node.getAttribute("cm-text");if(null!=cmText){""==cmText&&(cmText=node.textContent.replace(/\u200b/g,""));text+=cmText;return}var range,markerID=node.getAttribute("cm-marker");if(markerID){var found=cm.findMarks(Pos(fromLine,0),Pos(toLine+1,0),recognizeMarker(+markerID));found.length&&(range=found[0].find())&&(text+=getBetween(cm.doc,range.from,range.to).join(lineSep));return}if("false"==node.getAttribute("contenteditable"))return;for(var i=0;i<node.childNodes.length;i++)walk(node.childNodes[i]);/^(pre|div|p)$/i.test(node.nodeName)&&(closing=!0)}else if(3==node.nodeType){var val=node.nodeValue;if(!val)return;if(closing){text+=lineSep;closing=!1}text+=val}}for(var text="",closing=!1,lineSep=cm.doc.lineSeparator();;){walk(from);if(from==to)break;from=from.nextSibling}return text}function Selection(ranges,primIndex){this.ranges=ranges;this.primIndex=primIndex}function Range(anchor,head){this.anchor=anchor;this.head=head}function normalizeSelection(ranges,primIndex){var prim=ranges[primIndex];ranges.sort(function(a,b){return cmp(a.from(),b.from())});primIndex=indexOf(ranges,prim);for(var i=1;i<ranges.length;i++){var cur=ranges[i],prev=ranges[i-1];if(cmp(prev.to(),cur.from())>=0){var from=minPos(prev.from(),cur.from()),to=maxPos(prev.to(),cur.to()),inv=prev.empty()?cur.from()==cur.head:prev.from()==prev.head;primIndex>=i&&--primIndex;ranges.splice(--i,2,new Range(inv?to:from,inv?from:to))}}return new Selection(ranges,primIndex)}function simpleSelection(anchor,head){return new Selection([new Range(anchor,head||anchor)],0)}function clipLine(doc,n){return Math.max(doc.first,Math.min(n,doc.first+doc.size-1))}function clipPos(doc,pos){if(pos.line<doc.first)return Pos(doc.first,0);
2
- var last=doc.first+doc.size-1;return pos.line>last?Pos(last,getLine(doc,last).text.length):clipToLen(pos,getLine(doc,pos.line).text.length)}function clipToLen(pos,linelen){var ch=pos.ch;return null==ch||ch>linelen?Pos(pos.line,linelen):0>ch?Pos(pos.line,0):pos}function isLine(doc,l){return l>=doc.first&&l<doc.first+doc.size}function clipPosArray(doc,array){for(var out=[],i=0;i<array.length;i++)out[i]=clipPos(doc,array[i]);return out}function extendRange(doc,range,head,other){if(doc.cm&&doc.cm.display.shift||doc.extend){var anchor=range.anchor;if(other){var posBefore=cmp(head,anchor)<0;if(posBefore!=cmp(other,anchor)<0){anchor=head;head=other}else posBefore!=cmp(head,other)<0&&(head=other)}return new Range(anchor,head)}return new Range(other||head,head)}function extendSelection(doc,head,other,options){setSelection(doc,new Selection([extendRange(doc,doc.sel.primary(),head,other)],0),options)}function extendSelections(doc,heads,options){for(var out=[],i=0;i<doc.sel.ranges.length;i++)out[i]=extendRange(doc,doc.sel.ranges[i],heads[i],null);var newSel=normalizeSelection(out,doc.sel.primIndex);setSelection(doc,newSel,options)}function replaceOneSelection(doc,i,range,options){var ranges=doc.sel.ranges.slice(0);ranges[i]=range;setSelection(doc,normalizeSelection(ranges,doc.sel.primIndex),options)}function setSimpleSelection(doc,anchor,head,options){setSelection(doc,simpleSelection(anchor,head),options)}function filterSelectionChange(doc,sel,options){var obj={ranges:sel.ranges,update:function(ranges){this.ranges=[];for(var i=0;i<ranges.length;i++)this.ranges[i]=new Range(clipPos(doc,ranges[i].anchor),clipPos(doc,ranges[i].head))},origin:options&&options.origin};signal(doc,"beforeSelectionChange",doc,obj);doc.cm&&signal(doc.cm,"beforeSelectionChange",doc.cm,obj);return obj.ranges!=sel.ranges?normalizeSelection(obj.ranges,obj.ranges.length-1):sel}function setSelectionReplaceHistory(doc,sel,options){var done=doc.history.done,last=lst(done);if(last&&last.ranges){done[done.length-1]=sel;setSelectionNoUndo(doc,sel,options)}else setSelection(doc,sel,options)}function setSelection(doc,sel,options){setSelectionNoUndo(doc,sel,options);addSelectionToHistory(doc,doc.sel,doc.cm?doc.cm.curOp.id:NaN,options)}function setSelectionNoUndo(doc,sel,options){(hasHandler(doc,"beforeSelectionChange")||doc.cm&&hasHandler(doc.cm,"beforeSelectionChange"))&&(sel=filterSelectionChange(doc,sel,options));var bias=options&&options.bias||(cmp(sel.primary().head,doc.sel.primary().head)<0?-1:1);setSelectionInner(doc,skipAtomicInSelection(doc,sel,bias,!0));options&&options.scroll===!1||!doc.cm||ensureCursorVisible(doc.cm)}function setSelectionInner(doc,sel){if(!sel.equals(doc.sel)){doc.sel=sel;if(doc.cm){doc.cm.curOp.updateInput=doc.cm.curOp.selectionChanged=!0;signalCursorActivity(doc.cm)}signalLater(doc,"cursorActivity",doc)}}function reCheckSelection(doc){setSelectionInner(doc,skipAtomicInSelection(doc,doc.sel,null,!1),sel_dontScroll)}function skipAtomicInSelection(doc,sel,bias,mayClear){for(var out,i=0;i<sel.ranges.length;i++){var range=sel.ranges[i],old=sel.ranges.length==doc.sel.ranges.length&&doc.sel.ranges[i],newAnchor=skipAtomic(doc,range.anchor,old&&old.anchor,bias,mayClear),newHead=skipAtomic(doc,range.head,old&&old.head,bias,mayClear);if(out||newAnchor!=range.anchor||newHead!=range.head){out||(out=sel.ranges.slice(0,i));out[i]=new Range(newAnchor,newHead)}}return out?normalizeSelection(out,sel.primIndex):sel}function skipAtomicInner(doc,pos,oldPos,dir,mayClear){var line=getLine(doc,pos.line);if(line.markedSpans)for(var i=0;i<line.markedSpans.length;++i){var sp=line.markedSpans[i],m=sp.marker;if((null==sp.from||(m.inclusiveLeft?sp.from<=pos.ch:sp.from<pos.ch))&&(null==sp.to||(m.inclusiveRight?sp.to>=pos.ch:sp.to>pos.ch))){if(mayClear){signal(m,"beforeCursorEnter");if(m.explicitlyCleared){if(line.markedSpans){--i;continue}break}}if(!m.atomic)continue;if(oldPos){var diff,near=m.find(0>dir?1:-1);(0>dir?m.inclusiveRight:m.inclusiveLeft)&&(near=movePos(doc,near,-dir,near&&near.line==pos.line?line:null));if(near&&near.line==pos.line&&(diff=cmp(near,oldPos))&&(0>dir?0>diff:diff>0))return skipAtomicInner(doc,near,pos,dir,mayClear)}var far=m.find(0>dir?-1:1);(0>dir?m.inclusiveLeft:m.inclusiveRight)&&(far=movePos(doc,far,dir,far.line==pos.line?line:null));return far?skipAtomicInner(doc,far,pos,dir,mayClear):null}}return pos}function skipAtomic(doc,pos,oldPos,bias,mayClear){var dir=bias||1,found=skipAtomicInner(doc,pos,oldPos,dir,mayClear)||!mayClear&&skipAtomicInner(doc,pos,oldPos,dir,!0)||skipAtomicInner(doc,pos,oldPos,-dir,mayClear)||!mayClear&&skipAtomicInner(doc,pos,oldPos,-dir,!0);if(!found){doc.cantEdit=!0;return Pos(doc.first,0)}return found}function movePos(doc,pos,dir,line){return 0>dir&&0==pos.ch?pos.line>doc.first?clipPos(doc,Pos(pos.line-1)):null:dir>0&&pos.ch==(line||getLine(doc,pos.line)).text.length?pos.line<doc.first+doc.size-1?Pos(pos.line+1,0):null:new Pos(pos.line,pos.ch+dir)}function updateSelection(cm){cm.display.input.showSelection(cm.display.input.prepareSelection())}function prepareSelection(cm,primary){for(var doc=cm.doc,result={},curFragment=result.cursors=document.createDocumentFragment(),selFragment=result.selection=document.createDocumentFragment(),i=0;i<doc.sel.ranges.length;i++)if(primary!==!1||i!=doc.sel.primIndex){var range=doc.sel.ranges[i];if(!(range.from().line>=cm.display.viewTo||range.to().line<cm.display.viewFrom)){var collapsed=range.empty();(collapsed||cm.options.showCursorWhenSelecting)&&drawSelectionCursor(cm,range.head,curFragment);collapsed||drawSelectionRange(cm,range,selFragment)}}return result}function drawSelectionCursor(cm,head,output){var pos=cursorCoords(cm,head,"div",null,null,!cm.options.singleCursorHeightPerLine),cursor=output.appendChild(elt("div"," ","CodeMirror-cursor"));cursor.style.left=pos.left+"px";cursor.style.top=pos.top+"px";cursor.style.height=Math.max(0,pos.bottom-pos.top)*cm.options.cursorHeight+"px";if(pos.other){var otherCursor=output.appendChild(elt("div"," ","CodeMirror-cursor CodeMirror-secondarycursor"));otherCursor.style.display="";otherCursor.style.left=pos.other.left+"px";otherCursor.style.top=pos.other.top+"px";otherCursor.style.height=.85*(pos.other.bottom-pos.other.top)+"px"}}function drawSelectionRange(cm,range,output){function add(left,top,width,bottom){0>top&&(top=0);top=Math.round(top);bottom=Math.round(bottom);fragment.appendChild(elt("div",null,"CodeMirror-selected","position: absolute; left: "+left+"px; top: "+top+"px; width: "+(null==width?rightSide-left:width)+"px; height: "+(bottom-top)+"px"))}function drawForLine(line,fromArg,toArg){function coords(ch,bias){return charCoords(cm,Pos(line,ch),"div",lineObj,bias)}var start,end,lineObj=getLine(doc,line),lineLen=lineObj.text.length;iterateBidiSections(getOrder(lineObj),fromArg||0,null==toArg?lineLen:toArg,function(from,to,dir){var rightPos,left,right,leftPos=coords(from,"left");if(from==to){rightPos=leftPos;left=right=leftPos.left}else{rightPos=coords(to-1,"right");if("rtl"==dir){var tmp=leftPos;leftPos=rightPos;rightPos=tmp}left=leftPos.left;right=rightPos.right}null==fromArg&&0==from&&(left=leftSide);if(rightPos.top-leftPos.top>3){add(left,leftPos.top,null,leftPos.bottom);left=leftSide;leftPos.bottom<rightPos.top&&add(left,leftPos.bottom,null,rightPos.top)}null==toArg&&to==lineLen&&(right=rightSide);(!start||leftPos.top<start.top||leftPos.top==start.top&&leftPos.left<start.left)&&(start=leftPos);(!end||rightPos.bottom>end.bottom||rightPos.bottom==end.bottom&&rightPos.right>end.right)&&(end=rightPos);leftSide+1>left&&(left=leftSide);add(left,rightPos.top,right-left,rightPos.bottom)});return{start:start,end:end}}var display=cm.display,doc=cm.doc,fragment=document.createDocumentFragment(),padding=paddingH(cm.display),leftSide=padding.left,rightSide=Math.max(display.sizerWidth,displayWidth(cm)-display.sizer.offsetLeft)-padding.right,sFrom=range.from(),sTo=range.to();if(sFrom.line==sTo.line)drawForLine(sFrom.line,sFrom.ch,sTo.ch);else{var fromLine=getLine(doc,sFrom.line),toLine=getLine(doc,sTo.line),singleVLine=visualLine(fromLine)==visualLine(toLine),leftEnd=drawForLine(sFrom.line,sFrom.ch,singleVLine?fromLine.text.length+1:null).end,rightStart=drawForLine(sTo.line,singleVLine?0:null,sTo.ch).start;if(singleVLine)if(leftEnd.top<rightStart.top-2){add(leftEnd.right,leftEnd.top,null,leftEnd.bottom);add(leftSide,rightStart.top,rightStart.left,rightStart.bottom)}else add(leftEnd.right,leftEnd.top,rightStart.left-leftEnd.right,leftEnd.bottom);leftEnd.bottom<rightStart.top&&add(leftSide,leftEnd.bottom,null,rightStart.top)}output.appendChild(fragment)}function restartBlink(cm){if(cm.state.focused){var display=cm.display;clearInterval(display.blinker);var on=!0;display.cursorDiv.style.visibility="";cm.options.cursorBlinkRate>0?display.blinker=setInterval(function(){display.cursorDiv.style.visibility=(on=!on)?"":"hidden"},cm.options.cursorBlinkRate):cm.options.cursorBlinkRate<0&&(display.cursorDiv.style.visibility="hidden")}}function startWorker(cm,time){cm.doc.mode.startState&&cm.doc.frontier<cm.display.viewTo&&cm.state.highlight.set(time,bind(highlightWorker,cm))}function highlightWorker(cm){var doc=cm.doc;doc.frontier<doc.first&&(doc.frontier=doc.first);if(!(doc.frontier>=cm.display.viewTo)){var end=+new Date+cm.options.workTime,state=copyState(doc.mode,getStateBefore(cm,doc.frontier)),changedLines=[];doc.iter(doc.frontier,Math.min(doc.first+doc.size,cm.display.viewTo+500),function(line){if(doc.frontier>=cm.display.viewFrom){var oldStyles=line.styles,tooLong=line.text.length>cm.options.maxHighlightLength,highlighted=highlightLine(cm,line,tooLong?copyState(doc.mode,state):state,!0);line.styles=highlighted.styles;var oldCls=line.styleClasses,newCls=highlighted.classes;newCls?line.styleClasses=newCls:oldCls&&(line.styleClasses=null);for(var ischange=!oldStyles||oldStyles.length!=line.styles.length||oldCls!=newCls&&(!oldCls||!newCls||oldCls.bgClass!=newCls.bgClass||oldCls.textClass!=newCls.textClass),i=0;!ischange&&i<oldStyles.length;++i)ischange=oldStyles[i]!=line.styles[i];ischange&&changedLines.push(doc.frontier);line.stateAfter=tooLong?state:copyState(doc.mode,state)}else{line.text.length<=cm.options.maxHighlightLength&&processLine(cm,line.text,state);line.stateAfter=doc.frontier%5==0?copyState(doc.mode,state):null}++doc.frontier;if(+new Date>end){startWorker(cm,cm.options.workDelay);return!0}});changedLines.length&&runInOp(cm,function(){for(var i=0;i<changedLines.length;i++)regLineChange(cm,changedLines[i],"text")})}}function findStartLine(cm,n,precise){for(var minindent,minline,doc=cm.doc,lim=precise?-1:n-(cm.doc.mode.innerMode?1e3:100),search=n;search>lim;--search){if(search<=doc.first)return doc.first;var line=getLine(doc,search-1);if(line.stateAfter&&(!precise||search<=doc.frontier))return search;var indented=countColumn(line.text,null,cm.options.tabSize);if(null==minline||minindent>indented){minline=search-1;minindent=indented}}return minline}function getStateBefore(cm,n,precise){var doc=cm.doc,display=cm.display;if(!doc.mode.startState)return!0;var pos=findStartLine(cm,n,precise),state=pos>doc.first&&getLine(doc,pos-1).stateAfter;state=state?copyState(doc.mode,state):startState(doc.mode);doc.iter(pos,n,function(line){processLine(cm,line.text,state);var save=pos==n-1||pos%5==0||pos>=display.viewFrom&&pos<display.viewTo;line.stateAfter=save?copyState(doc.mode,state):null;++pos});precise&&(doc.frontier=pos);return state}function paddingTop(display){return display.lineSpace.offsetTop}function paddingVert(display){return display.mover.offsetHeight-display.lineSpace.offsetHeight}function paddingH(display){if(display.cachedPaddingH)return display.cachedPaddingH;var e=removeChildrenAndAdd(display.measure,elt("pre","x")),style=window.getComputedStyle?window.getComputedStyle(e):e.currentStyle,data={left:parseInt(style.paddingLeft),right:parseInt(style.paddingRight)};isNaN(data.left)||isNaN(data.right)||(display.cachedPaddingH=data);return data}function scrollGap(cm){return scrollerGap-cm.display.nativeBarWidth}function displayWidth(cm){return cm.display.scroller.clientWidth-scrollGap(cm)-cm.display.barWidth}function displayHeight(cm){return cm.display.scroller.clientHeight-scrollGap(cm)-cm.display.barHeight}function ensureLineHeights(cm,lineView,rect){var wrapping=cm.options.lineWrapping,curWidth=wrapping&&displayWidth(cm);if(!lineView.measure.heights||wrapping&&lineView.measure.width!=curWidth){var heights=lineView.measure.heights=[];if(wrapping){lineView.measure.width=curWidth;for(var rects=lineView.text.firstChild.getClientRects(),i=0;i<rects.length-1;i++){var cur=rects[i],next=rects[i+1];Math.abs(cur.bottom-next.bottom)>2&&heights.push((cur.bottom+next.top)/2-rect.top)}}heights.push(rect.bottom-rect.top)}}function mapFromLineView(lineView,line,lineN){if(lineView.line==line)return{map:lineView.measure.map,cache:lineView.measure.cache};for(var i=0;i<lineView.rest.length;i++)if(lineView.rest[i]==line)return{map:lineView.measure.maps[i],cache:lineView.measure.caches[i]};for(var i=0;i<lineView.rest.length;i++)if(lineNo(lineView.rest[i])>lineN)return{map:lineView.measure.maps[i],cache:lineView.measure.caches[i],before:!0}}function updateExternalMeasurement(cm,line){line=visualLine(line);var lineN=lineNo(line),view=cm.display.externalMeasured=new LineView(cm.doc,line,lineN);view.lineN=lineN;var built=view.built=buildLineContent(cm,view);view.text=built.pre;removeChildrenAndAdd(cm.display.lineMeasure,built.pre);return view}function measureChar(cm,line,ch,bias){return measureCharPrepared(cm,prepareMeasureForLine(cm,line),ch,bias)}function findViewForLine(cm,lineN){if(lineN>=cm.display.viewFrom&&lineN<cm.display.viewTo)return cm.display.view[findViewIndex(cm,lineN)];var ext=cm.display.externalMeasured;return ext&&lineN>=ext.lineN&&lineN<ext.lineN+ext.size?ext:void 0}function prepareMeasureForLine(cm,line){var lineN=lineNo(line),view=findViewForLine(cm,lineN);if(view&&!view.text)view=null;else if(view&&view.changes){updateLineForChanges(cm,view,lineN,getDimensions(cm));cm.curOp.forceUpdate=!0}view||(view=updateExternalMeasurement(cm,line));var info=mapFromLineView(view,line,lineN);return{line:line,view:view,rect:null,map:info.map,cache:info.cache,before:info.before,hasHeights:!1}}function measureCharPrepared(cm,prepared,ch,bias,varHeight){prepared.before&&(ch=-1);var found,key=ch+(bias||"");if(prepared.cache.hasOwnProperty(key))found=prepared.cache[key];else{prepared.rect||(prepared.rect=prepared.view.text.getBoundingClientRect());if(!prepared.hasHeights){ensureLineHeights(cm,prepared.view,prepared.rect);prepared.hasHeights=!0}found=measureCharInner(cm,prepared,ch,bias);found.bogus||(prepared.cache[key]=found)}return{left:found.left,right:found.right,top:varHeight?found.rtop:found.top,bottom:varHeight?found.rbottom:found.bottom}}function nodeAndOffsetInLineMap(map,ch,bias){for(var node,start,end,collapse,i=0;i<map.length;i+=3){var mStart=map[i],mEnd=map[i+1];if(mStart>ch){start=0;end=1;collapse="left"}else if(mEnd>ch){start=ch-mStart;end=start+1}else if(i==map.length-3||ch==mEnd&&map[i+3]>ch){end=mEnd-mStart;start=end-1;ch>=mEnd&&(collapse="right")}if(null!=start){node=map[i+2];mStart==mEnd&&bias==(node.insertLeft?"left":"right")&&(collapse=bias);if("left"==bias&&0==start)for(;i&&map[i-2]==map[i-3]&&map[i-1].insertLeft;){node=map[(i-=3)+2];collapse="left"}if("right"==bias&&start==mEnd-mStart)for(;i<map.length-3&&map[i+3]==map[i+4]&&!map[i+5].insertLeft;){node=map[(i+=3)+2];collapse="right"}break}}return{node:node,start:start,end:end,collapse:collapse,coverStart:mStart,coverEnd:mEnd}}function measureCharInner(cm,prepared,ch,bias){var rect,place=nodeAndOffsetInLineMap(prepared.map,ch,bias),node=place.node,start=place.start,end=place.end,collapse=place.collapse;if(3==node.nodeType){for(var i=0;4>i;i++){for(;start&&isExtendingChar(prepared.line.text.charAt(place.coverStart+start));)--start;for(;place.coverStart+end<place.coverEnd&&isExtendingChar(prepared.line.text.charAt(place.coverStart+end));)++end;if(ie&&9>ie_version&&0==start&&end==place.coverEnd-place.coverStart)rect=node.parentNode.getBoundingClientRect();else if(ie&&cm.options.lineWrapping){var rects=range(node,start,end).getClientRects();rect=rects.length?rects["right"==bias?rects.length-1:0]:nullRect}else rect=range(node,start,end).getBoundingClientRect()||nullRect;if(rect.left||rect.right||0==start)break;end=start;start-=1;collapse="right"}ie&&11>ie_version&&(rect=maybeUpdateRectForZooming(cm.display.measure,rect))}else{start>0&&(collapse=bias="right");var rects;rect=cm.options.lineWrapping&&(rects=node.getClientRects()).length>1?rects["right"==bias?rects.length-1:0]:node.getBoundingClientRect()}if(ie&&9>ie_version&&!start&&(!rect||!rect.left&&!rect.right)){var rSpan=node.parentNode.getClientRects()[0];rect=rSpan?{left:rSpan.left,right:rSpan.left+charWidth(cm.display),top:rSpan.top,bottom:rSpan.bottom}:nullRect}for(var rtop=rect.top-prepared.rect.top,rbot=rect.bottom-prepared.rect.top,mid=(rtop+rbot)/2,heights=prepared.view.measure.heights,i=0;i<heights.length-1&&!(mid<heights[i]);i++);var top=i?heights[i-1]:0,bot=heights[i],result={left:("right"==collapse?rect.right:rect.left)-prepared.rect.left,right:("left"==collapse?rect.left:rect.right)-prepared.rect.left,top:top,bottom:bot};rect.left||rect.right||(result.bogus=!0);if(!cm.options.singleCursorHeightPerLine){result.rtop=rtop;result.rbottom=rbot}return result}function maybeUpdateRectForZooming(measure,rect){if(!window.screen||null==screen.logicalXDPI||screen.logicalXDPI==screen.deviceXDPI||!hasBadZoomedRects(measure))return rect;var scaleX=screen.logicalXDPI/screen.deviceXDPI,scaleY=screen.logicalYDPI/screen.deviceYDPI;return{left:rect.left*scaleX,right:rect.right*scaleX,top:rect.top*scaleY,bottom:rect.bottom*scaleY}}function clearLineMeasurementCacheFor(lineView){if(lineView.measure){lineView.measure.cache={};lineView.measure.heights=null;if(lineView.rest)for(var i=0;i<lineView.rest.length;i++)lineView.measure.caches[i]={}}}function clearLineMeasurementCache(cm){cm.display.externalMeasure=null;removeChildren(cm.display.lineMeasure);for(var i=0;i<cm.display.view.length;i++)clearLineMeasurementCacheFor(cm.display.view[i])}function clearCaches(cm){clearLineMeasurementCache(cm);cm.display.cachedCharWidth=cm.display.cachedTextHeight=cm.display.cachedPaddingH=null;cm.options.lineWrapping||(cm.display.maxLineChanged=!0);cm.display.lineNumChars=null}function pageScrollX(){return window.pageXOffset||(document.documentElement||document.body).scrollLeft}function pageScrollY(){return window.pageYOffset||(document.documentElement||document.body).scrollTop}function intoCoordSystem(cm,lineObj,rect,context){if(lineObj.widgets)for(var i=0;i<lineObj.widgets.length;++i)if(lineObj.widgets[i].above){var size=widgetHeight(lineObj.widgets[i]);rect.top+=size;rect.bottom+=size}if("line"==context)return rect;context||(context="local");var yOff=heightAtLine(lineObj);"local"==context?yOff+=paddingTop(cm.display):yOff-=cm.display.viewOffset;if("page"==context||"window"==context){var lOff=cm.display.lineSpace.getBoundingClientRect();yOff+=lOff.top+("window"==context?0:pageScrollY());var xOff=lOff.left+("window"==context?0:pageScrollX());rect.left+=xOff;rect.right+=xOff}rect.top+=yOff;rect.bottom+=yOff;return rect}function fromCoordSystem(cm,coords,context){if("div"==context)return coords;var left=coords.left,top=coords.top;if("page"==context){left-=pageScrollX();top-=pageScrollY()}else if("local"==context||!context){var localBox=cm.display.sizer.getBoundingClientRect();left+=localBox.left;top+=localBox.top}var lineSpaceBox=cm.display.lineSpace.getBoundingClientRect();return{left:left-lineSpaceBox.left,top:top-lineSpaceBox.top}}function charCoords(cm,pos,context,lineObj,bias){lineObj||(lineObj=getLine(cm.doc,pos.line));return intoCoordSystem(cm,lineObj,measureChar(cm,lineObj,pos.ch,bias),context)}function cursorCoords(cm,pos,context,lineObj,preparedMeasure,varHeight){function get(ch,right){var m=measureCharPrepared(cm,preparedMeasure,ch,right?"right":"left",varHeight);right?m.left=m.right:m.right=m.left;return intoCoordSystem(cm,lineObj,m,context)}function getBidi(ch,partPos){var part=order[partPos],right=part.level%2;if(ch==bidiLeft(part)&&partPos&&part.level<order[partPos-1].level){part=order[--partPos];ch=bidiRight(part)-(part.level%2?0:1);right=!0}else if(ch==bidiRight(part)&&partPos<order.length-1&&part.level<order[partPos+1].level){part=order[++partPos];ch=bidiLeft(part)-part.level%2;right=!1}return right&&ch==part.to&&ch>part.from?get(ch-1):get(ch,right)}lineObj=lineObj||getLine(cm.doc,pos.line);preparedMeasure||(preparedMeasure=prepareMeasureForLine(cm,lineObj));var order=getOrder(lineObj),ch=pos.ch;if(!order)return get(ch);var partPos=getBidiPartAt(order,ch),val=getBidi(ch,partPos);null!=bidiOther&&(val.other=getBidi(ch,bidiOther));return val}function estimateCoords(cm,pos){var left=0,pos=clipPos(cm.doc,pos);cm.options.lineWrapping||(left=charWidth(cm.display)*pos.ch);var lineObj=getLine(cm.doc,pos.line),top=heightAtLine(lineObj)+paddingTop(cm.display);return{left:left,right:left,top:top,bottom:top+lineObj.height}}function PosWithInfo(line,ch,outside,xRel){var pos=Pos(line,ch);pos.xRel=xRel;outside&&(pos.outside=!0);return pos}function coordsChar(cm,x,y){var doc=cm.doc;y+=cm.display.viewOffset;if(0>y)return PosWithInfo(doc.first,0,!0,-1);var lineN=lineAtHeight(doc,y),last=doc.first+doc.size-1;if(lineN>last)return PosWithInfo(doc.first+doc.size-1,getLine(doc,last).text.length,!0,1);0>x&&(x=0);for(var lineObj=getLine(doc,lineN);;){var found=coordsCharInner(cm,lineObj,lineN,x,y),merged=collapsedSpanAtEnd(lineObj),mergedPos=merged&&merged.find(0,!0);if(!merged||!(found.ch>mergedPos.from.ch||found.ch==mergedPos.from.ch&&found.xRel>0))return found;lineN=lineNo(lineObj=mergedPos.to.line)}}function coordsCharInner(cm,lineObj,lineNo,x,y){function getX(ch){var sp=cursorCoords(cm,Pos(lineNo,ch),"line",lineObj,preparedMeasure);wrongLine=!0;if(innerOff>sp.bottom)return sp.left-adjust;if(innerOff<sp.top)return sp.left+adjust;wrongLine=!1;return sp.left}var innerOff=y-heightAtLine(lineObj),wrongLine=!1,adjust=2*cm.display.wrapper.clientWidth,preparedMeasure=prepareMeasureForLine(cm,lineObj),bidi=getOrder(lineObj),dist=lineObj.text.length,from=lineLeft(lineObj),to=lineRight(lineObj),fromX=getX(from),fromOutside=wrongLine,toX=getX(to),toOutside=wrongLine;if(x>toX)return PosWithInfo(lineNo,to,toOutside,1);for(;;){if(bidi?to==from||to==moveVisually(lineObj,from,1):1>=to-from){for(var ch=fromX>x||toX-x>=x-fromX?from:to,xDiff=x-(ch==from?fromX:toX);isExtendingChar(lineObj.text.charAt(ch));)++ch;var pos=PosWithInfo(lineNo,ch,ch==from?fromOutside:toOutside,-1>xDiff?-1:xDiff>1?1:0);return pos}var step=Math.ceil(dist/2),middle=from+step;if(bidi){middle=from;for(var i=0;step>i;++i)middle=moveVisually(lineObj,middle,1)}var middleX=getX(middle);if(middleX>x){to=middle;toX=middleX;(toOutside=wrongLine)&&(toX+=1e3);dist=step}else{from=middle;fromX=middleX;fromOutside=wrongLine;dist-=step}}}function textHeight(display){if(null!=display.cachedTextHeight)return display.cachedTextHeight;if(null==measureText){measureText=elt("pre");for(var i=0;49>i;++i){measureText.appendChild(document.createTextNode("x"));measureText.appendChild(elt("br"))}measureText.appendChild(document.createTextNode("x"))}removeChildrenAndAdd(display.measure,measureText);var height=measureText.offsetHeight/50;height>3&&(display.cachedTextHeight=height);removeChildren(display.measure);return height||1}function charWidth(display){if(null!=display.cachedCharWidth)return display.cachedCharWidth;var anchor=elt("span","xxxxxxxxxx"),pre=elt("pre",[anchor]);removeChildrenAndAdd(display.measure,pre);var rect=anchor.getBoundingClientRect(),width=(rect.right-rect.left)/10;width>2&&(display.cachedCharWidth=width);return width||10}function startOperation(cm){cm.curOp={cm:cm,viewChanged:!1,startHeight:cm.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:++nextOpId};operationGroup?operationGroup.ops.push(cm.curOp):cm.curOp.ownsGroup=operationGroup={ops:[cm.curOp],delayedCallbacks:[]}}function fireCallbacksForOps(group){var callbacks=group.delayedCallbacks,i=0;do{for(;i<callbacks.length;i++)callbacks[i].call(null);for(var j=0;j<group.ops.length;j++){var op=group.ops[j];if(op.cursorActivityHandlers)for(;op.cursorActivityCalled<op.cursorActivityHandlers.length;)op.cursorActivityHandlers[op.cursorActivityCalled++].call(null,op.cm)}}while(i<callbacks.length)}function endOperation(cm){var op=cm.curOp,group=op.ownsGroup;if(group)try{fireCallbacksForOps(group)}finally{operationGroup=null;for(var i=0;i<group.ops.length;i++)group.ops[i].cm.curOp=null;endOperations(group)}}function endOperations(group){for(var ops=group.ops,i=0;i<ops.length;i++)endOperation_R1(ops[i]);for(var i=0;i<ops.length;i++)endOperation_W1(ops[i]);for(var i=0;i<ops.length;i++)endOperation_R2(ops[i]);for(var i=0;i<ops.length;i++)endOperation_W2(ops[i]);for(var i=0;i<ops.length;i++)endOperation_finish(ops[i])}function endOperation_R1(op){var cm=op.cm,display=cm.display;maybeClipScrollbars(cm);op.updateMaxLine&&findMaxLine(cm);op.mustUpdate=op.viewChanged||op.forceUpdate||null!=op.scrollTop||op.scrollToPos&&(op.scrollToPos.from.line<display.viewFrom||op.scrollToPos.to.line>=display.viewTo)||display.maxLineChanged&&cm.options.lineWrapping;op.update=op.mustUpdate&&new DisplayUpdate(cm,op.mustUpdate&&{top:op.scrollTop,ensure:op.scrollToPos},op.forceUpdate)}function endOperation_W1(op){op.updatedDisplay=op.mustUpdate&&updateDisplayIfNeeded(op.cm,op.update)}function endOperation_R2(op){var cm=op.cm,display=cm.display;op.updatedDisplay&&updateHeightsInViewport(cm);op.barMeasure=measureForScrollbars(cm);if(display.maxLineChanged&&!cm.options.lineWrapping){op.adjustWidthTo=measureChar(cm,display.maxLine,display.maxLine.text.length).left+3;cm.display.sizerWidth=op.adjustWidthTo;op.barMeasure.scrollWidth=Math.max(display.scroller.clientWidth,display.sizer.offsetLeft+op.adjustWidthTo+scrollGap(cm)+cm.display.barWidth);op.maxScrollLeft=Math.max(0,display.sizer.offsetLeft+op.adjustWidthTo-displayWidth(cm))}(op.updatedDisplay||op.selectionChanged)&&(op.preparedSelection=display.input.prepareSelection())}function endOperation_W2(op){var cm=op.cm;if(null!=op.adjustWidthTo){cm.display.sizer.style.minWidth=op.adjustWidthTo+"px";op.maxScrollLeft<cm.doc.scrollLeft&&setScrollLeft(cm,Math.min(cm.display.scroller.scrollLeft,op.maxScrollLeft),!0);cm.display.maxLineChanged=!1}op.preparedSelection&&cm.display.input.showSelection(op.preparedSelection);(op.updatedDisplay||op.startHeight!=cm.doc.height)&&updateScrollbars(cm,op.barMeasure);op.updatedDisplay&&setDocumentHeight(cm,op.barMeasure);op.selectionChanged&&restartBlink(cm);cm.state.focused&&op.updateInput&&cm.display.input.reset(op.typing);!op.focus||op.focus!=activeElt()||document.hasFocus&&!document.hasFocus()||ensureFocus(op.cm)}function endOperation_finish(op){var cm=op.cm,display=cm.display,doc=cm.doc;op.updatedDisplay&&postUpdateDisplay(cm,op.update);null==display.wheelStartX||null==op.scrollTop&&null==op.scrollLeft&&!op.scrollToPos||(display.wheelStartX=display.wheelStartY=null);if(null!=op.scrollTop&&(display.scroller.scrollTop!=op.scrollTop||op.forceScroll)){doc.scrollTop=Math.max(0,Math.min(display.scroller.scrollHeight-display.scroller.clientHeight,op.scrollTop));display.scrollbars.setScrollTop(doc.scrollTop);display.scroller.scrollTop=doc.scrollTop}if(null!=op.scrollLeft&&(display.scroller.scrollLeft!=op.scrollLeft||op.forceScroll)){doc.scrollLeft=Math.max(0,Math.min(display.scroller.scrollWidth-display.scroller.clientWidth,op.scrollLeft));display.scrollbars.setScrollLeft(doc.scrollLeft);display.scroller.scrollLeft=doc.scrollLeft;alignHorizontally(cm)}if(op.scrollToPos){var coords=scrollPosIntoView(cm,clipPos(doc,op.scrollToPos.from),clipPos(doc,op.scrollToPos.to),op.scrollToPos.margin);op.scrollToPos.isCursor&&cm.state.focused&&maybeScrollWindow(cm,coords)}var hidden=op.maybeHiddenMarkers,unhidden=op.maybeUnhiddenMarkers;if(hidden)for(var i=0;i<hidden.length;++i)hidden[i].lines.length||signal(hidden[i],"hide");if(unhidden)for(var i=0;i<unhidden.length;++i)unhidden[i].lines.length&&signal(unhidden[i],"unhide");display.wrapper.offsetHeight&&(doc.scrollTop=cm.display.scroller.scrollTop);op.changeObjs&&signal(cm,"changes",cm,op.changeObjs);op.update&&op.update.finish()}function runInOp(cm,f){if(cm.curOp)return f();startOperation(cm);try{return f()}finally{endOperation(cm)}}function operation(cm,f){return function(){if(cm.curOp)return f.apply(cm,arguments);startOperation(cm);try{return f.apply(cm,arguments)}finally{endOperation(cm)}}}function methodOp(f){return function(){if(this.curOp)return f.apply(this,arguments);startOperation(this);try{return f.apply(this,arguments)}finally{endOperation(this)}}}function docMethodOp(f){return function(){var cm=this.cm;if(!cm||cm.curOp)return f.apply(this,arguments);startOperation(cm);try{return f.apply(this,arguments)}finally{endOperation(cm)}}}function LineView(doc,line,lineN){this.line=line;this.rest=visualLineContinued(line);this.size=this.rest?lineNo(lst(this.rest))-lineN+1:1;this.node=this.text=null;this.hidden=lineIsHidden(doc,line)}function buildViewArray(cm,from,to){for(var nextPos,array=[],pos=from;to>pos;pos=nextPos){var view=new LineView(cm.doc,getLine(cm.doc,pos),pos);nextPos=pos+view.size;array.push(view)}return array}function regChange(cm,from,to,lendiff){null==from&&(from=cm.doc.first);null==to&&(to=cm.doc.first+cm.doc.size);lendiff||(lendiff=0);var display=cm.display;lendiff&&to<display.viewTo&&(null==display.updateLineNumbers||display.updateLineNumbers>from)&&(display.updateLineNumbers=from);cm.curOp.viewChanged=!0;if(from>=display.viewTo)sawCollapsedSpans&&visualLineNo(cm.doc,from)<display.viewTo&&resetView(cm);else if(to<=display.viewFrom)if(sawCollapsedSpans&&visualLineEndNo(cm.doc,to+lendiff)>display.viewFrom)resetView(cm);else{display.viewFrom+=lendiff;display.viewTo+=lendiff}else if(from<=display.viewFrom&&to>=display.viewTo)resetView(cm);else if(from<=display.viewFrom){var cut=viewCuttingPoint(cm,to,to+lendiff,1);if(cut){display.view=display.view.slice(cut.index);display.viewFrom=cut.lineN;display.viewTo+=lendiff}else resetView(cm)}else if(to>=display.viewTo){var cut=viewCuttingPoint(cm,from,from,-1);if(cut){display.view=display.view.slice(0,cut.index);display.viewTo=cut.lineN}else resetView(cm)}else{var cutTop=viewCuttingPoint(cm,from,from,-1),cutBot=viewCuttingPoint(cm,to,to+lendiff,1);if(cutTop&&cutBot){display.view=display.view.slice(0,cutTop.index).concat(buildViewArray(cm,cutTop.lineN,cutBot.lineN)).concat(display.view.slice(cutBot.index));display.viewTo+=lendiff}else resetView(cm)}var ext=display.externalMeasured;ext&&(to<ext.lineN?ext.lineN+=lendiff:from<ext.lineN+ext.size&&(display.externalMeasured=null))}function regLineChange(cm,line,type){cm.curOp.viewChanged=!0;var display=cm.display,ext=cm.display.externalMeasured;ext&&line>=ext.lineN&&line<ext.lineN+ext.size&&(display.externalMeasured=null);if(!(line<display.viewFrom||line>=display.viewTo)){var lineView=display.view[findViewIndex(cm,line)];if(null!=lineView.node){var arr=lineView.changes||(lineView.changes=[]);-1==indexOf(arr,type)&&arr.push(type)}}}function resetView(cm){cm.display.viewFrom=cm.display.viewTo=cm.doc.first;cm.display.view=[];cm.display.viewOffset=0}function findViewIndex(cm,n){if(n>=cm.display.viewTo)return null;n-=cm.display.viewFrom;if(0>n)return null;for(var view=cm.display.view,i=0;i<view.length;i++){n-=view[i].size;if(0>n)return i}}function viewCuttingPoint(cm,oldN,newN,dir){var diff,index=findViewIndex(cm,oldN),view=cm.display.view;if(!sawCollapsedSpans||newN==cm.doc.first+cm.doc.size)return{index:index,lineN:newN};for(var i=0,n=cm.display.viewFrom;index>i;i++)n+=view[i].size;if(n!=oldN){if(dir>0){if(index==view.length-1)return null;diff=n+view[index].size-oldN;index++}else diff=n-oldN;oldN+=diff;
3
- newN+=diff}for(;visualLineNo(cm.doc,newN)!=newN;){if(index==(0>dir?0:view.length-1))return null;newN+=dir*view[index-(0>dir?1:0)].size;index+=dir}return{index:index,lineN:newN}}function adjustView(cm,from,to){var display=cm.display,view=display.view;if(0==view.length||from>=display.viewTo||to<=display.viewFrom){display.view=buildViewArray(cm,from,to);display.viewFrom=from}else{display.viewFrom>from?display.view=buildViewArray(cm,from,display.viewFrom).concat(display.view):display.viewFrom<from&&(display.view=display.view.slice(findViewIndex(cm,from)));display.viewFrom=from;display.viewTo<to?display.view=display.view.concat(buildViewArray(cm,display.viewTo,to)):display.viewTo>to&&(display.view=display.view.slice(0,findViewIndex(cm,to)))}display.viewTo=to}function countDirtyView(cm){for(var view=cm.display.view,dirty=0,i=0;i<view.length;i++){var lineView=view[i];lineView.hidden||lineView.node&&!lineView.changes||++dirty}return dirty}function registerEventHandlers(cm){function finishTouch(){if(d.activeTouch){touchFinished=setTimeout(function(){d.activeTouch=null},1e3);prevTouch=d.activeTouch;prevTouch.end=+new Date}}function isMouseLikeTouchEvent(e){if(1!=e.touches.length)return!1;var touch=e.touches[0];return touch.radiusX<=1&&touch.radiusY<=1}function farAway(touch,other){if(null==other.left)return!0;var dx=other.left-touch.left,dy=other.top-touch.top;return dx*dx+dy*dy>400}var d=cm.display;on(d.scroller,"mousedown",operation(cm,onMouseDown));ie&&11>ie_version?on(d.scroller,"dblclick",operation(cm,function(e){if(!signalDOMEvent(cm,e)){var pos=posFromMouse(cm,e);if(pos&&!clickInGutter(cm,e)&&!eventInWidget(cm.display,e)){e_preventDefault(e);var word=cm.findWordAt(pos);extendSelection(cm.doc,word.anchor,word.head)}}})):on(d.scroller,"dblclick",function(e){signalDOMEvent(cm,e)||e_preventDefault(e)});captureRightClick||on(d.scroller,"contextmenu",function(e){onContextMenu(cm,e)});var touchFinished,prevTouch={end:0};on(d.scroller,"touchstart",function(e){if(!signalDOMEvent(cm,e)&&!isMouseLikeTouchEvent(e)){clearTimeout(touchFinished);var now=+new Date;d.activeTouch={start:now,moved:!1,prev:now-prevTouch.end<=300?prevTouch:null};if(1==e.touches.length){d.activeTouch.left=e.touches[0].pageX;d.activeTouch.top=e.touches[0].pageY}}});on(d.scroller,"touchmove",function(){d.activeTouch&&(d.activeTouch.moved=!0)});on(d.scroller,"touchend",function(e){var touch=d.activeTouch;if(touch&&!eventInWidget(d,e)&&null!=touch.left&&!touch.moved&&new Date-touch.start<300){var range,pos=cm.coordsChar(d.activeTouch,"page");range=!touch.prev||farAway(touch,touch.prev)?new Range(pos,pos):!touch.prev.prev||farAway(touch,touch.prev.prev)?cm.findWordAt(pos):new Range(Pos(pos.line,0),clipPos(cm.doc,Pos(pos.line+1,0)));cm.setSelection(range.anchor,range.head);cm.focus();e_preventDefault(e)}finishTouch()});on(d.scroller,"touchcancel",finishTouch);on(d.scroller,"scroll",function(){if(d.scroller.clientHeight){setScrollTop(cm,d.scroller.scrollTop);setScrollLeft(cm,d.scroller.scrollLeft,!0);signal(cm,"scroll",cm)}});on(d.scroller,"mousewheel",function(e){onScrollWheel(cm,e)});on(d.scroller,"DOMMouseScroll",function(e){onScrollWheel(cm,e)});on(d.wrapper,"scroll",function(){d.wrapper.scrollTop=d.wrapper.scrollLeft=0});d.dragFunctions={enter:function(e){signalDOMEvent(cm,e)||e_stop(e)},over:function(e){if(!signalDOMEvent(cm,e)){onDragOver(cm,e);e_stop(e)}},start:function(e){onDragStart(cm,e)},drop:operation(cm,onDrop),leave:function(e){signalDOMEvent(cm,e)||clearDragCursor(cm)}};var inp=d.input.getField();on(inp,"keyup",function(e){onKeyUp.call(cm,e)});on(inp,"keydown",operation(cm,onKeyDown));on(inp,"keypress",operation(cm,onKeyPress));on(inp,"focus",bind(onFocus,cm));on(inp,"blur",bind(onBlur,cm))}function dragDropChanged(cm,value,old){var wasOn=old&&old!=CodeMirror.Init;if(!value!=!wasOn){var funcs=cm.display.dragFunctions,toggle=value?on:off;toggle(cm.display.scroller,"dragstart",funcs.start);toggle(cm.display.scroller,"dragenter",funcs.enter);toggle(cm.display.scroller,"dragover",funcs.over);toggle(cm.display.scroller,"dragleave",funcs.leave);toggle(cm.display.scroller,"drop",funcs.drop)}}function onResize(cm){var d=cm.display;if(d.lastWrapHeight!=d.wrapper.clientHeight||d.lastWrapWidth!=d.wrapper.clientWidth){d.cachedCharWidth=d.cachedTextHeight=d.cachedPaddingH=null;d.scrollbarsClipped=!1;cm.setSize()}}function eventInWidget(display,e){for(var n=e_target(e);n!=display.wrapper;n=n.parentNode)if(!n||1==n.nodeType&&"true"==n.getAttribute("cm-ignore-events")||n.parentNode==display.sizer&&n!=display.mover)return!0}function posFromMouse(cm,e,liberal,forRect){var display=cm.display;if(!liberal&&"true"==e_target(e).getAttribute("cm-not-content"))return null;var x,y,space=display.lineSpace.getBoundingClientRect();try{x=e.clientX-space.left;y=e.clientY-space.top}catch(e){return null}var line,coords=coordsChar(cm,x,y);if(forRect&&1==coords.xRel&&(line=getLine(cm.doc,coords.line).text).length==coords.ch){var colDiff=countColumn(line,line.length,cm.options.tabSize)-line.length;coords=Pos(coords.line,Math.max(0,Math.round((x-paddingH(cm.display).left)/charWidth(cm.display))-colDiff))}return coords}function onMouseDown(e){var cm=this,display=cm.display;if(!(signalDOMEvent(cm,e)||display.activeTouch&&display.input.supportsTouch())){display.shift=e.shiftKey;if(eventInWidget(display,e)){if(!webkit){display.scroller.draggable=!1;setTimeout(function(){display.scroller.draggable=!0},100)}}else if(!clickInGutter(cm,e)){var start=posFromMouse(cm,e);window.focus();switch(e_button(e)){case 1:cm.state.selectingText?cm.state.selectingText(e):start?leftButtonDown(cm,e,start):e_target(e)==display.scroller&&e_preventDefault(e);break;case 2:webkit&&(cm.state.lastMiddleDown=+new Date);start&&extendSelection(cm.doc,start);setTimeout(function(){display.input.focus()},20);e_preventDefault(e);break;case 3:captureRightClick?onContextMenu(cm,e):delayBlurEvent(cm)}}}}function leftButtonDown(cm,e,start){ie?setTimeout(bind(ensureFocus,cm),0):cm.curOp.focus=activeElt();var type,now=+new Date;if(lastDoubleClick&&lastDoubleClick.time>now-400&&0==cmp(lastDoubleClick.pos,start))type="triple";else if(lastClick&&lastClick.time>now-400&&0==cmp(lastClick.pos,start)){type="double";lastDoubleClick={time:now,pos:start}}else{type="single";lastClick={time:now,pos:start}}var contained,sel=cm.doc.sel,modifier=mac?e.metaKey:e.ctrlKey;cm.options.dragDrop&&dragAndDrop&&!cm.isReadOnly()&&"single"==type&&(contained=sel.contains(start))>-1&&(cmp((contained=sel.ranges[contained]).from(),start)<0||start.xRel>0)&&(cmp(contained.to(),start)>0||start.xRel<0)?leftButtonStartDrag(cm,e,start,modifier):leftButtonSelect(cm,e,start,type,modifier)}function leftButtonStartDrag(cm,e,start,modifier){var display=cm.display,startTime=+new Date,dragEnd=operation(cm,function(e2){webkit&&(display.scroller.draggable=!1);cm.state.draggingText=!1;off(document,"mouseup",dragEnd);off(display.scroller,"drop",dragEnd);if(Math.abs(e.clientX-e2.clientX)+Math.abs(e.clientY-e2.clientY)<10){e_preventDefault(e2);!modifier&&+new Date-200<startTime&&extendSelection(cm.doc,start);webkit||ie&&9==ie_version?setTimeout(function(){document.body.focus();display.input.focus()},20):display.input.focus()}});webkit&&(display.scroller.draggable=!0);cm.state.draggingText=dragEnd;display.scroller.dragDrop&&display.scroller.dragDrop();on(document,"mouseup",dragEnd);on(display.scroller,"drop",dragEnd)}function leftButtonSelect(cm,e,start,type,addNew){function extendTo(pos){if(0!=cmp(lastPos,pos)){lastPos=pos;if("rect"==type){for(var ranges=[],tabSize=cm.options.tabSize,startCol=countColumn(getLine(doc,start.line).text,start.ch,tabSize),posCol=countColumn(getLine(doc,pos.line).text,pos.ch,tabSize),left=Math.min(startCol,posCol),right=Math.max(startCol,posCol),line=Math.min(start.line,pos.line),end=Math.min(cm.lastLine(),Math.max(start.line,pos.line));end>=line;line++){var text=getLine(doc,line).text,leftPos=findColumn(text,left,tabSize);left==right?ranges.push(new Range(Pos(line,leftPos),Pos(line,leftPos))):text.length>leftPos&&ranges.push(new Range(Pos(line,leftPos),Pos(line,findColumn(text,right,tabSize))))}ranges.length||ranges.push(new Range(start,start));setSelection(doc,normalizeSelection(startSel.ranges.slice(0,ourIndex).concat(ranges),ourIndex),{origin:"*mouse",scroll:!1});cm.scrollIntoView(pos)}else{var oldRange=ourRange,anchor=oldRange.anchor,head=pos;if("single"!=type){if("double"==type)var range=cm.findWordAt(pos);else var range=new Range(Pos(pos.line,0),clipPos(doc,Pos(pos.line+1,0)));if(cmp(range.anchor,anchor)>0){head=range.head;anchor=minPos(oldRange.from(),range.anchor)}else{head=range.anchor;anchor=maxPos(oldRange.to(),range.head)}}var ranges=startSel.ranges.slice(0);ranges[ourIndex]=new Range(clipPos(doc,anchor),head);setSelection(doc,normalizeSelection(ranges,ourIndex),sel_mouse)}}}function extend(e){var curCount=++counter,cur=posFromMouse(cm,e,!0,"rect"==type);if(cur)if(0!=cmp(cur,lastPos)){cm.curOp.focus=activeElt();extendTo(cur);var visible=visibleLines(display,doc);(cur.line>=visible.to||cur.line<visible.from)&&setTimeout(operation(cm,function(){counter==curCount&&extend(e)}),150)}else{var outside=e.clientY<editorSize.top?-20:e.clientY>editorSize.bottom?20:0;outside&&setTimeout(operation(cm,function(){if(counter==curCount){display.scroller.scrollTop+=outside;extend(e)}}),50)}}function done(e){cm.state.selectingText=!1;counter=1/0;e_preventDefault(e);display.input.focus();off(document,"mousemove",move);off(document,"mouseup",up);doc.history.lastSelOrigin=null}var display=cm.display,doc=cm.doc;e_preventDefault(e);var ourRange,ourIndex,startSel=doc.sel,ranges=startSel.ranges;if(addNew&&!e.shiftKey){ourIndex=doc.sel.contains(start);ourRange=ourIndex>-1?ranges[ourIndex]:new Range(start,start)}else{ourRange=doc.sel.primary();ourIndex=doc.sel.primIndex}if(chromeOS?e.shiftKey&&e.metaKey:e.altKey){type="rect";addNew||(ourRange=new Range(start,start));start=posFromMouse(cm,e,!0,!0);ourIndex=-1}else if("double"==type){var word=cm.findWordAt(start);ourRange=cm.display.shift||doc.extend?extendRange(doc,ourRange,word.anchor,word.head):word}else if("triple"==type){var line=new Range(Pos(start.line,0),clipPos(doc,Pos(start.line+1,0)));ourRange=cm.display.shift||doc.extend?extendRange(doc,ourRange,line.anchor,line.head):line}else ourRange=extendRange(doc,ourRange,start);if(addNew)if(-1==ourIndex){ourIndex=ranges.length;setSelection(doc,normalizeSelection(ranges.concat([ourRange]),ourIndex),{scroll:!1,origin:"*mouse"})}else if(ranges.length>1&&ranges[ourIndex].empty()&&"single"==type&&!e.shiftKey){setSelection(doc,normalizeSelection(ranges.slice(0,ourIndex).concat(ranges.slice(ourIndex+1)),0),{scroll:!1,origin:"*mouse"});startSel=doc.sel}else replaceOneSelection(doc,ourIndex,ourRange,sel_mouse);else{ourIndex=0;setSelection(doc,new Selection([ourRange],0),sel_mouse);startSel=doc.sel}var lastPos=start,editorSize=display.wrapper.getBoundingClientRect(),counter=0,move=operation(cm,function(e){e_button(e)?extend(e):done(e)}),up=operation(cm,done);cm.state.selectingText=up;on(document,"mousemove",move);on(document,"mouseup",up)}function gutterEvent(cm,e,type,prevent){try{var mX=e.clientX,mY=e.clientY}catch(e){return!1}if(mX>=Math.floor(cm.display.gutters.getBoundingClientRect().right))return!1;prevent&&e_preventDefault(e);var display=cm.display,lineBox=display.lineDiv.getBoundingClientRect();if(mY>lineBox.bottom||!hasHandler(cm,type))return e_defaultPrevented(e);mY-=lineBox.top-display.viewOffset;for(var i=0;i<cm.options.gutters.length;++i){var g=display.gutters.childNodes[i];if(g&&g.getBoundingClientRect().right>=mX){var line=lineAtHeight(cm.doc,mY),gutter=cm.options.gutters[i];signal(cm,type,cm,line,gutter,e);return e_defaultPrevented(e)}}}function clickInGutter(cm,e){return gutterEvent(cm,e,"gutterClick",!0)}function onDrop(e){var cm=this;clearDragCursor(cm);if(!signalDOMEvent(cm,e)&&!eventInWidget(cm.display,e)){e_preventDefault(e);ie&&(lastDrop=+new Date);var pos=posFromMouse(cm,e,!0),files=e.dataTransfer.files;if(pos&&!cm.isReadOnly())if(files&&files.length&&window.FileReader&&window.File)for(var n=files.length,text=Array(n),read=0,loadFile=function(file,i){if(!cm.options.allowDropFileTypes||-1!=indexOf(cm.options.allowDropFileTypes,file.type)){var reader=new FileReader;reader.onload=operation(cm,function(){var content=reader.result;/[\x00-\x08\x0e-\x1f]{2}/.test(content)&&(content="");text[i]=content;if(++read==n){pos=clipPos(cm.doc,pos);var change={from:pos,to:pos,text:cm.doc.splitLines(text.join(cm.doc.lineSeparator())),origin:"paste"};makeChange(cm.doc,change);setSelectionReplaceHistory(cm.doc,simpleSelection(pos,changeEnd(change)))}});reader.readAsText(file)}},i=0;n>i;++i)loadFile(files[i],i);else{if(cm.state.draggingText&&cm.doc.sel.contains(pos)>-1){cm.state.draggingText(e);setTimeout(function(){cm.display.input.focus()},20);return}try{var text=e.dataTransfer.getData("Text");if(text){if(cm.state.draggingText&&!(mac?e.altKey:e.ctrlKey))var selected=cm.listSelections();setSelectionNoUndo(cm.doc,simpleSelection(pos,pos));if(selected)for(var i=0;i<selected.length;++i)replaceRange(cm.doc,"",selected[i].anchor,selected[i].head,"drag");cm.replaceSelection(text,"around","paste");cm.display.input.focus()}}catch(e){}}}}function onDragStart(cm,e){if(ie&&(!cm.state.draggingText||+new Date-lastDrop<100))e_stop(e);else if(!signalDOMEvent(cm,e)&&!eventInWidget(cm.display,e)){e.dataTransfer.setData("Text",cm.getSelection());e.dataTransfer.effectAllowed="copyMove";if(e.dataTransfer.setDragImage&&!safari){var img=elt("img",null,null,"position: fixed; left: 0; top: 0;");img.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";if(presto){img.width=img.height=1;cm.display.wrapper.appendChild(img);img._top=img.offsetTop}e.dataTransfer.setDragImage(img,0,0);presto&&img.parentNode.removeChild(img)}}}function onDragOver(cm,e){var pos=posFromMouse(cm,e);if(pos){var frag=document.createDocumentFragment();drawSelectionCursor(cm,pos,frag);if(!cm.display.dragCursor){cm.display.dragCursor=elt("div",null,"CodeMirror-cursors CodeMirror-dragcursors");cm.display.lineSpace.insertBefore(cm.display.dragCursor,cm.display.cursorDiv)}removeChildrenAndAdd(cm.display.dragCursor,frag)}}function clearDragCursor(cm){if(cm.display.dragCursor){cm.display.lineSpace.removeChild(cm.display.dragCursor);cm.display.dragCursor=null}}function setScrollTop(cm,val){if(!(Math.abs(cm.doc.scrollTop-val)<2)){cm.doc.scrollTop=val;gecko||updateDisplaySimple(cm,{top:val});cm.display.scroller.scrollTop!=val&&(cm.display.scroller.scrollTop=val);cm.display.scrollbars.setScrollTop(val);gecko&&updateDisplaySimple(cm);startWorker(cm,100)}}function setScrollLeft(cm,val,isScroller){if(!(isScroller?val==cm.doc.scrollLeft:Math.abs(cm.doc.scrollLeft-val)<2)){val=Math.min(val,cm.display.scroller.scrollWidth-cm.display.scroller.clientWidth);cm.doc.scrollLeft=val;alignHorizontally(cm);cm.display.scroller.scrollLeft!=val&&(cm.display.scroller.scrollLeft=val);cm.display.scrollbars.setScrollLeft(val)}}function onScrollWheel(cm,e){var delta=wheelEventDelta(e),dx=delta.x,dy=delta.y,display=cm.display,scroll=display.scroller,canScrollX=scroll.scrollWidth>scroll.clientWidth,canScrollY=scroll.scrollHeight>scroll.clientHeight;if(dx&&canScrollX||dy&&canScrollY){if(dy&&mac&&webkit)outer:for(var cur=e.target,view=display.view;cur!=scroll;cur=cur.parentNode)for(var i=0;i<view.length;i++)if(view[i].node==cur){cm.display.currentWheelTarget=cur;break outer}if(!dx||gecko||presto||null==wheelPixelsPerUnit){if(dy&&null!=wheelPixelsPerUnit){var pixels=dy*wheelPixelsPerUnit,top=cm.doc.scrollTop,bot=top+display.wrapper.clientHeight;0>pixels?top=Math.max(0,top+pixels-50):bot=Math.min(cm.doc.height,bot+pixels+50);updateDisplaySimple(cm,{top:top,bottom:bot})}if(20>wheelSamples)if(null==display.wheelStartX){display.wheelStartX=scroll.scrollLeft;display.wheelStartY=scroll.scrollTop;display.wheelDX=dx;display.wheelDY=dy;setTimeout(function(){if(null!=display.wheelStartX){var movedX=scroll.scrollLeft-display.wheelStartX,movedY=scroll.scrollTop-display.wheelStartY,sample=movedY&&display.wheelDY&&movedY/display.wheelDY||movedX&&display.wheelDX&&movedX/display.wheelDX;display.wheelStartX=display.wheelStartY=null;if(sample){wheelPixelsPerUnit=(wheelPixelsPerUnit*wheelSamples+sample)/(wheelSamples+1);++wheelSamples}}},200)}else{display.wheelDX+=dx;display.wheelDY+=dy}}else{dy&&canScrollY&&setScrollTop(cm,Math.max(0,Math.min(scroll.scrollTop+dy*wheelPixelsPerUnit,scroll.scrollHeight-scroll.clientHeight)));setScrollLeft(cm,Math.max(0,Math.min(scroll.scrollLeft+dx*wheelPixelsPerUnit,scroll.scrollWidth-scroll.clientWidth)));(!dy||dy&&canScrollY)&&e_preventDefault(e);display.wheelStartX=null}}}function doHandleBinding(cm,bound,dropShift){if("string"==typeof bound){bound=commands[bound];if(!bound)return!1}cm.display.input.ensurePolled();var prevShift=cm.display.shift,done=!1;try{cm.isReadOnly()&&(cm.state.suppressEdits=!0);dropShift&&(cm.display.shift=!1);done=bound(cm)!=Pass}finally{cm.display.shift=prevShift;cm.state.suppressEdits=!1}return done}function lookupKeyForEditor(cm,name,handle){for(var i=0;i<cm.state.keyMaps.length;i++){var result=lookupKey(name,cm.state.keyMaps[i],handle,cm);if(result)return result}return cm.options.extraKeys&&lookupKey(name,cm.options.extraKeys,handle,cm)||lookupKey(name,cm.options.keyMap,handle,cm)}function dispatchKey(cm,name,e,handle){var seq=cm.state.keySeq;if(seq){if(isModifierKey(name))return"handled";stopSeq.set(50,function(){if(cm.state.keySeq==seq){cm.state.keySeq=null;cm.display.input.reset()}});name=seq+" "+name}var result=lookupKeyForEditor(cm,name,handle);"multi"==result&&(cm.state.keySeq=name);"handled"==result&&signalLater(cm,"keyHandled",cm,name,e);if("handled"==result||"multi"==result){e_preventDefault(e);restartBlink(cm)}if(seq&&!result&&/\'$/.test(name)){e_preventDefault(e);return!0}return!!result}function handleKeyBinding(cm,e){var name=keyName(e,!0);return name?e.shiftKey&&!cm.state.keySeq?dispatchKey(cm,"Shift-"+name,e,function(b){return doHandleBinding(cm,b,!0)})||dispatchKey(cm,name,e,function(b){return("string"==typeof b?/^go[A-Z]/.test(b):b.motion)?doHandleBinding(cm,b):void 0}):dispatchKey(cm,name,e,function(b){return doHandleBinding(cm,b)}):!1}function handleCharBinding(cm,e,ch){return dispatchKey(cm,"'"+ch+"'",e,function(b){return doHandleBinding(cm,b,!0)})}function onKeyDown(e){var cm=this;cm.curOp.focus=activeElt();if(!signalDOMEvent(cm,e)){ie&&11>ie_version&&27==e.keyCode&&(e.returnValue=!1);var code=e.keyCode;cm.display.shift=16==code||e.shiftKey;var handled=handleKeyBinding(cm,e);if(presto){lastStoppedKey=handled?code:null;!handled&&88==code&&!hasCopyEvent&&(mac?e.metaKey:e.ctrlKey)&&cm.replaceSelection("",null,"cut")}18!=code||/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)||showCrossHair(cm)}}function showCrossHair(cm){function up(e){if(18==e.keyCode||!e.altKey){rmClass(lineDiv,"CodeMirror-crosshair");off(document,"keyup",up);off(document,"mouseover",up)}}var lineDiv=cm.display.lineDiv;addClass(lineDiv,"CodeMirror-crosshair");on(document,"keyup",up);on(document,"mouseover",up)}function onKeyUp(e){16==e.keyCode&&(this.doc.sel.shift=!1);signalDOMEvent(this,e)}function onKeyPress(e){var cm=this;if(!(eventInWidget(cm.display,e)||signalDOMEvent(cm,e)||e.ctrlKey&&!e.altKey||mac&&e.metaKey)){var keyCode=e.keyCode,charCode=e.charCode;if(presto&&keyCode==lastStoppedKey){lastStoppedKey=null;e_preventDefault(e)}else if(!presto||e.which&&!(e.which<10)||!handleKeyBinding(cm,e)){var ch=String.fromCharCode(null==charCode?keyCode:charCode);handleCharBinding(cm,e,ch)||cm.display.input.onKeyPress(e)}}}function delayBlurEvent(cm){cm.state.delayingBlurEvent=!0;setTimeout(function(){if(cm.state.delayingBlurEvent){cm.state.delayingBlurEvent=!1;onBlur(cm)}},100)}function onFocus(cm){cm.state.delayingBlurEvent&&(cm.state.delayingBlurEvent=!1);if("nocursor"!=cm.options.readOnly){if(!cm.state.focused){signal(cm,"focus",cm);cm.state.focused=!0;addClass(cm.display.wrapper,"CodeMirror-focused");if(!cm.curOp&&cm.display.selForContextMenu!=cm.doc.sel){cm.display.input.reset();webkit&&setTimeout(function(){cm.display.input.reset(!0)},20)}cm.display.input.receivedFocus()}restartBlink(cm)}}function onBlur(cm){if(!cm.state.delayingBlurEvent){if(cm.state.focused){signal(cm,"blur",cm);cm.state.focused=!1;rmClass(cm.display.wrapper,"CodeMirror-focused")}clearInterval(cm.display.blinker);setTimeout(function(){cm.state.focused||(cm.display.shift=!1)},150)}}function onContextMenu(cm,e){eventInWidget(cm.display,e)||contextMenuInGutter(cm,e)||signalDOMEvent(cm,e,"contextmenu")||cm.display.input.onContextMenu(e)}function contextMenuInGutter(cm,e){return hasHandler(cm,"gutterContextMenu")?gutterEvent(cm,e,"gutterContextMenu",!1):!1}function adjustForChange(pos,change){if(cmp(pos,change.from)<0)return pos;if(cmp(pos,change.to)<=0)return changeEnd(change);var line=pos.line+change.text.length-(change.to.line-change.from.line)-1,ch=pos.ch;pos.line==change.to.line&&(ch+=changeEnd(change).ch-change.to.ch);return Pos(line,ch)}function computeSelAfterChange(doc,change){for(var out=[],i=0;i<doc.sel.ranges.length;i++){var range=doc.sel.ranges[i];out.push(new Range(adjustForChange(range.anchor,change),adjustForChange(range.head,change)))}return normalizeSelection(out,doc.sel.primIndex)}function offsetPos(pos,old,nw){return pos.line==old.line?Pos(nw.line,pos.ch-old.ch+nw.ch):Pos(nw.line+(pos.line-old.line),pos.ch)}function computeReplacedSel(doc,changes,hint){for(var out=[],oldPrev=Pos(doc.first,0),newPrev=oldPrev,i=0;i<changes.length;i++){var change=changes[i],from=offsetPos(change.from,oldPrev,newPrev),to=offsetPos(changeEnd(change),oldPrev,newPrev);oldPrev=change.to;newPrev=to;if("around"==hint){var range=doc.sel.ranges[i],inv=cmp(range.head,range.anchor)<0;out[i]=new Range(inv?to:from,inv?from:to)}else out[i]=new Range(from,from)}return new Selection(out,doc.sel.primIndex)}function filterChange(doc,change,update){var obj={canceled:!1,from:change.from,to:change.to,text:change.text,origin:change.origin,cancel:function(){this.canceled=!0}};update&&(obj.update=function(from,to,text,origin){from&&(this.from=clipPos(doc,from));to&&(this.to=clipPos(doc,to));text&&(this.text=text);void 0!==origin&&(this.origin=origin)});signal(doc,"beforeChange",doc,obj);doc.cm&&signal(doc.cm,"beforeChange",doc.cm,obj);return obj.canceled?null:{from:obj.from,to:obj.to,text:obj.text,origin:obj.origin}}function makeChange(doc,change,ignoreReadOnly){if(doc.cm){if(!doc.cm.curOp)return operation(doc.cm,makeChange)(doc,change,ignoreReadOnly);if(doc.cm.state.suppressEdits)return}if(hasHandler(doc,"beforeChange")||doc.cm&&hasHandler(doc.cm,"beforeChange")){change=filterChange(doc,change,!0);if(!change)return}var split=sawReadOnlySpans&&!ignoreReadOnly&&removeReadOnlyRanges(doc,change.from,change.to);if(split)for(var i=split.length-1;i>=0;--i)makeChangeInner(doc,{from:split[i].from,to:split[i].to,text:i?[""]:change.text});else makeChangeInner(doc,change)}function makeChangeInner(doc,change){if(1!=change.text.length||""!=change.text[0]||0!=cmp(change.from,change.to)){var selAfter=computeSelAfterChange(doc,change);addChangeToHistory(doc,change,selAfter,doc.cm?doc.cm.curOp.id:NaN);makeChangeSingleDoc(doc,change,selAfter,stretchSpansOverChange(doc,change));var rebased=[];linkedDocs(doc,function(doc,sharedHist){if(!sharedHist&&-1==indexOf(rebased,doc.history)){rebaseHist(doc.history,change);rebased.push(doc.history)}makeChangeSingleDoc(doc,change,null,stretchSpansOverChange(doc,change))})}}function makeChangeFromHistory(doc,type,allowSelectionOnly){if(!doc.cm||!doc.cm.state.suppressEdits){for(var event,hist=doc.history,selAfter=doc.sel,source="undo"==type?hist.done:hist.undone,dest="undo"==type?hist.undone:hist.done,i=0;i<source.length;i++){event=source[i];if(allowSelectionOnly?event.ranges&&!event.equals(doc.sel):!event.ranges)break}if(i!=source.length){hist.lastOrigin=hist.lastSelOrigin=null;for(;;){event=source.pop();if(!event.ranges)break;pushSelectionToHistory(event,dest);if(allowSelectionOnly&&!event.equals(doc.sel)){setSelection(doc,event,{clearRedo:!1});return}selAfter=event}var antiChanges=[];pushSelectionToHistory(selAfter,dest);dest.push({changes:antiChanges,generation:hist.generation});hist.generation=event.generation||++hist.maxGeneration;for(var filter=hasHandler(doc,"beforeChange")||doc.cm&&hasHandler(doc.cm,"beforeChange"),i=event.changes.length-1;i>=0;--i){var change=event.changes[i];change.origin=type;if(filter&&!filterChange(doc,change,!1)){source.length=0;return}antiChanges.push(historyChangeFromChange(doc,change));var after=i?computeSelAfterChange(doc,change):lst(source);makeChangeSingleDoc(doc,change,after,mergeOldSpans(doc,change));!i&&doc.cm&&doc.cm.scrollIntoView({from:change.from,to:changeEnd(change)});var rebased=[];linkedDocs(doc,function(doc,sharedHist){if(!sharedHist&&-1==indexOf(rebased,doc.history)){rebaseHist(doc.history,change);rebased.push(doc.history)}makeChangeSingleDoc(doc,change,null,mergeOldSpans(doc,change))})}}}}function shiftDoc(doc,distance){if(0!=distance){doc.first+=distance;doc.sel=new Selection(map(doc.sel.ranges,function(range){return new Range(Pos(range.anchor.line+distance,range.anchor.ch),Pos(range.head.line+distance,range.head.ch))}),doc.sel.primIndex);if(doc.cm){regChange(doc.cm,doc.first,doc.first-distance,distance);for(var d=doc.cm.display,l=d.viewFrom;l<d.viewTo;l++)regLineChange(doc.cm,l,"gutter")}}}function makeChangeSingleDoc(doc,change,selAfter,spans){if(doc.cm&&!doc.cm.curOp)return operation(doc.cm,makeChangeSingleDoc)(doc,change,selAfter,spans);if(change.to.line<doc.first)shiftDoc(doc,change.text.length-1-(change.to.line-change.from.line));else if(!(change.from.line>doc.lastLine())){if(change.from.line<doc.first){var shift=change.text.length-1-(doc.first-change.from.line);shiftDoc(doc,shift);change={from:Pos(doc.first,0),to:Pos(change.to.line+shift,change.to.ch),text:[lst(change.text)],origin:change.origin}}var last=doc.lastLine();change.to.line>last&&(change={from:change.from,to:Pos(last,getLine(doc,last).text.length),text:[change.text[0]],origin:change.origin});change.removed=getBetween(doc,change.from,change.to);selAfter||(selAfter=computeSelAfterChange(doc,change));doc.cm?makeChangeSingleDocInEditor(doc.cm,change,spans):updateDoc(doc,change,spans);setSelectionNoUndo(doc,selAfter,sel_dontScroll)}}function makeChangeSingleDocInEditor(cm,change,spans){var doc=cm.doc,display=cm.display,from=change.from,to=change.to,recomputeMaxLength=!1,checkWidthStart=from.line;if(!cm.options.lineWrapping){checkWidthStart=lineNo(visualLine(getLine(doc,from.line)));doc.iter(checkWidthStart,to.line+1,function(line){if(line==display.maxLine){recomputeMaxLength=!0;return!0}})}doc.sel.contains(change.from,change.to)>-1&&signalCursorActivity(cm);updateDoc(doc,change,spans,estimateHeight(cm));if(!cm.options.lineWrapping){doc.iter(checkWidthStart,from.line+change.text.length,function(line){var len=lineLength(line);if(len>display.maxLineLength){display.maxLine=line;display.maxLineLength=len;display.maxLineChanged=!0;recomputeMaxLength=!1}});recomputeMaxLength&&(cm.curOp.updateMaxLine=!0)}doc.frontier=Math.min(doc.frontier,from.line);startWorker(cm,400);var lendiff=change.text.length-(to.line-from.line)-1;change.full?regChange(cm):from.line!=to.line||1!=change.text.length||isWholeLineUpdate(cm.doc,change)?regChange(cm,from.line,to.line+1,lendiff):regLineChange(cm,from.line,"text");var changesHandler=hasHandler(cm,"changes"),changeHandler=hasHandler(cm,"change");if(changeHandler||changesHandler){var obj={from:from,to:to,text:change.text,removed:change.removed,origin:change.origin};changeHandler&&signalLater(cm,"change",cm,obj);changesHandler&&(cm.curOp.changeObjs||(cm.curOp.changeObjs=[])).push(obj)}cm.display.selForContextMenu=null}function replaceRange(doc,code,from,to,origin){to||(to=from);if(cmp(to,from)<0){var tmp=to;to=from;from=tmp}"string"==typeof code&&(code=doc.splitLines(code));makeChange(doc,{from:from,to:to,text:code,origin:origin})}function maybeScrollWindow(cm,coords){if(!signalDOMEvent(cm,"scrollCursorIntoView")){var display=cm.display,box=display.sizer.getBoundingClientRect(),doScroll=null;coords.top+box.top<0?doScroll=!0:coords.bottom+box.top>(window.innerHeight||document.documentElement.clientHeight)&&(doScroll=!1);if(null!=doScroll&&!phantom){var scrollNode=elt("div","​",null,"position: absolute; top: "+(coords.top-display.viewOffset-paddingTop(cm.display))+"px; height: "+(coords.bottom-coords.top+scrollGap(cm)+display.barHeight)+"px; left: "+coords.left+"px; width: 2px;");cm.display.lineSpace.appendChild(scrollNode);scrollNode.scrollIntoView(doScroll);cm.display.lineSpace.removeChild(scrollNode)}}}function scrollPosIntoView(cm,pos,end,margin){null==margin&&(margin=0);for(var limit=0;5>limit;limit++){var changed=!1,coords=cursorCoords(cm,pos),endCoords=end&&end!=pos?cursorCoords(cm,end):coords,scrollPos=calculateScrollPos(cm,Math.min(coords.left,endCoords.left),Math.min(coords.top,endCoords.top)-margin,Math.max(coords.left,endCoords.left),Math.max(coords.bottom,endCoords.bottom)+margin),startTop=cm.doc.scrollTop,startLeft=cm.doc.scrollLeft;if(null!=scrollPos.scrollTop){setScrollTop(cm,scrollPos.scrollTop);Math.abs(cm.doc.scrollTop-startTop)>1&&(changed=!0)}if(null!=scrollPos.scrollLeft){setScrollLeft(cm,scrollPos.scrollLeft);Math.abs(cm.doc.scrollLeft-startLeft)>1&&(changed=!0)}if(!changed)break}return coords}function scrollIntoView(cm,x1,y1,x2,y2){var scrollPos=calculateScrollPos(cm,x1,y1,x2,y2);null!=scrollPos.scrollTop&&setScrollTop(cm,scrollPos.scrollTop);null!=scrollPos.scrollLeft&&setScrollLeft(cm,scrollPos.scrollLeft)}function calculateScrollPos(cm,x1,y1,x2,y2){var display=cm.display,snapMargin=textHeight(cm.display);0>y1&&(y1=0);var screentop=cm.curOp&&null!=cm.curOp.scrollTop?cm.curOp.scrollTop:display.scroller.scrollTop,screen=displayHeight(cm),result={};y2-y1>screen&&(y2=y1+screen);var docBottom=cm.doc.height+paddingVert(display),atTop=snapMargin>y1,atBottom=y2>docBottom-snapMargin;if(screentop>y1)result.scrollTop=atTop?0:y1;else if(y2>screentop+screen){var newTop=Math.min(y1,(atBottom?docBottom:y2)-screen);newTop!=screentop&&(result.scrollTop=newTop)}var screenleft=cm.curOp&&null!=cm.curOp.scrollLeft?cm.curOp.scrollLeft:display.scroller.scrollLeft,screenw=displayWidth(cm)-(cm.options.fixedGutter?display.gutters.offsetWidth:0),tooWide=x2-x1>screenw;tooWide&&(x2=x1+screenw);10>x1?result.scrollLeft=0:screenleft>x1?result.scrollLeft=Math.max(0,x1-(tooWide?0:10)):x2>screenw+screenleft-3&&(result.scrollLeft=x2+(tooWide?0:10)-screenw);return result}function addToScrollPos(cm,left,top){(null!=left||null!=top)&&resolveScrollToPos(cm);null!=left&&(cm.curOp.scrollLeft=(null==cm.curOp.scrollLeft?cm.doc.scrollLeft:cm.curOp.scrollLeft)+left);null!=top&&(cm.curOp.scrollTop=(null==cm.curOp.scrollTop?cm.doc.scrollTop:cm.curOp.scrollTop)+top)}function ensureCursorVisible(cm){resolveScrollToPos(cm);var cur=cm.getCursor(),from=cur,to=cur;if(!cm.options.lineWrapping){from=cur.ch?Pos(cur.line,cur.ch-1):cur;to=Pos(cur.line,cur.ch+1)}cm.curOp.scrollToPos={from:from,to:to,margin:cm.options.cursorScrollMargin,isCursor:!0}}function resolveScrollToPos(cm){var range=cm.curOp.scrollToPos;if(range){cm.curOp.scrollToPos=null;var from=estimateCoords(cm,range.from),to=estimateCoords(cm,range.to),sPos=calculateScrollPos(cm,Math.min(from.left,to.left),Math.min(from.top,to.top)-range.margin,Math.max(from.right,to.right),Math.max(from.bottom,to.bottom)+range.margin);cm.scrollTo(sPos.scrollLeft,sPos.scrollTop)}}function indentLine(cm,n,how,aggressive){var state,doc=cm.doc;null==how&&(how="add");"smart"==how&&(doc.mode.indent?state=getStateBefore(cm,n):how="prev");var tabSize=cm.options.tabSize,line=getLine(doc,n),curSpace=countColumn(line.text,null,tabSize);line.stateAfter&&(line.stateAfter=null);var indentation,curSpaceString=line.text.match(/^\s*/)[0];if(aggressive||/\S/.test(line.text)){if("smart"==how){indentation=doc.mode.indent(state,line.text.slice(curSpaceString.length),line.text);
4
- if(indentation==Pass||indentation>150){if(!aggressive)return;how="prev"}}}else{indentation=0;how="not"}"prev"==how?indentation=n>doc.first?countColumn(getLine(doc,n-1).text,null,tabSize):0:"add"==how?indentation=curSpace+cm.options.indentUnit:"subtract"==how?indentation=curSpace-cm.options.indentUnit:"number"==typeof how&&(indentation=curSpace+how);indentation=Math.max(0,indentation);var indentString="",pos=0;if(cm.options.indentWithTabs)for(var i=Math.floor(indentation/tabSize);i;--i){pos+=tabSize;indentString+=" "}indentation>pos&&(indentString+=spaceStr(indentation-pos));if(indentString!=curSpaceString){replaceRange(doc,indentString,Pos(n,0),Pos(n,curSpaceString.length),"+input");line.stateAfter=null;return!0}for(var i=0;i<doc.sel.ranges.length;i++){var range=doc.sel.ranges[i];if(range.head.line==n&&range.head.ch<curSpaceString.length){var pos=Pos(n,curSpaceString.length);replaceOneSelection(doc,i,new Range(pos,pos));break}}}function changeLine(doc,handle,changeType,op){var no=handle,line=handle;"number"==typeof handle?line=getLine(doc,clipLine(doc,handle)):no=lineNo(handle);if(null==no)return null;op(line,no)&&doc.cm&&regLineChange(doc.cm,no,changeType);return line}function deleteNearSelection(cm,compute){for(var ranges=cm.doc.sel.ranges,kill=[],i=0;i<ranges.length;i++){for(var toKill=compute(ranges[i]);kill.length&&cmp(toKill.from,lst(kill).to)<=0;){var replaced=kill.pop();if(cmp(replaced.from,toKill.from)<0){toKill.from=replaced.from;break}}kill.push(toKill)}runInOp(cm,function(){for(var i=kill.length-1;i>=0;i--)replaceRange(cm.doc,"",kill[i].from,kill[i].to,"+delete");ensureCursorVisible(cm)})}function findPosH(doc,pos,dir,unit,visually){function findNextLine(){var l=line+dir;if(l<doc.first||l>=doc.first+doc.size)return!1;line=l;return lineObj=getLine(doc,l)}function moveOnce(boundToLine){var next=(visually?moveVisually:moveLogically)(lineObj,ch,dir,!0);if(null==next){if(boundToLine||!findNextLine())return!1;ch=visually?(0>dir?lineRight:lineLeft)(lineObj):0>dir?lineObj.text.length:0}else ch=next;return!0}var line=pos.line,ch=pos.ch,origDir=dir,lineObj=getLine(doc,line);if("char"==unit)moveOnce();else if("column"==unit)moveOnce(!0);else if("word"==unit||"group"==unit)for(var sawType=null,group="group"==unit,helper=doc.cm&&doc.cm.getHelper(pos,"wordChars"),first=!0;!(0>dir)||moveOnce(!first);first=!1){var cur=lineObj.text.charAt(ch)||"\n",type=isWordChar(cur,helper)?"w":group&&"\n"==cur?"n":!group||/\s/.test(cur)?null:"p";!group||first||type||(type="s");if(sawType&&sawType!=type){if(0>dir){dir=1;moveOnce()}break}type&&(sawType=type);if(dir>0&&!moveOnce(!first))break}var result=skipAtomic(doc,Pos(line,ch),pos,origDir,!0);cmp(pos,result)||(result.hitSide=!0);return result}function findPosV(cm,pos,dir,unit){var y,doc=cm.doc,x=pos.left;if("page"==unit){var pageSize=Math.min(cm.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight);y=pos.top+dir*(pageSize-(0>dir?1.5:.5)*textHeight(cm.display))}else"line"==unit&&(y=dir>0?pos.bottom+3:pos.top-3);for(;;){var target=coordsChar(cm,x,y);if(!target.outside)break;if(0>dir?0>=y:y>=doc.height){target.hitSide=!0;break}y+=5*dir}return target}function option(name,deflt,handle,notOnInit){CodeMirror.defaults[name]=deflt;handle&&(optionHandlers[name]=notOnInit?function(cm,val,old){old!=Init&&handle(cm,val,old)}:handle)}function normalizeKeyName(name){for(var alt,ctrl,shift,cmd,parts=name.split(/-(?!$)/),name=parts[parts.length-1],i=0;i<parts.length-1;i++){var mod=parts[i];if(/^(cmd|meta|m)$/i.test(mod))cmd=!0;else if(/^a(lt)?$/i.test(mod))alt=!0;else if(/^(c|ctrl|control)$/i.test(mod))ctrl=!0;else{if(!/^s(hift)$/i.test(mod))throw new Error("Unrecognized modifier name: "+mod);shift=!0}}alt&&(name="Alt-"+name);ctrl&&(name="Ctrl-"+name);cmd&&(name="Cmd-"+name);shift&&(name="Shift-"+name);return name}function getKeyMap(val){return"string"==typeof val?keyMap[val]:val}function markText(doc,from,to,options,type){if(options&&options.shared)return markTextShared(doc,from,to,options,type);if(doc.cm&&!doc.cm.curOp)return operation(doc.cm,markText)(doc,from,to,options,type);var marker=new TextMarker(doc,type),diff=cmp(from,to);options&&copyObj(options,marker,!1);if(diff>0||0==diff&&marker.clearWhenEmpty!==!1)return marker;if(marker.replacedWith){marker.collapsed=!0;marker.widgetNode=elt("span",[marker.replacedWith],"CodeMirror-widget");options.handleMouseEvents||marker.widgetNode.setAttribute("cm-ignore-events","true");options.insertLeft&&(marker.widgetNode.insertLeft=!0)}if(marker.collapsed){if(conflictingCollapsedRange(doc,from.line,from,to,marker)||from.line!=to.line&&conflictingCollapsedRange(doc,to.line,from,to,marker))throw new Error("Inserting collapsed marker partially overlapping an existing one");sawCollapsedSpans=!0}marker.addToHistory&&addChangeToHistory(doc,{from:from,to:to,origin:"markText"},doc.sel,NaN);var updateMaxLine,curLine=from.line,cm=doc.cm;doc.iter(curLine,to.line+1,function(line){cm&&marker.collapsed&&!cm.options.lineWrapping&&visualLine(line)==cm.display.maxLine&&(updateMaxLine=!0);marker.collapsed&&curLine!=from.line&&updateLineHeight(line,0);addMarkedSpan(line,new MarkedSpan(marker,curLine==from.line?from.ch:null,curLine==to.line?to.ch:null));++curLine});marker.collapsed&&doc.iter(from.line,to.line+1,function(line){lineIsHidden(doc,line)&&updateLineHeight(line,0)});marker.clearOnEnter&&on(marker,"beforeCursorEnter",function(){marker.clear()});if(marker.readOnly){sawReadOnlySpans=!0;(doc.history.done.length||doc.history.undone.length)&&doc.clearHistory()}if(marker.collapsed){marker.id=++nextMarkerId;marker.atomic=!0}if(cm){updateMaxLine&&(cm.curOp.updateMaxLine=!0);if(marker.collapsed)regChange(cm,from.line,to.line+1);else if(marker.className||marker.title||marker.startStyle||marker.endStyle||marker.css)for(var i=from.line;i<=to.line;i++)regLineChange(cm,i,"text");marker.atomic&&reCheckSelection(cm.doc);signalLater(cm,"markerAdded",cm,marker)}return marker}function markTextShared(doc,from,to,options,type){options=copyObj(options);options.shared=!1;var markers=[markText(doc,from,to,options,type)],primary=markers[0],widget=options.widgetNode;linkedDocs(doc,function(doc){widget&&(options.widgetNode=widget.cloneNode(!0));markers.push(markText(doc,clipPos(doc,from),clipPos(doc,to),options,type));for(var i=0;i<doc.linked.length;++i)if(doc.linked[i].isParent)return;primary=lst(markers)});return new SharedTextMarker(markers,primary)}function findSharedMarkers(doc){return doc.findMarks(Pos(doc.first,0),doc.clipPos(Pos(doc.lastLine())),function(m){return m.parent})}function copySharedMarkers(doc,markers){for(var i=0;i<markers.length;i++){var marker=markers[i],pos=marker.find(),mFrom=doc.clipPos(pos.from),mTo=doc.clipPos(pos.to);if(cmp(mFrom,mTo)){var subMark=markText(doc,mFrom,mTo,marker.primary,marker.primary.type);marker.markers.push(subMark);subMark.parent=marker}}}function detachSharedMarkers(markers){for(var i=0;i<markers.length;i++){var marker=markers[i],linked=[marker.primary.doc];linkedDocs(marker.primary.doc,function(d){linked.push(d)});for(var j=0;j<marker.markers.length;j++){var subMarker=marker.markers[j];if(-1==indexOf(linked,subMarker.doc)){subMarker.parent=null;marker.markers.splice(j--,1)}}}}function MarkedSpan(marker,from,to){this.marker=marker;this.from=from;this.to=to}function getMarkedSpanFor(spans,marker){if(spans)for(var i=0;i<spans.length;++i){var span=spans[i];if(span.marker==marker)return span}}function removeMarkedSpan(spans,span){for(var r,i=0;i<spans.length;++i)spans[i]!=span&&(r||(r=[])).push(spans[i]);return r}function addMarkedSpan(line,span){line.markedSpans=line.markedSpans?line.markedSpans.concat([span]):[span];span.marker.attachLine(line)}function markedSpansBefore(old,startCh,isInsert){if(old)for(var nw,i=0;i<old.length;++i){var span=old[i],marker=span.marker,startsBefore=null==span.from||(marker.inclusiveLeft?span.from<=startCh:span.from<startCh);if(startsBefore||span.from==startCh&&"bookmark"==marker.type&&(!isInsert||!span.marker.insertLeft)){var endsAfter=null==span.to||(marker.inclusiveRight?span.to>=startCh:span.to>startCh);(nw||(nw=[])).push(new MarkedSpan(marker,span.from,endsAfter?null:span.to))}}return nw}function markedSpansAfter(old,endCh,isInsert){if(old)for(var nw,i=0;i<old.length;++i){var span=old[i],marker=span.marker,endsAfter=null==span.to||(marker.inclusiveRight?span.to>=endCh:span.to>endCh);if(endsAfter||span.from==endCh&&"bookmark"==marker.type&&(!isInsert||span.marker.insertLeft)){var startsBefore=null==span.from||(marker.inclusiveLeft?span.from<=endCh:span.from<endCh);(nw||(nw=[])).push(new MarkedSpan(marker,startsBefore?null:span.from-endCh,null==span.to?null:span.to-endCh))}}return nw}function stretchSpansOverChange(doc,change){if(change.full)return null;var oldFirst=isLine(doc,change.from.line)&&getLine(doc,change.from.line).markedSpans,oldLast=isLine(doc,change.to.line)&&getLine(doc,change.to.line).markedSpans;if(!oldFirst&&!oldLast)return null;var startCh=change.from.ch,endCh=change.to.ch,isInsert=0==cmp(change.from,change.to),first=markedSpansBefore(oldFirst,startCh,isInsert),last=markedSpansAfter(oldLast,endCh,isInsert),sameLine=1==change.text.length,offset=lst(change.text).length+(sameLine?startCh:0);if(first)for(var i=0;i<first.length;++i){var span=first[i];if(null==span.to){var found=getMarkedSpanFor(last,span.marker);found?sameLine&&(span.to=null==found.to?null:found.to+offset):span.to=startCh}}if(last)for(var i=0;i<last.length;++i){var span=last[i];null!=span.to&&(span.to+=offset);if(null==span.from){var found=getMarkedSpanFor(first,span.marker);if(!found){span.from=offset;sameLine&&(first||(first=[])).push(span)}}else{span.from+=offset;sameLine&&(first||(first=[])).push(span)}}first&&(first=clearEmptySpans(first));last&&last!=first&&(last=clearEmptySpans(last));var newMarkers=[first];if(!sameLine){var gapMarkers,gap=change.text.length-2;if(gap>0&&first)for(var i=0;i<first.length;++i)null==first[i].to&&(gapMarkers||(gapMarkers=[])).push(new MarkedSpan(first[i].marker,null,null));for(var i=0;gap>i;++i)newMarkers.push(gapMarkers);newMarkers.push(last)}return newMarkers}function clearEmptySpans(spans){for(var i=0;i<spans.length;++i){var span=spans[i];null!=span.from&&span.from==span.to&&span.marker.clearWhenEmpty!==!1&&spans.splice(i--,1)}return spans.length?spans:null}function mergeOldSpans(doc,change){var old=getOldSpans(doc,change),stretched=stretchSpansOverChange(doc,change);if(!old)return stretched;if(!stretched)return old;for(var i=0;i<old.length;++i){var oldCur=old[i],stretchCur=stretched[i];if(oldCur&&stretchCur)spans:for(var j=0;j<stretchCur.length;++j){for(var span=stretchCur[j],k=0;k<oldCur.length;++k)if(oldCur[k].marker==span.marker)continue spans;oldCur.push(span)}else stretchCur&&(old[i]=stretchCur)}return old}function removeReadOnlyRanges(doc,from,to){var markers=null;doc.iter(from.line,to.line+1,function(line){if(line.markedSpans)for(var i=0;i<line.markedSpans.length;++i){var mark=line.markedSpans[i].marker;!mark.readOnly||markers&&-1!=indexOf(markers,mark)||(markers||(markers=[])).push(mark)}});if(!markers)return null;for(var parts=[{from:from,to:to}],i=0;i<markers.length;++i)for(var mk=markers[i],m=mk.find(0),j=0;j<parts.length;++j){var p=parts[j];if(!(cmp(p.to,m.from)<0||cmp(p.from,m.to)>0)){var newParts=[j,1],dfrom=cmp(p.from,m.from),dto=cmp(p.to,m.to);(0>dfrom||!mk.inclusiveLeft&&!dfrom)&&newParts.push({from:p.from,to:m.from});(dto>0||!mk.inclusiveRight&&!dto)&&newParts.push({from:m.to,to:p.to});parts.splice.apply(parts,newParts);j+=newParts.length-1}}return parts}function detachMarkedSpans(line){var spans=line.markedSpans;if(spans){for(var i=0;i<spans.length;++i)spans[i].marker.detachLine(line);line.markedSpans=null}}function attachMarkedSpans(line,spans){if(spans){for(var i=0;i<spans.length;++i)spans[i].marker.attachLine(line);line.markedSpans=spans}}function extraLeft(marker){return marker.inclusiveLeft?-1:0}function extraRight(marker){return marker.inclusiveRight?1:0}function compareCollapsedMarkers(a,b){var lenDiff=a.lines.length-b.lines.length;if(0!=lenDiff)return lenDiff;var aPos=a.find(),bPos=b.find(),fromCmp=cmp(aPos.from,bPos.from)||extraLeft(a)-extraLeft(b);if(fromCmp)return-fromCmp;var toCmp=cmp(aPos.to,bPos.to)||extraRight(a)-extraRight(b);return toCmp?toCmp:b.id-a.id}function collapsedSpanAtSide(line,start){var found,sps=sawCollapsedSpans&&line.markedSpans;if(sps)for(var sp,i=0;i<sps.length;++i){sp=sps[i];sp.marker.collapsed&&null==(start?sp.from:sp.to)&&(!found||compareCollapsedMarkers(found,sp.marker)<0)&&(found=sp.marker)}return found}function collapsedSpanAtStart(line){return collapsedSpanAtSide(line,!0)}function collapsedSpanAtEnd(line){return collapsedSpanAtSide(line,!1)}function conflictingCollapsedRange(doc,lineNo,from,to,marker){var line=getLine(doc,lineNo),sps=sawCollapsedSpans&&line.markedSpans;if(sps)for(var i=0;i<sps.length;++i){var sp=sps[i];if(sp.marker.collapsed){var found=sp.marker.find(0),fromCmp=cmp(found.from,from)||extraLeft(sp.marker)-extraLeft(marker),toCmp=cmp(found.to,to)||extraRight(sp.marker)-extraRight(marker);if(!(fromCmp>=0&&0>=toCmp||0>=fromCmp&&toCmp>=0)&&(0>=fromCmp&&(cmp(found.to,from)>0||sp.marker.inclusiveRight&&marker.inclusiveLeft)||fromCmp>=0&&(cmp(found.from,to)<0||sp.marker.inclusiveLeft&&marker.inclusiveRight)))return!0}}}function visualLine(line){for(var merged;merged=collapsedSpanAtStart(line);)line=merged.find(-1,!0).line;return line}function visualLineContinued(line){for(var merged,lines;merged=collapsedSpanAtEnd(line);){line=merged.find(1,!0).line;(lines||(lines=[])).push(line)}return lines}function visualLineNo(doc,lineN){var line=getLine(doc,lineN),vis=visualLine(line);return line==vis?lineN:lineNo(vis)}function visualLineEndNo(doc,lineN){if(lineN>doc.lastLine())return lineN;var merged,line=getLine(doc,lineN);if(!lineIsHidden(doc,line))return lineN;for(;merged=collapsedSpanAtEnd(line);)line=merged.find(1,!0).line;return lineNo(line)+1}function lineIsHidden(doc,line){var sps=sawCollapsedSpans&&line.markedSpans;if(sps)for(var sp,i=0;i<sps.length;++i){sp=sps[i];if(sp.marker.collapsed){if(null==sp.from)return!0;if(!sp.marker.widgetNode&&0==sp.from&&sp.marker.inclusiveLeft&&lineIsHiddenInner(doc,line,sp))return!0}}}function lineIsHiddenInner(doc,line,span){if(null==span.to){var end=span.marker.find(1,!0);return lineIsHiddenInner(doc,end.line,getMarkedSpanFor(end.line.markedSpans,span.marker))}if(span.marker.inclusiveRight&&span.to==line.text.length)return!0;for(var sp,i=0;i<line.markedSpans.length;++i){sp=line.markedSpans[i];if(sp.marker.collapsed&&!sp.marker.widgetNode&&sp.from==span.to&&(null==sp.to||sp.to!=span.from)&&(sp.marker.inclusiveLeft||span.marker.inclusiveRight)&&lineIsHiddenInner(doc,line,sp))return!0}}function adjustScrollWhenAboveVisible(cm,line,diff){heightAtLine(line)<(cm.curOp&&cm.curOp.scrollTop||cm.doc.scrollTop)&&addToScrollPos(cm,null,diff)}function widgetHeight(widget){if(null!=widget.height)return widget.height;var cm=widget.doc.cm;if(!cm)return 0;if(!contains(document.body,widget.node)){var parentStyle="position: relative;";widget.coverGutter&&(parentStyle+="margin-left: -"+cm.display.gutters.offsetWidth+"px;");widget.noHScroll&&(parentStyle+="width: "+cm.display.wrapper.clientWidth+"px;");removeChildrenAndAdd(cm.display.measure,elt("div",[widget.node],null,parentStyle))}return widget.height=widget.node.parentNode.offsetHeight}function addLineWidget(doc,handle,node,options){var widget=new LineWidget(doc,node,options),cm=doc.cm;cm&&widget.noHScroll&&(cm.display.alignWidgets=!0);changeLine(doc,handle,"widget",function(line){var widgets=line.widgets||(line.widgets=[]);null==widget.insertAt?widgets.push(widget):widgets.splice(Math.min(widgets.length-1,Math.max(0,widget.insertAt)),0,widget);widget.line=line;if(cm&&!lineIsHidden(doc,line)){var aboveVisible=heightAtLine(line)<doc.scrollTop;updateLineHeight(line,line.height+widgetHeight(widget));aboveVisible&&addToScrollPos(cm,null,widget.height);cm.curOp.forceUpdate=!0}return!0});return widget}function updateLine(line,text,markedSpans,estimateHeight){line.text=text;line.stateAfter&&(line.stateAfter=null);line.styles&&(line.styles=null);null!=line.order&&(line.order=null);detachMarkedSpans(line);attachMarkedSpans(line,markedSpans);var estHeight=estimateHeight?estimateHeight(line):1;estHeight!=line.height&&updateLineHeight(line,estHeight)}function cleanUpLine(line){line.parent=null;detachMarkedSpans(line)}function extractLineClasses(type,output){if(type)for(;;){var lineClass=type.match(/(?:^|\s+)line-(background-)?(\S+)/);if(!lineClass)break;type=type.slice(0,lineClass.index)+type.slice(lineClass.index+lineClass[0].length);var prop=lineClass[1]?"bgClass":"textClass";null==output[prop]?output[prop]=lineClass[2]:new RegExp("(?:^|s)"+lineClass[2]+"(?:$|s)").test(output[prop])||(output[prop]+=" "+lineClass[2])}return type}function callBlankLine(mode,state){if(mode.blankLine)return mode.blankLine(state);if(mode.innerMode){var inner=CodeMirror.innerMode(mode,state);return inner.mode.blankLine?inner.mode.blankLine(inner.state):void 0}}function readToken(mode,stream,state,inner){for(var i=0;10>i;i++){inner&&(inner[0]=CodeMirror.innerMode(mode,state).mode);var style=mode.token(stream,state);if(stream.pos>stream.start)return style}throw new Error("Mode "+mode.name+" failed to advance stream.")}function takeToken(cm,pos,precise,asArray){function getObj(copy){return{start:stream.start,end:stream.pos,string:stream.current(),type:style||null,state:copy?copyState(doc.mode,state):state}}var style,doc=cm.doc,mode=doc.mode;pos=clipPos(doc,pos);var tokens,line=getLine(doc,pos.line),state=getStateBefore(cm,pos.line,precise),stream=new StringStream(line.text,cm.options.tabSize);asArray&&(tokens=[]);for(;(asArray||stream.pos<pos.ch)&&!stream.eol();){stream.start=stream.pos;style=readToken(mode,stream,state);asArray&&tokens.push(getObj(!0))}return asArray?tokens:getObj()}function runMode(cm,text,mode,state,f,lineClasses,forceToEnd){var flattenSpans=mode.flattenSpans;null==flattenSpans&&(flattenSpans=cm.options.flattenSpans);var style,curStart=0,curStyle=null,stream=new StringStream(text,cm.options.tabSize),inner=cm.options.addModeClass&&[null];""==text&&extractLineClasses(callBlankLine(mode,state),lineClasses);for(;!stream.eol();){if(stream.pos>cm.options.maxHighlightLength){flattenSpans=!1;forceToEnd&&processLine(cm,text,state,stream.pos);stream.pos=text.length;style=null}else style=extractLineClasses(readToken(mode,stream,state,inner),lineClasses);if(inner){var mName=inner[0].name;mName&&(style="m-"+(style?mName+" "+style:mName))}if(!flattenSpans||curStyle!=style){for(;curStart<stream.start;){curStart=Math.min(stream.start,curStart+5e4);f(curStart,curStyle)}curStyle=style}stream.start=stream.pos}for(;curStart<stream.pos;){var pos=Math.min(stream.pos,curStart+5e4);f(pos,curStyle);curStart=pos}}function highlightLine(cm,line,state,forceToEnd){var st=[cm.state.modeGen],lineClasses={};runMode(cm,line.text,cm.doc.mode,state,function(end,style){st.push(end,style)},lineClasses,forceToEnd);for(var o=0;o<cm.state.overlays.length;++o){var overlay=cm.state.overlays[o],i=1,at=0;runMode(cm,line.text,overlay.mode,!0,function(end,style){for(var start=i;end>at;){var i_end=st[i];i_end>end&&st.splice(i,1,end,st[i+1],i_end);i+=2;at=Math.min(end,i_end)}if(style)if(overlay.opaque){st.splice(start,i-start,end,"cm-overlay "+style);i=start+2}else for(;i>start;start+=2){var cur=st[start+1];st[start+1]=(cur?cur+" ":"")+"cm-overlay "+style}},lineClasses)}return{styles:st,classes:lineClasses.bgClass||lineClasses.textClass?lineClasses:null}}function getLineStyles(cm,line,updateFrontier){if(!line.styles||line.styles[0]!=cm.state.modeGen){var state=getStateBefore(cm,lineNo(line)),result=highlightLine(cm,line,line.text.length>cm.options.maxHighlightLength?copyState(cm.doc.mode,state):state);line.stateAfter=state;line.styles=result.styles;result.classes?line.styleClasses=result.classes:line.styleClasses&&(line.styleClasses=null);updateFrontier===cm.doc.frontier&&cm.doc.frontier++}return line.styles}function processLine(cm,text,state,startAt){var mode=cm.doc.mode,stream=new StringStream(text,cm.options.tabSize);stream.start=stream.pos=startAt||0;""==text&&callBlankLine(mode,state);for(;!stream.eol();){readToken(mode,stream,state);stream.start=stream.pos}}function interpretTokenStyle(style,options){if(!style||/^\s*$/.test(style))return null;var cache=options.addModeClass?styleToClassCacheWithMode:styleToClassCache;return cache[style]||(cache[style]=style.replace(/\S+/g,"cm-$&"))}function buildLineContent(cm,lineView){var content=elt("span",null,null,webkit?"padding-right: .1px":null),builder={pre:elt("pre",[content],"CodeMirror-line"),content:content,col:0,pos:0,cm:cm,splitSpaces:(ie||webkit)&&cm.getOption("lineWrapping")};lineView.measure={};for(var i=0;i<=(lineView.rest?lineView.rest.length:0);i++){var order,line=i?lineView.rest[i-1]:lineView.line;builder.pos=0;builder.addToken=buildToken;hasBadBidiRects(cm.display.measure)&&(order=getOrder(line))&&(builder.addToken=buildTokenBadBidi(builder.addToken,order));builder.map=[];var allowFrontierUpdate=lineView!=cm.display.externalMeasured&&lineNo(line);insertLineContent(line,builder,getLineStyles(cm,line,allowFrontierUpdate));if(line.styleClasses){line.styleClasses.bgClass&&(builder.bgClass=joinClasses(line.styleClasses.bgClass,builder.bgClass||""));line.styleClasses.textClass&&(builder.textClass=joinClasses(line.styleClasses.textClass,builder.textClass||""))}0==builder.map.length&&builder.map.push(0,0,builder.content.appendChild(zeroWidthElement(cm.display.measure)));if(0==i){lineView.measure.map=builder.map;lineView.measure.cache={}}else{(lineView.measure.maps||(lineView.measure.maps=[])).push(builder.map);(lineView.measure.caches||(lineView.measure.caches=[])).push({})}}webkit&&/\bcm-tab\b/.test(builder.content.lastChild.className)&&(builder.content.className="cm-tab-wrap-hack");signal(cm,"renderLine",cm,lineView.line,builder.pre);builder.pre.className&&(builder.textClass=joinClasses(builder.pre.className,builder.textClass||""));return builder}function defaultSpecialCharPlaceholder(ch){var token=elt("span","•","cm-invalidchar");token.title="\\u"+ch.charCodeAt(0).toString(16);token.setAttribute("aria-label",token.title);return token}function buildToken(builder,text,style,startStyle,endStyle,title,css){if(text){var displayText=builder.splitSpaces?text.replace(/ {3,}/g,splitSpaces):text,special=builder.cm.state.specialChars,mustWrap=!1;if(special.test(text))for(var content=document.createDocumentFragment(),pos=0;;){special.lastIndex=pos;var m=special.exec(text),skipped=m?m.index-pos:text.length-pos;if(skipped){var txt=document.createTextNode(displayText.slice(pos,pos+skipped));ie&&9>ie_version?content.appendChild(elt("span",[txt])):content.appendChild(txt);builder.map.push(builder.pos,builder.pos+skipped,txt);builder.col+=skipped;builder.pos+=skipped}if(!m)break;pos+=skipped+1;if(" "==m[0]){var tabSize=builder.cm.options.tabSize,tabWidth=tabSize-builder.col%tabSize,txt=content.appendChild(elt("span",spaceStr(tabWidth),"cm-tab"));txt.setAttribute("role","presentation");txt.setAttribute("cm-text"," ");builder.col+=tabWidth}else if("\r"==m[0]||"\n"==m[0]){var txt=content.appendChild(elt("span","\r"==m[0]?"␍":"␤","cm-invalidchar"));txt.setAttribute("cm-text",m[0]);builder.col+=1}else{var txt=builder.cm.options.specialCharPlaceholder(m[0]);txt.setAttribute("cm-text",m[0]);ie&&9>ie_version?content.appendChild(elt("span",[txt])):content.appendChild(txt);builder.col+=1}builder.map.push(builder.pos,builder.pos+1,txt);builder.pos++}else{builder.col+=text.length;var content=document.createTextNode(displayText);builder.map.push(builder.pos,builder.pos+text.length,content);ie&&9>ie_version&&(mustWrap=!0);builder.pos+=text.length}if(style||startStyle||endStyle||mustWrap||css){var fullStyle=style||"";startStyle&&(fullStyle+=startStyle);endStyle&&(fullStyle+=endStyle);var token=elt("span",[content],fullStyle,css);title&&(token.title=title);return builder.content.appendChild(token)}builder.content.appendChild(content)}}function splitSpaces(old){for(var out=" ",i=0;i<old.length-2;++i)out+=i%2?" ":" ";out+=" ";return out}function buildTokenBadBidi(inner,order){return function(builder,text,style,startStyle,endStyle,title,css){style=style?style+" cm-force-border":"cm-force-border";for(var start=builder.pos,end=start+text.length;;){for(var i=0;i<order.length;i++){var part=order[i];if(part.to>start&&part.from<=start)break}if(part.to>=end)return inner(builder,text,style,startStyle,endStyle,title,css);inner(builder,text.slice(0,part.to-start),style,startStyle,null,title,css);startStyle=null;text=text.slice(part.to-start);start=part.to}}}function buildCollapsedSpan(builder,size,marker,ignoreWidget){var widget=!ignoreWidget&&marker.widgetNode;widget&&builder.map.push(builder.pos,builder.pos+size,widget);if(!ignoreWidget&&builder.cm.display.input.needsContentAttribute){widget||(widget=builder.content.appendChild(document.createElement("span")));widget.setAttribute("cm-marker",marker.id)}if(widget){builder.cm.display.input.setUneditable(widget);builder.content.appendChild(widget)}builder.pos+=size}function insertLineContent(line,builder,styles){var spans=line.markedSpans,allText=line.text,at=0;if(spans)for(var style,css,spanStyle,spanEndStyle,spanStartStyle,title,collapsed,len=allText.length,pos=0,i=1,text="",nextChange=0;;){if(nextChange==pos){spanStyle=spanEndStyle=spanStartStyle=title=css="";collapsed=null;nextChange=1/0;for(var endStyles,foundBookmarks=[],j=0;j<spans.length;++j){var sp=spans[j],m=sp.marker;if("bookmark"==m.type&&sp.from==pos&&m.widgetNode)foundBookmarks.push(m);else if(sp.from<=pos&&(null==sp.to||sp.to>pos||m.collapsed&&sp.to==pos&&sp.from==pos)){if(null!=sp.to&&sp.to!=pos&&nextChange>sp.to){nextChange=sp.to;spanEndStyle=""}m.className&&(spanStyle+=" "+m.className);m.css&&(css=(css?css+";":"")+m.css);m.startStyle&&sp.from==pos&&(spanStartStyle+=" "+m.startStyle);m.endStyle&&sp.to==nextChange&&(endStyles||(endStyles=[])).push(m.endStyle,sp.to);m.title&&!title&&(title=m.title);m.collapsed&&(!collapsed||compareCollapsedMarkers(collapsed.marker,m)<0)&&(collapsed=sp)}else sp.from>pos&&nextChange>sp.from&&(nextChange=sp.from)}if(endStyles)for(var j=0;j<endStyles.length;j+=2)endStyles[j+1]==nextChange&&(spanEndStyle+=" "+endStyles[j]);if(!collapsed||collapsed.from==pos)for(var j=0;j<foundBookmarks.length;++j)buildCollapsedSpan(builder,0,foundBookmarks[j]);if(collapsed&&(collapsed.from||0)==pos){buildCollapsedSpan(builder,(null==collapsed.to?len+1:collapsed.to)-pos,collapsed.marker,null==collapsed.from);if(null==collapsed.to)return;collapsed.to==pos&&(collapsed=!1)}}if(pos>=len)break;for(var upto=Math.min(len,nextChange);;){if(text){var end=pos+text.length;if(!collapsed){var tokenText=end>upto?text.slice(0,upto-pos):text;builder.addToken(builder,tokenText,style?style+spanStyle:spanStyle,spanStartStyle,pos+tokenText.length==nextChange?spanEndStyle:"",title,css)}if(end>=upto){text=text.slice(upto-pos);pos=upto;break}pos=end;spanStartStyle=""}text=allText.slice(at,at=styles[i++]);style=interpretTokenStyle(styles[i++],builder.cm.options)}}else for(var i=1;i<styles.length;i+=2)builder.addToken(builder,allText.slice(at,at=styles[i]),interpretTokenStyle(styles[i+1],builder.cm.options))}function isWholeLineUpdate(doc,change){return 0==change.from.ch&&0==change.to.ch&&""==lst(change.text)&&(!doc.cm||doc.cm.options.wholeLineUpdateBefore)}function updateDoc(doc,change,markedSpans,estimateHeight){function spansFor(n){return markedSpans?markedSpans[n]:null}function update(line,text,spans){updateLine(line,text,spans,estimateHeight);signalLater(line,"change",line,change)}function linesFor(start,end){for(var i=start,result=[];end>i;++i)result.push(new Line(text[i],spansFor(i),estimateHeight));return result}var from=change.from,to=change.to,text=change.text,firstLine=getLine(doc,from.line),lastLine=getLine(doc,to.line),lastText=lst(text),lastSpans=spansFor(text.length-1),nlines=to.line-from.line;if(change.full){doc.insert(0,linesFor(0,text.length));doc.remove(text.length,doc.size-text.length)}else if(isWholeLineUpdate(doc,change)){var added=linesFor(0,text.length-1);update(lastLine,lastLine.text,lastSpans);nlines&&doc.remove(from.line,nlines);added.length&&doc.insert(from.line,added)}else if(firstLine==lastLine)if(1==text.length)update(firstLine,firstLine.text.slice(0,from.ch)+lastText+firstLine.text.slice(to.ch),lastSpans);else{var added=linesFor(1,text.length-1);added.push(new Line(lastText+firstLine.text.slice(to.ch),lastSpans,estimateHeight));update(firstLine,firstLine.text.slice(0,from.ch)+text[0],spansFor(0));doc.insert(from.line+1,added)}else if(1==text.length){update(firstLine,firstLine.text.slice(0,from.ch)+text[0]+lastLine.text.slice(to.ch),spansFor(0));doc.remove(from.line+1,nlines)}else{update(firstLine,firstLine.text.slice(0,from.ch)+text[0],spansFor(0));update(lastLine,lastText+lastLine.text.slice(to.ch),lastSpans);var added=linesFor(1,text.length-1);nlines>1&&doc.remove(from.line+1,nlines-1);doc.insert(from.line+1,added)}signalLater(doc,"change",doc,change)}function LeafChunk(lines){this.lines=lines;this.parent=null;for(var i=0,height=0;i<lines.length;++i){lines[i].parent=this;height+=lines[i].height}this.height=height}function BranchChunk(children){this.children=children;for(var size=0,height=0,i=0;i<children.length;++i){var ch=children[i];size+=ch.chunkSize();height+=ch.height;ch.parent=this}this.size=size;this.height=height;this.parent=null}function linkedDocs(doc,f,sharedHistOnly){function propagate(doc,skip,sharedHist){if(doc.linked)for(var i=0;i<doc.linked.length;++i){var rel=doc.linked[i];if(rel.doc!=skip){var shared=sharedHist&&rel.sharedHist;if(!sharedHistOnly||shared){f(rel.doc,shared);propagate(rel.doc,doc,shared)}}}}propagate(doc,null,!0)}function attachDoc(cm,doc){if(doc.cm)throw new Error("This document is already in use.");cm.doc=doc;doc.cm=cm;estimateLineHeights(cm);loadMode(cm);cm.options.lineWrapping||findMaxLine(cm);cm.options.mode=doc.modeOption;regChange(cm)}function getLine(doc,n){n-=doc.first;if(0>n||n>=doc.size)throw new Error("There is no line "+(n+doc.first)+" in the document.");for(var chunk=doc;!chunk.lines;)for(var i=0;;++i){var child=chunk.children[i],sz=child.chunkSize();if(sz>n){chunk=child;break}n-=sz}return chunk.lines[n]}function getBetween(doc,start,end){var out=[],n=start.line;doc.iter(start.line,end.line+1,function(line){var text=line.text;n==end.line&&(text=text.slice(0,end.ch));n==start.line&&(text=text.slice(start.ch));out.push(text);++n});return out}function getLines(doc,from,to){var out=[];doc.iter(from,to,function(line){out.push(line.text)});return out}function updateLineHeight(line,height){var diff=height-line.height;if(diff)for(var n=line;n;n=n.parent)n.height+=diff}function lineNo(line){if(null==line.parent)return null;for(var cur=line.parent,no=indexOf(cur.lines,line),chunk=cur.parent;chunk;cur=chunk,chunk=chunk.parent)for(var i=0;chunk.children[i]!=cur;++i)no+=chunk.children[i].chunkSize();return no+cur.first}function lineAtHeight(chunk,h){var n=chunk.first;outer:do{for(var i=0;i<chunk.children.length;++i){var child=chunk.children[i],ch=child.height;if(ch>h){chunk=child;continue outer}h-=ch;n+=child.chunkSize()}return n}while(!chunk.lines);for(var i=0;i<chunk.lines.length;++i){var line=chunk.lines[i],lh=line.height;if(lh>h)break;h-=lh}return n+i}function heightAtLine(lineObj){lineObj=visualLine(lineObj);for(var h=0,chunk=lineObj.parent,i=0;i<chunk.lines.length;++i){var line=chunk.lines[i];if(line==lineObj)break;h+=line.height}for(var p=chunk.parent;p;chunk=p,p=chunk.parent)for(var i=0;i<p.children.length;++i){var cur=p.children[i];if(cur==chunk)break;h+=cur.height}return h}function getOrder(line){var order=line.order;null==order&&(order=line.order=bidiOrdering(line.text));return order}function History(startGen){this.done=[];this.undone=[];this.undoDepth=1/0;this.lastModTime=this.lastSelTime=0;this.lastOp=this.lastSelOp=null;this.lastOrigin=this.lastSelOrigin=null;this.generation=this.maxGeneration=startGen||1;
5
- }function historyChangeFromChange(doc,change){var histChange={from:copyPos(change.from),to:changeEnd(change),text:getBetween(doc,change.from,change.to)};attachLocalSpans(doc,histChange,change.from.line,change.to.line+1);linkedDocs(doc,function(doc){attachLocalSpans(doc,histChange,change.from.line,change.to.line+1)},!0);return histChange}function clearSelectionEvents(array){for(;array.length;){var last=lst(array);if(!last.ranges)break;array.pop()}}function lastChangeEvent(hist,force){if(force){clearSelectionEvents(hist.done);return lst(hist.done)}if(hist.done.length&&!lst(hist.done).ranges)return lst(hist.done);if(hist.done.length>1&&!hist.done[hist.done.length-2].ranges){hist.done.pop();return lst(hist.done)}}function addChangeToHistory(doc,change,selAfter,opId){var hist=doc.history;hist.undone.length=0;var cur,time=+new Date;if((hist.lastOp==opId||hist.lastOrigin==change.origin&&change.origin&&("+"==change.origin.charAt(0)&&doc.cm&&hist.lastModTime>time-doc.cm.options.historyEventDelay||"*"==change.origin.charAt(0)))&&(cur=lastChangeEvent(hist,hist.lastOp==opId))){var last=lst(cur.changes);0==cmp(change.from,change.to)&&0==cmp(change.from,last.to)?last.to=changeEnd(change):cur.changes.push(historyChangeFromChange(doc,change))}else{var before=lst(hist.done);before&&before.ranges||pushSelectionToHistory(doc.sel,hist.done);cur={changes:[historyChangeFromChange(doc,change)],generation:hist.generation};hist.done.push(cur);for(;hist.done.length>hist.undoDepth;){hist.done.shift();hist.done[0].ranges||hist.done.shift()}}hist.done.push(selAfter);hist.generation=++hist.maxGeneration;hist.lastModTime=hist.lastSelTime=time;hist.lastOp=hist.lastSelOp=opId;hist.lastOrigin=hist.lastSelOrigin=change.origin;last||signal(doc,"historyAdded")}function selectionEventCanBeMerged(doc,origin,prev,sel){var ch=origin.charAt(0);return"*"==ch||"+"==ch&&prev.ranges.length==sel.ranges.length&&prev.somethingSelected()==sel.somethingSelected()&&new Date-doc.history.lastSelTime<=(doc.cm?doc.cm.options.historyEventDelay:500)}function addSelectionToHistory(doc,sel,opId,options){var hist=doc.history,origin=options&&options.origin;opId==hist.lastSelOp||origin&&hist.lastSelOrigin==origin&&(hist.lastModTime==hist.lastSelTime&&hist.lastOrigin==origin||selectionEventCanBeMerged(doc,origin,lst(hist.done),sel))?hist.done[hist.done.length-1]=sel:pushSelectionToHistory(sel,hist.done);hist.lastSelTime=+new Date;hist.lastSelOrigin=origin;hist.lastSelOp=opId;options&&options.clearRedo!==!1&&clearSelectionEvents(hist.undone)}function pushSelectionToHistory(sel,dest){var top=lst(dest);top&&top.ranges&&top.equals(sel)||dest.push(sel)}function attachLocalSpans(doc,change,from,to){var existing=change["spans_"+doc.id],n=0;doc.iter(Math.max(doc.first,from),Math.min(doc.first+doc.size,to),function(line){line.markedSpans&&((existing||(existing=change["spans_"+doc.id]={}))[n]=line.markedSpans);++n})}function removeClearedSpans(spans){if(!spans)return null;for(var out,i=0;i<spans.length;++i)spans[i].marker.explicitlyCleared?out||(out=spans.slice(0,i)):out&&out.push(spans[i]);return out?out.length?out:null:spans}function getOldSpans(doc,change){var found=change["spans_"+doc.id];if(!found)return null;for(var i=0,nw=[];i<change.text.length;++i)nw.push(removeClearedSpans(found[i]));return nw}function copyHistoryArray(events,newGroup,instantiateSel){for(var i=0,copy=[];i<events.length;++i){var event=events[i];if(event.ranges)copy.push(instantiateSel?Selection.prototype.deepCopy.call(event):event);else{var changes=event.changes,newChanges=[];copy.push({changes:newChanges});for(var j=0;j<changes.length;++j){var m,change=changes[j];newChanges.push({from:change.from,to:change.to,text:change.text});if(newGroup)for(var prop in change)if((m=prop.match(/^spans_(\d+)$/))&&indexOf(newGroup,Number(m[1]))>-1){lst(newChanges)[prop]=change[prop];delete change[prop]}}}}return copy}function rebaseHistSelSingle(pos,from,to,diff){if(to<pos.line)pos.line+=diff;else if(from<pos.line){pos.line=from;pos.ch=0}}function rebaseHistArray(array,from,to,diff){for(var i=0;i<array.length;++i){var sub=array[i],ok=!0;if(sub.ranges){if(!sub.copied){sub=array[i]=sub.deepCopy();sub.copied=!0}for(var j=0;j<sub.ranges.length;j++){rebaseHistSelSingle(sub.ranges[j].anchor,from,to,diff);rebaseHistSelSingle(sub.ranges[j].head,from,to,diff)}}else{for(var j=0;j<sub.changes.length;++j){var cur=sub.changes[j];if(to<cur.from.line){cur.from=Pos(cur.from.line+diff,cur.from.ch);cur.to=Pos(cur.to.line+diff,cur.to.ch)}else if(from<=cur.to.line){ok=!1;break}}if(!ok){array.splice(0,i+1);i=0}}}}function rebaseHist(hist,change){var from=change.from.line,to=change.to.line,diff=change.text.length-(to-from)-1;rebaseHistArray(hist.done,from,to,diff);rebaseHistArray(hist.undone,from,to,diff)}function e_defaultPrevented(e){return null!=e.defaultPrevented?e.defaultPrevented:0==e.returnValue}function e_target(e){return e.target||e.srcElement}function e_button(e){var b=e.which;null==b&&(1&e.button?b=1:2&e.button?b=3:4&e.button&&(b=2));mac&&e.ctrlKey&&1==b&&(b=3);return b}function getHandlers(emitter,type,copy){var arr=emitter._handlers&&emitter._handlers[type];return copy?arr&&arr.length>0?arr.slice():noHandlers:arr||noHandlers}function signalLater(emitter,type){function bnd(f){return function(){f.apply(null,args)}}var arr=getHandlers(emitter,type,!1);if(arr.length){var list,args=Array.prototype.slice.call(arguments,2);if(operationGroup)list=operationGroup.delayedCallbacks;else if(orphanDelayedCallbacks)list=orphanDelayedCallbacks;else{list=orphanDelayedCallbacks=[];setTimeout(fireOrphanDelayed,0)}for(var i=0;i<arr.length;++i)list.push(bnd(arr[i]))}}function fireOrphanDelayed(){var delayed=orphanDelayedCallbacks;orphanDelayedCallbacks=null;for(var i=0;i<delayed.length;++i)delayed[i]()}function signalDOMEvent(cm,e,override){"string"==typeof e&&(e={type:e,preventDefault:function(){this.defaultPrevented=!0}});signal(cm,override||e.type,cm,e);return e_defaultPrevented(e)||e.codemirrorIgnore}function signalCursorActivity(cm){var arr=cm._handlers&&cm._handlers.cursorActivity;if(arr)for(var set=cm.curOp.cursorActivityHandlers||(cm.curOp.cursorActivityHandlers=[]),i=0;i<arr.length;++i)-1==indexOf(set,arr[i])&&set.push(arr[i])}function hasHandler(emitter,type){return getHandlers(emitter,type).length>0}function eventMixin(ctor){ctor.prototype.on=function(type,f){on(this,type,f)};ctor.prototype.off=function(type,f){off(this,type,f)}}function Delayed(){this.id=null}function spaceStr(n){for(;spaceStrs.length<=n;)spaceStrs.push(lst(spaceStrs)+" ");return spaceStrs[n]}function lst(arr){return arr[arr.length-1]}function indexOf(array,elt){for(var i=0;i<array.length;++i)if(array[i]==elt)return i;return-1}function map(array,f){for(var out=[],i=0;i<array.length;i++)out[i]=f(array[i],i);return out}function nothing(){}function createObj(base,props){var inst;if(Object.create)inst=Object.create(base);else{nothing.prototype=base;inst=new nothing}props&&copyObj(props,inst);return inst}function copyObj(obj,target,overwrite){target||(target={});for(var prop in obj)!obj.hasOwnProperty(prop)||overwrite===!1&&target.hasOwnProperty(prop)||(target[prop]=obj[prop]);return target}function bind(f){var args=Array.prototype.slice.call(arguments,1);return function(){return f.apply(null,args)}}function isWordChar(ch,helper){return helper?helper.source.indexOf("\\w")>-1&&isWordCharBasic(ch)?!0:helper.test(ch):isWordCharBasic(ch)}function isEmpty(obj){for(var n in obj)if(obj.hasOwnProperty(n)&&obj[n])return!1;return!0}function isExtendingChar(ch){return ch.charCodeAt(0)>=768&&extendingChars.test(ch)}function elt(tag,content,className,style){var e=document.createElement(tag);className&&(e.className=className);style&&(e.style.cssText=style);if("string"==typeof content)e.appendChild(document.createTextNode(content));else if(content)for(var i=0;i<content.length;++i)e.appendChild(content[i]);return e}function removeChildren(e){for(var count=e.childNodes.length;count>0;--count)e.removeChild(e.firstChild);return e}function removeChildrenAndAdd(parent,e){return removeChildren(parent).appendChild(e)}function activeElt(){for(var activeElement=document.activeElement;activeElement&&activeElement.root&&activeElement.root.activeElement;)activeElement=activeElement.root.activeElement;return activeElement}function classTest(cls){return new RegExp("(^|\\s)"+cls+"(?:$|\\s)\\s*")}function joinClasses(a,b){for(var as=a.split(" "),i=0;i<as.length;i++)as[i]&&!classTest(as[i]).test(b)&&(b+=" "+as[i]);return b}function forEachCodeMirror(f){if(document.body.getElementsByClassName)for(var byClass=document.body.getElementsByClassName("CodeMirror"),i=0;i<byClass.length;i++){var cm=byClass[i].CodeMirror;cm&&f(cm)}}function ensureGlobalHandlers(){if(!globalsRegistered){registerGlobalHandlers();globalsRegistered=!0}}function registerGlobalHandlers(){var resizeTimer;on(window,"resize",function(){null==resizeTimer&&(resizeTimer=setTimeout(function(){resizeTimer=null;forEachCodeMirror(onResize)},100))});on(window,"blur",function(){forEachCodeMirror(onBlur)})}function zeroWidthElement(measure){if(null==zwspSupported){var test=elt("span","​");removeChildrenAndAdd(measure,elt("span",[test,document.createTextNode("x")]));0!=measure.firstChild.offsetHeight&&(zwspSupported=test.offsetWidth<=1&&test.offsetHeight>2&&!(ie&&8>ie_version))}var node=zwspSupported?elt("span","​"):elt("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px");node.setAttribute("cm-text","");return node}function hasBadBidiRects(measure){if(null!=badBidiRects)return badBidiRects;var txt=removeChildrenAndAdd(measure,document.createTextNode("AخA")),r0=range(txt,0,1).getBoundingClientRect();if(!r0||r0.left==r0.right)return!1;var r1=range(txt,1,2).getBoundingClientRect();return badBidiRects=r1.right-r0.right<3}function hasBadZoomedRects(measure){if(null!=badZoomedRects)return badZoomedRects;var node=removeChildrenAndAdd(measure,elt("span","x")),normal=node.getBoundingClientRect(),fromRange=range(node,0,1).getBoundingClientRect();return badZoomedRects=Math.abs(normal.left-fromRange.left)>1}function iterateBidiSections(order,from,to,f){if(!order)return f(from,to,"ltr");for(var found=!1,i=0;i<order.length;++i){var part=order[i];if(part.from<to&&part.to>from||from==to&&part.to==from){f(Math.max(part.from,from),Math.min(part.to,to),1==part.level?"rtl":"ltr");found=!0}}found||f(from,to,"ltr")}function bidiLeft(part){return part.level%2?part.to:part.from}function bidiRight(part){return part.level%2?part.from:part.to}function lineLeft(line){var order=getOrder(line);return order?bidiLeft(order[0]):0}function lineRight(line){var order=getOrder(line);return order?bidiRight(lst(order)):line.text.length}function lineStart(cm,lineN){var line=getLine(cm.doc,lineN),visual=visualLine(line);visual!=line&&(lineN=lineNo(visual));var order=getOrder(visual),ch=order?order[0].level%2?lineRight(visual):lineLeft(visual):0;return Pos(lineN,ch)}function lineEnd(cm,lineN){for(var merged,line=getLine(cm.doc,lineN);merged=collapsedSpanAtEnd(line);){line=merged.find(1,!0).line;lineN=null}var order=getOrder(line),ch=order?order[0].level%2?lineLeft(line):lineRight(line):line.text.length;return Pos(null==lineN?lineNo(line):lineN,ch)}function lineStartSmart(cm,pos){var start=lineStart(cm,pos.line),line=getLine(cm.doc,start.line),order=getOrder(line);if(!order||0==order[0].level){var firstNonWS=Math.max(0,line.text.search(/\S/)),inWS=pos.line==start.line&&pos.ch<=firstNonWS&&pos.ch;return Pos(start.line,inWS?0:firstNonWS)}return start}function compareBidiLevel(order,a,b){var linedir=order[0].level;return a==linedir?!0:b==linedir?!1:b>a}function getBidiPartAt(order,pos){bidiOther=null;for(var found,i=0;i<order.length;++i){var cur=order[i];if(cur.from<pos&&cur.to>pos)return i;if(cur.from==pos||cur.to==pos){if(null!=found){if(compareBidiLevel(order,cur.level,order[found].level)){cur.from!=cur.to&&(bidiOther=found);return i}cur.from!=cur.to&&(bidiOther=i);return found}found=i}}return found}function moveInLine(line,pos,dir,byUnit){if(!byUnit)return pos+dir;do pos+=dir;while(pos>0&&isExtendingChar(line.text.charAt(pos)));return pos}function moveVisually(line,start,dir,byUnit){var bidi=getOrder(line);if(!bidi)return moveLogically(line,start,dir,byUnit);for(var pos=getBidiPartAt(bidi,start),part=bidi[pos],target=moveInLine(line,start,part.level%2?-dir:dir,byUnit);;){if(target>part.from&&target<part.to)return target;if(target==part.from||target==part.to){if(getBidiPartAt(bidi,target)==pos)return target;part=bidi[pos+=dir];return dir>0==part.level%2?part.to:part.from}part=bidi[pos+=dir];if(!part)return null;target=dir>0==part.level%2?moveInLine(line,part.to,-1,byUnit):moveInLine(line,part.from,1,byUnit)}}function moveLogically(line,start,dir,byUnit){var target=start+dir;if(byUnit)for(;target>0&&isExtendingChar(line.text.charAt(target));)target+=dir;return 0>target||target>line.text.length?null:target}var userAgent=navigator.userAgent,platform=navigator.platform,gecko=/gecko\/\d/i.test(userAgent),ie_upto10=/MSIE \d/.test(userAgent),ie_11up=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent),ie=ie_upto10||ie_11up,ie_version=ie&&(ie_upto10?document.documentMode||6:ie_11up[1]),webkit=/WebKit\//.test(userAgent),qtwebkit=webkit&&/Qt\/\d+\.\d+/.test(userAgent),chrome=/Chrome\//.test(userAgent),presto=/Opera\//.test(userAgent),safari=/Apple Computer/.test(navigator.vendor),mac_geMountainLion=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent),phantom=/PhantomJS/.test(userAgent),ios=/AppleWebKit/.test(userAgent)&&/Mobile\/\w+/.test(userAgent),mobile=ios||/Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent),mac=ios||/Mac/.test(platform),chromeOS=/\bCrOS\b/.test(userAgent),windows=/win/i.test(platform),presto_version=presto&&userAgent.match(/Version\/(\d*\.\d*)/);presto_version&&(presto_version=Number(presto_version[1]));if(presto_version&&presto_version>=15){presto=!1;webkit=!0}var flipCtrlCmd=mac&&(qtwebkit||presto&&(null==presto_version||12.11>presto_version)),captureRightClick=gecko||ie&&ie_version>=9,sawReadOnlySpans=!1,sawCollapsedSpans=!1;NativeScrollbars.prototype=copyObj({update:function(measure){var needsH=measure.scrollWidth>measure.clientWidth+1,needsV=measure.scrollHeight>measure.clientHeight+1,sWidth=measure.nativeBarWidth;if(needsV){this.vert.style.display="block";this.vert.style.bottom=needsH?sWidth+"px":"0";var totalHeight=measure.viewHeight-(needsH?sWidth:0);this.vert.firstChild.style.height=Math.max(0,measure.scrollHeight-measure.clientHeight+totalHeight)+"px"}else{this.vert.style.display="";this.vert.firstChild.style.height="0"}if(needsH){this.horiz.style.display="block";this.horiz.style.right=needsV?sWidth+"px":"0";this.horiz.style.left=measure.barLeft+"px";var totalWidth=measure.viewWidth-measure.barLeft-(needsV?sWidth:0);this.horiz.firstChild.style.width=measure.scrollWidth-measure.clientWidth+totalWidth+"px"}else{this.horiz.style.display="";this.horiz.firstChild.style.width="0"}if(!this.checkedZeroWidth&&measure.clientHeight>0){0==sWidth&&this.zeroWidthHack();this.checkedZeroWidth=!0}return{right:needsV?sWidth:0,bottom:needsH?sWidth:0}},setScrollLeft:function(pos){this.horiz.scrollLeft!=pos&&(this.horiz.scrollLeft=pos);this.disableHoriz&&this.enableZeroWidthBar(this.horiz,this.disableHoriz)},setScrollTop:function(pos){this.vert.scrollTop!=pos&&(this.vert.scrollTop=pos);this.disableVert&&this.enableZeroWidthBar(this.vert,this.disableVert)},zeroWidthHack:function(){var w=mac&&!mac_geMountainLion?"12px":"18px";this.horiz.style.height=this.vert.style.width=w;this.horiz.style.pointerEvents=this.vert.style.pointerEvents="none";this.disableHoriz=new Delayed;this.disableVert=new Delayed},enableZeroWidthBar:function(bar,delay){function maybeDisable(){var box=bar.getBoundingClientRect(),elt=document.elementFromPoint(box.left+1,box.bottom-1);elt!=bar?bar.style.pointerEvents="none":delay.set(1e3,maybeDisable)}bar.style.pointerEvents="auto";delay.set(1e3,maybeDisable)},clear:function(){var parent=this.horiz.parentNode;parent.removeChild(this.horiz);parent.removeChild(this.vert)}},NativeScrollbars.prototype);NullScrollbars.prototype=copyObj({update:function(){return{bottom:0,right:0}},setScrollLeft:function(){},setScrollTop:function(){},clear:function(){}},NullScrollbars.prototype);CodeMirror.scrollbarModel={"native":NativeScrollbars,"null":NullScrollbars};DisplayUpdate.prototype.signal=function(emitter,type){hasHandler(emitter,type)&&this.events.push(arguments)};DisplayUpdate.prototype.finish=function(){for(var i=0;i<this.events.length;i++)signal.apply(null,this.events[i])};var Pos=CodeMirror.Pos=function(line,ch){if(!(this instanceof Pos))return new Pos(line,ch);this.line=line;this.ch=ch},cmp=CodeMirror.cmpPos=function(a,b){return a.line-b.line||a.ch-b.ch},lastCopied=null;TextareaInput.prototype=copyObj({init:function(display){function prepareCopyCut(e){if(!signalDOMEvent(cm,e)){if(cm.somethingSelected()){lastCopied=cm.getSelections();if(input.inaccurateSelection){input.prevInput="";input.inaccurateSelection=!1;te.value=lastCopied.join("\n");selectInput(te)}}else{if(!cm.options.lineWiseCopyCut)return;var ranges=copyableRanges(cm);lastCopied=ranges.text;if("cut"==e.type)cm.setSelections(ranges.ranges,null,sel_dontScroll);else{input.prevInput="";te.value=ranges.text.join("\n");selectInput(te)}}"cut"==e.type&&(cm.state.cutIncoming=!0)}}var input=this,cm=this.cm,div=this.wrapper=hiddenTextarea(),te=this.textarea=div.firstChild;display.wrapper.insertBefore(div,display.wrapper.firstChild);ios&&(te.style.width="0px");on(te,"input",function(){ie&&ie_version>=9&&input.hasSelection&&(input.hasSelection=null);input.poll()});on(te,"paste",function(e){if(!signalDOMEvent(cm,e)&&!handlePaste(e,cm)){cm.state.pasteIncoming=!0;input.fastPoll()}});on(te,"cut",prepareCopyCut);on(te,"copy",prepareCopyCut);on(display.scroller,"paste",function(e){if(!eventInWidget(display,e)&&!signalDOMEvent(cm,e)){cm.state.pasteIncoming=!0;input.focus()}});on(display.lineSpace,"selectstart",function(e){eventInWidget(display,e)||e_preventDefault(e)});on(te,"compositionstart",function(){var start=cm.getCursor("from");input.composing&&input.composing.range.clear();input.composing={start:start,range:cm.markText(start,cm.getCursor("to"),{className:"CodeMirror-composing"})}});on(te,"compositionend",function(){if(input.composing){input.poll();input.composing.range.clear();input.composing=null}})},prepareSelection:function(){var cm=this.cm,display=cm.display,doc=cm.doc,result=prepareSelection(cm);if(cm.options.moveInputWithCursor){var headPos=cursorCoords(cm,doc.sel.primary().head,"div"),wrapOff=display.wrapper.getBoundingClientRect(),lineOff=display.lineDiv.getBoundingClientRect();result.teTop=Math.max(0,Math.min(display.wrapper.clientHeight-10,headPos.top+lineOff.top-wrapOff.top));result.teLeft=Math.max(0,Math.min(display.wrapper.clientWidth-10,headPos.left+lineOff.left-wrapOff.left))}return result},showSelection:function(drawn){var cm=this.cm,display=cm.display;removeChildrenAndAdd(display.cursorDiv,drawn.cursors);removeChildrenAndAdd(display.selectionDiv,drawn.selection);if(null!=drawn.teTop){this.wrapper.style.top=drawn.teTop+"px";this.wrapper.style.left=drawn.teLeft+"px"}},reset:function(typing){if(!this.contextMenuPending){var minimal,selected,cm=this.cm,doc=cm.doc;if(cm.somethingSelected()){this.prevInput="";var range=doc.sel.primary();minimal=hasCopyEvent&&(range.to().line-range.from().line>100||(selected=cm.getSelection()).length>1e3);var content=minimal?"-":selected||cm.getSelection();this.textarea.value=content;cm.state.focused&&selectInput(this.textarea);ie&&ie_version>=9&&(this.hasSelection=content)}else if(!typing){this.prevInput=this.textarea.value="";ie&&ie_version>=9&&(this.hasSelection=null)}this.inaccurateSelection=minimal}},getField:function(){return this.textarea},supportsTouch:function(){return!1},focus:function(){if("nocursor"!=this.cm.options.readOnly&&(!mobile||activeElt()!=this.textarea))try{this.textarea.focus()}catch(e){}},blur:function(){this.textarea.blur()},resetPosition:function(){this.wrapper.style.top=this.wrapper.style.left=0},receivedFocus:function(){this.slowPoll()},slowPoll:function(){var input=this;input.pollingFast||input.polling.set(this.cm.options.pollInterval,function(){input.poll();input.cm.state.focused&&input.slowPoll()})},fastPoll:function(){function p(){var changed=input.poll();if(changed||missed){input.pollingFast=!1;input.slowPoll()}else{missed=!0;input.polling.set(60,p)}}var missed=!1,input=this;input.pollingFast=!0;input.polling.set(20,p)},poll:function(){var cm=this.cm,input=this.textarea,prevInput=this.prevInput;if(this.contextMenuPending||!cm.state.focused||hasSelection(input)&&!prevInput&&!this.composing||cm.isReadOnly()||cm.options.disableInput||cm.state.keySeq)return!1;var text=input.value;if(text==prevInput&&!cm.somethingSelected())return!1;if(ie&&ie_version>=9&&this.hasSelection===text||mac&&/[\uf700-\uf7ff]/.test(text)){cm.display.input.reset();return!1}if(cm.doc.sel==cm.display.selForContextMenu){var first=text.charCodeAt(0);8203!=first||prevInput||(prevInput="​");if(8666==first){this.reset();return this.cm.execCommand("undo")}}for(var same=0,l=Math.min(prevInput.length,text.length);l>same&&prevInput.charCodeAt(same)==text.charCodeAt(same);)++same;var self=this;runInOp(cm,function(){applyTextInput(cm,text.slice(same),prevInput.length-same,null,self.composing?"*compose":null);text.length>1e3||text.indexOf("\n")>-1?input.value=self.prevInput="":self.prevInput=text;if(self.composing){self.composing.range.clear();self.composing.range=cm.markText(self.composing.start,cm.getCursor("to"),{className:"CodeMirror-composing"})}});return!0},ensurePolled:function(){this.pollingFast&&this.poll()&&(this.pollingFast=!1)},onKeyPress:function(){ie&&ie_version>=9&&(this.hasSelection=null);this.fastPoll()},onContextMenu:function(e){function prepareSelectAllHack(){if(null!=te.selectionStart){var selected=cm.somethingSelected(),extval="​"+(selected?te.value:"");te.value="⇚";te.value=extval;input.prevInput=selected?"":"​";te.selectionStart=1;te.selectionEnd=extval.length;display.selForContextMenu=cm.doc.sel}}function rehide(){input.contextMenuPending=!1;input.wrapper.style.cssText=oldWrapperCSS;te.style.cssText=oldCSS;ie&&9>ie_version&&display.scrollbars.setScrollTop(display.scroller.scrollTop=scrollPos);if(null!=te.selectionStart){(!ie||ie&&9>ie_version)&&prepareSelectAllHack();var i=0,poll=function(){display.selForContextMenu==cm.doc.sel&&0==te.selectionStart&&te.selectionEnd>0&&"​"==input.prevInput?operation(cm,commands.selectAll)(cm):i++<10?display.detectingSelectAll=setTimeout(poll,500):display.input.reset()};display.detectingSelectAll=setTimeout(poll,200)}}var input=this,cm=input.cm,display=cm.display,te=input.textarea,pos=posFromMouse(cm,e),scrollPos=display.scroller.scrollTop;if(pos&&!presto){var reset=cm.options.resetSelectionOnContextMenu;reset&&-1==cm.doc.sel.contains(pos)&&operation(cm,setSelection)(cm.doc,simpleSelection(pos),sel_dontScroll);var oldCSS=te.style.cssText,oldWrapperCSS=input.wrapper.style.cssText;input.wrapper.style.cssText="position: absolute";var wrapperBox=input.wrapper.getBoundingClientRect();te.style.cssText="position: absolute; width: 30px; height: 30px; top: "+(e.clientY-wrapperBox.top-5)+"px; left: "+(e.clientX-wrapperBox.left-5)+"px; z-index: 1000; background: "+(ie?"rgba(255, 255, 255, .05)":"transparent")+"; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";if(webkit)var oldScrollY=window.scrollY;display.input.focus();webkit&&window.scrollTo(null,oldScrollY);display.input.reset();cm.somethingSelected()||(te.value=input.prevInput=" ");input.contextMenuPending=!0;display.selForContextMenu=cm.doc.sel;clearTimeout(display.detectingSelectAll);ie&&ie_version>=9&&prepareSelectAllHack();if(captureRightClick){e_stop(e);var mouseup=function(){off(window,"mouseup",mouseup);setTimeout(rehide,20)};on(window,"mouseup",mouseup)}else setTimeout(rehide,50)}},readOnlyChanged:function(val){val||this.reset()},setUneditable:nothing,needsContentAttribute:!1},TextareaInput.prototype);ContentEditableInput.prototype=copyObj({init:function(display){function onCopyCut(e){if(!signalDOMEvent(cm,e)){if(cm.somethingSelected()){lastCopied=cm.getSelections();"cut"==e.type&&cm.replaceSelection("",null,"cut")}else{if(!cm.options.lineWiseCopyCut)return;var ranges=copyableRanges(cm);lastCopied=ranges.text;"cut"==e.type&&cm.operation(function(){cm.setSelections(ranges.ranges,0,sel_dontScroll);cm.replaceSelection("",null,"cut")})}if(e.clipboardData&&!ios){e.preventDefault();e.clipboardData.clearData();e.clipboardData.setData("text/plain",lastCopied.join("\n"))}else{var kludge=hiddenTextarea(),te=kludge.firstChild;cm.display.lineSpace.insertBefore(kludge,cm.display.lineSpace.firstChild);te.value=lastCopied.join("\n");var hadFocus=document.activeElement;selectInput(te);setTimeout(function(){cm.display.lineSpace.removeChild(kludge);hadFocus.focus()},50)}}}var input=this,cm=input.cm,div=input.div=display.lineDiv;disableBrowserMagic(div);on(div,"paste",function(e){signalDOMEvent(cm,e)||handlePaste(e,cm)});on(div,"compositionstart",function(e){var data=e.data;input.composing={sel:cm.doc.sel,data:data,startData:data};if(data){var prim=cm.doc.sel.primary(),line=cm.getLine(prim.head.line),found=line.indexOf(data,Math.max(0,prim.head.ch-data.length));found>-1&&found<=prim.head.ch&&(input.composing.sel=simpleSelection(Pos(prim.head.line,found),Pos(prim.head.line,found+data.length)))}});on(div,"compositionupdate",function(e){input.composing.data=e.data});on(div,"compositionend",function(e){var ours=input.composing;if(ours){e.data==ours.startData||/\u200b/.test(e.data)||(ours.data=e.data);setTimeout(function(){ours.handled||input.applyComposition(ours);input.composing==ours&&(input.composing=null)},50)}});on(div,"touchstart",function(){input.forceCompositionEnd()});on(div,"input",function(){input.composing||(cm.isReadOnly()||!input.pollContent())&&runInOp(input.cm,function(){regChange(cm)})});on(div,"copy",onCopyCut);on(div,"cut",onCopyCut)},prepareSelection:function(){var result=prepareSelection(this.cm,!1);result.focus=this.cm.state.focused;return result},showSelection:function(info){if(info&&this.cm.display.view.length){info.focus&&this.showPrimarySelection();this.showMultipleSelections(info)}},showPrimarySelection:function(){var sel=window.getSelection(),prim=this.cm.doc.sel.primary(),curAnchor=domToPos(this.cm,sel.anchorNode,sel.anchorOffset),curFocus=domToPos(this.cm,sel.focusNode,sel.focusOffset);if(!curAnchor||curAnchor.bad||!curFocus||curFocus.bad||0!=cmp(minPos(curAnchor,curFocus),prim.from())||0!=cmp(maxPos(curAnchor,curFocus),prim.to())){var start=posToDOM(this.cm,prim.from()),end=posToDOM(this.cm,prim.to());if(start||end){var view=this.cm.display.view,old=sel.rangeCount&&sel.getRangeAt(0);if(start){if(!end){var measure=view[view.length-1].measure,map=measure.maps?measure.maps[measure.maps.length-1]:measure.map;end={node:map[map.length-1],offset:map[map.length-2]-map[map.length-3]}}}else start={node:view[0].measure.map[2],offset:0};try{var rng=range(start.node,start.offset,end.offset,end.node)}catch(e){}if(rng){if(!gecko&&this.cm.state.focused){sel.collapse(start.node,start.offset);rng.collapsed||sel.addRange(rng)}else{sel.removeAllRanges();sel.addRange(rng)}old&&null==sel.anchorNode?sel.addRange(old):gecko&&this.startGracePeriod()}this.rememberSelection()}}},startGracePeriod:function(){var input=this;clearTimeout(this.gracePeriod);this.gracePeriod=setTimeout(function(){input.gracePeriod=!1;input.selectionChanged()&&input.cm.operation(function(){input.cm.curOp.selectionChanged=!0})},20)},showMultipleSelections:function(info){removeChildrenAndAdd(this.cm.display.cursorDiv,info.cursors);removeChildrenAndAdd(this.cm.display.selectionDiv,info.selection)},rememberSelection:function(){var sel=window.getSelection();this.lastAnchorNode=sel.anchorNode;this.lastAnchorOffset=sel.anchorOffset;this.lastFocusNode=sel.focusNode;this.lastFocusOffset=sel.focusOffset},selectionInEditor:function(){var sel=window.getSelection();if(!sel.rangeCount)return!1;var node=sel.getRangeAt(0).commonAncestorContainer;return contains(this.div,node)},focus:function(){"nocursor"!=this.cm.options.readOnly&&this.div.focus()},blur:function(){this.div.blur()},getField:function(){return this.div},supportsTouch:function(){return!0},receivedFocus:function(){function poll(){if(input.cm.state.focused){input.pollSelection();input.polling.set(input.cm.options.pollInterval,poll)}}var input=this;this.selectionInEditor()?this.pollSelection():runInOp(this.cm,function(){input.cm.curOp.selectionChanged=!0});this.polling.set(this.cm.options.pollInterval,poll)},selectionChanged:function(){var sel=window.getSelection();return sel.anchorNode!=this.lastAnchorNode||sel.anchorOffset!=this.lastAnchorOffset||sel.focusNode!=this.lastFocusNode||sel.focusOffset!=this.lastFocusOffset},pollSelection:function(){if(!this.composing&&!this.gracePeriod&&this.selectionChanged()){var sel=window.getSelection(),cm=this.cm;this.rememberSelection();var anchor=domToPos(cm,sel.anchorNode,sel.anchorOffset),head=domToPos(cm,sel.focusNode,sel.focusOffset);anchor&&head&&runInOp(cm,function(){setSelection(cm.doc,simpleSelection(anchor,head),sel_dontScroll);(anchor.bad||head.bad)&&(cm.curOp.selectionChanged=!0)})}},pollContent:function(){var cm=this.cm,display=cm.display,sel=cm.doc.sel.primary(),from=sel.from(),to=sel.to();if(from.line<display.viewFrom||to.line>display.viewTo-1)return!1;var fromIndex;if(from.line==display.viewFrom||0==(fromIndex=findViewIndex(cm,from.line)))var fromLine=lineNo(display.view[0].line),fromNode=display.view[0].node;else var fromLine=lineNo(display.view[fromIndex].line),fromNode=display.view[fromIndex-1].node.nextSibling;var toIndex=findViewIndex(cm,to.line);if(toIndex==display.view.length-1)var toLine=display.viewTo-1,toNode=display.lineDiv.lastChild;else var toLine=lineNo(display.view[toIndex+1].line)-1,toNode=display.view[toIndex+1].node.previousSibling;for(var newText=cm.doc.splitLines(domTextBetween(cm,fromNode,toNode,fromLine,toLine)),oldText=getBetween(cm.doc,Pos(fromLine,0),Pos(toLine,getLine(cm.doc,toLine).text.length));newText.length>1&&oldText.length>1;)if(lst(newText)==lst(oldText)){newText.pop();oldText.pop();toLine--}else{if(newText[0]!=oldText[0])break;newText.shift();oldText.shift();fromLine++}for(var cutFront=0,cutEnd=0,newTop=newText[0],oldTop=oldText[0],maxCutFront=Math.min(newTop.length,oldTop.length);maxCutFront>cutFront&&newTop.charCodeAt(cutFront)==oldTop.charCodeAt(cutFront);)++cutFront;for(var newBot=lst(newText),oldBot=lst(oldText),maxCutEnd=Math.min(newBot.length-(1==newText.length?cutFront:0),oldBot.length-(1==oldText.length?cutFront:0));maxCutEnd>cutEnd&&newBot.charCodeAt(newBot.length-cutEnd-1)==oldBot.charCodeAt(oldBot.length-cutEnd-1);)++cutEnd;newText[newText.length-1]=newBot.slice(0,newBot.length-cutEnd);newText[0]=newText[0].slice(cutFront);var chFrom=Pos(fromLine,cutFront),chTo=Pos(toLine,oldText.length?lst(oldText).length-cutEnd:0);if(newText.length>1||newText[0]||cmp(chFrom,chTo)){replaceRange(cm.doc,newText,chFrom,chTo,"+input");return!0}},ensurePolled:function(){this.forceCompositionEnd()},reset:function(){this.forceCompositionEnd()},forceCompositionEnd:function(){if(this.composing&&!this.composing.handled){this.applyComposition(this.composing);this.composing.handled=!0;this.div.blur();this.div.focus()}},applyComposition:function(composing){this.cm.isReadOnly()?operation(this.cm,regChange)(this.cm):composing.data&&composing.data!=composing.startData&&operation(this.cm,applyTextInput)(this.cm,composing.data,0,composing.sel)},setUneditable:function(node){node.contentEditable="false"},onKeyPress:function(e){e.preventDefault();this.cm.isReadOnly()||operation(this.cm,applyTextInput)(this.cm,String.fromCharCode(null==e.charCode?e.keyCode:e.charCode),0)},readOnlyChanged:function(val){this.div.contentEditable=String("nocursor"!=val)},onContextMenu:nothing,resetPosition:nothing,needsContentAttribute:!0
6
- },ContentEditableInput.prototype);CodeMirror.inputStyles={textarea:TextareaInput,contenteditable:ContentEditableInput};Selection.prototype={primary:function(){return this.ranges[this.primIndex]},equals:function(other){if(other==this)return!0;if(other.primIndex!=this.primIndex||other.ranges.length!=this.ranges.length)return!1;for(var i=0;i<this.ranges.length;i++){var here=this.ranges[i],there=other.ranges[i];if(0!=cmp(here.anchor,there.anchor)||0!=cmp(here.head,there.head))return!1}return!0},deepCopy:function(){for(var out=[],i=0;i<this.ranges.length;i++)out[i]=new Range(copyPos(this.ranges[i].anchor),copyPos(this.ranges[i].head));return new Selection(out,this.primIndex)},somethingSelected:function(){for(var i=0;i<this.ranges.length;i++)if(!this.ranges[i].empty())return!0;return!1},contains:function(pos,end){end||(end=pos);for(var i=0;i<this.ranges.length;i++){var range=this.ranges[i];if(cmp(end,range.from())>=0&&cmp(pos,range.to())<=0)return i}return-1}};Range.prototype={from:function(){return minPos(this.anchor,this.head)},to:function(){return maxPos(this.anchor,this.head)},empty:function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch}};var measureText,lastClick,lastDoubleClick,nullRect={left:0,right:0,top:0,bottom:0},operationGroup=null,nextOpId=0,lastDrop=0,wheelSamples=0,wheelPixelsPerUnit=null;ie?wheelPixelsPerUnit=-.53:gecko?wheelPixelsPerUnit=15:chrome?wheelPixelsPerUnit=-.7:safari&&(wheelPixelsPerUnit=-1/3);var wheelEventDelta=function(e){var dx=e.wheelDeltaX,dy=e.wheelDeltaY;null==dx&&e.detail&&e.axis==e.HORIZONTAL_AXIS&&(dx=e.detail);null==dy&&e.detail&&e.axis==e.VERTICAL_AXIS?dy=e.detail:null==dy&&(dy=e.wheelDelta);return{x:dx,y:dy}};CodeMirror.wheelEventPixels=function(e){var delta=wheelEventDelta(e);delta.x*=wheelPixelsPerUnit;delta.y*=wheelPixelsPerUnit;return delta};var stopSeq=new Delayed,lastStoppedKey=null,changeEnd=CodeMirror.changeEnd=function(change){return change.text?Pos(change.from.line+change.text.length-1,lst(change.text).length+(1==change.text.length?change.from.ch:0)):change.to};CodeMirror.prototype={constructor:CodeMirror,focus:function(){window.focus();this.display.input.focus()},setOption:function(option,value){var options=this.options,old=options[option];if(options[option]!=value||"mode"==option){options[option]=value;optionHandlers.hasOwnProperty(option)&&operation(this,optionHandlers[option])(this,value,old)}},getOption:function(option){return this.options[option]},getDoc:function(){return this.doc},addKeyMap:function(map,bottom){this.state.keyMaps[bottom?"push":"unshift"](getKeyMap(map))},removeKeyMap:function(map){for(var maps=this.state.keyMaps,i=0;i<maps.length;++i)if(maps[i]==map||maps[i].name==map){maps.splice(i,1);return!0}},addOverlay:methodOp(function(spec,options){var mode=spec.token?spec:CodeMirror.getMode(this.options,spec);if(mode.startState)throw new Error("Overlays may not be stateful.");this.state.overlays.push({mode:mode,modeSpec:spec,opaque:options&&options.opaque});this.state.modeGen++;regChange(this)}),removeOverlay:methodOp(function(spec){for(var overlays=this.state.overlays,i=0;i<overlays.length;++i){var cur=overlays[i].modeSpec;if(cur==spec||"string"==typeof spec&&cur.name==spec){overlays.splice(i,1);this.state.modeGen++;regChange(this);return}}}),indentLine:methodOp(function(n,dir,aggressive){"string"!=typeof dir&&"number"!=typeof dir&&(dir=null==dir?this.options.smartIndent?"smart":"prev":dir?"add":"subtract");isLine(this.doc,n)&&indentLine(this,n,dir,aggressive)}),indentSelection:methodOp(function(how){for(var ranges=this.doc.sel.ranges,end=-1,i=0;i<ranges.length;i++){var range=ranges[i];if(range.empty()){if(range.head.line>end){indentLine(this,range.head.line,how,!0);end=range.head.line;i==this.doc.sel.primIndex&&ensureCursorVisible(this)}}else{var from=range.from(),to=range.to(),start=Math.max(end,from.line);end=Math.min(this.lastLine(),to.line-(to.ch?0:1))+1;for(var j=start;end>j;++j)indentLine(this,j,how);var newRanges=this.doc.sel.ranges;0==from.ch&&ranges.length==newRanges.length&&newRanges[i].from().ch>0&&replaceOneSelection(this.doc,i,new Range(from,newRanges[i].to()),sel_dontScroll)}}}),getTokenAt:function(pos,precise){return takeToken(this,pos,precise)},getLineTokens:function(line,precise){return takeToken(this,Pos(line),precise,!0)},getTokenTypeAt:function(pos){pos=clipPos(this.doc,pos);var type,styles=getLineStyles(this,getLine(this.doc,pos.line)),before=0,after=(styles.length-1)/2,ch=pos.ch;if(0==ch)type=styles[2];else for(;;){var mid=before+after>>1;if((mid?styles[2*mid-1]:0)>=ch)after=mid;else{if(!(styles[2*mid+1]<ch)){type=styles[2*mid+2];break}before=mid+1}}var cut=type?type.indexOf("cm-overlay "):-1;return 0>cut?type:0==cut?null:type.slice(0,cut-1)},getModeAt:function(pos){var mode=this.doc.mode;return mode.innerMode?CodeMirror.innerMode(mode,this.getTokenAt(pos).state).mode:mode},getHelper:function(pos,type){return this.getHelpers(pos,type)[0]},getHelpers:function(pos,type){var found=[];if(!helpers.hasOwnProperty(type))return found;var help=helpers[type],mode=this.getModeAt(pos);if("string"==typeof mode[type])help[mode[type]]&&found.push(help[mode[type]]);else if(mode[type])for(var i=0;i<mode[type].length;i++){var val=help[mode[type][i]];val&&found.push(val)}else mode.helperType&&help[mode.helperType]?found.push(help[mode.helperType]):help[mode.name]&&found.push(help[mode.name]);for(var i=0;i<help._global.length;i++){var cur=help._global[i];cur.pred(mode,this)&&-1==indexOf(found,cur.val)&&found.push(cur.val)}return found},getStateAfter:function(line,precise){var doc=this.doc;line=clipLine(doc,null==line?doc.first+doc.size-1:line);return getStateBefore(this,line+1,precise)},cursorCoords:function(start,mode){var pos,range=this.doc.sel.primary();pos=null==start?range.head:"object"==typeof start?clipPos(this.doc,start):start?range.from():range.to();return cursorCoords(this,pos,mode||"page")},charCoords:function(pos,mode){return charCoords(this,clipPos(this.doc,pos),mode||"page")},coordsChar:function(coords,mode){coords=fromCoordSystem(this,coords,mode||"page");return coordsChar(this,coords.left,coords.top)},lineAtHeight:function(height,mode){height=fromCoordSystem(this,{top:height,left:0},mode||"page").top;return lineAtHeight(this.doc,height+this.display.viewOffset)},heightAtLine:function(line,mode){var lineObj,end=!1;if("number"==typeof line){var last=this.doc.first+this.doc.size-1;if(line<this.doc.first)line=this.doc.first;else if(line>last){line=last;end=!0}lineObj=getLine(this.doc,line)}else lineObj=line;return intoCoordSystem(this,lineObj,{top:0,left:0},mode||"page").top+(end?this.doc.height-heightAtLine(lineObj):0)},defaultTextHeight:function(){return textHeight(this.display)},defaultCharWidth:function(){return charWidth(this.display)},setGutterMarker:methodOp(function(line,gutterID,value){return changeLine(this.doc,line,"gutter",function(line){var markers=line.gutterMarkers||(line.gutterMarkers={});markers[gutterID]=value;!value&&isEmpty(markers)&&(line.gutterMarkers=null);return!0})}),clearGutter:methodOp(function(gutterID){var cm=this,doc=cm.doc,i=doc.first;doc.iter(function(line){if(line.gutterMarkers&&line.gutterMarkers[gutterID]){line.gutterMarkers[gutterID]=null;regLineChange(cm,i,"gutter");isEmpty(line.gutterMarkers)&&(line.gutterMarkers=null)}++i})}),lineInfo:function(line){if("number"==typeof line){if(!isLine(this.doc,line))return null;var n=line;line=getLine(this.doc,line);if(!line)return null}else{var n=lineNo(line);if(null==n)return null}return{line:n,handle:line,text:line.text,gutterMarkers:line.gutterMarkers,textClass:line.textClass,bgClass:line.bgClass,wrapClass:line.wrapClass,widgets:line.widgets}},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(pos,node,scroll,vert,horiz){var display=this.display;pos=cursorCoords(this,clipPos(this.doc,pos));var top=pos.bottom,left=pos.left;node.style.position="absolute";node.setAttribute("cm-ignore-events","true");this.display.input.setUneditable(node);display.sizer.appendChild(node);if("over"==vert)top=pos.top;else if("above"==vert||"near"==vert){var vspace=Math.max(display.wrapper.clientHeight,this.doc.height),hspace=Math.max(display.sizer.clientWidth,display.lineSpace.clientWidth);("above"==vert||pos.bottom+node.offsetHeight>vspace)&&pos.top>node.offsetHeight?top=pos.top-node.offsetHeight:pos.bottom+node.offsetHeight<=vspace&&(top=pos.bottom);left+node.offsetWidth>hspace&&(left=hspace-node.offsetWidth)}node.style.top=top+"px";node.style.left=node.style.right="";if("right"==horiz){left=display.sizer.clientWidth-node.offsetWidth;node.style.right="0px"}else{"left"==horiz?left=0:"middle"==horiz&&(left=(display.sizer.clientWidth-node.offsetWidth)/2);node.style.left=left+"px"}scroll&&scrollIntoView(this,left,top,left+node.offsetWidth,top+node.offsetHeight)},triggerOnKeyDown:methodOp(onKeyDown),triggerOnKeyPress:methodOp(onKeyPress),triggerOnKeyUp:onKeyUp,execCommand:function(cmd){return commands.hasOwnProperty(cmd)?commands[cmd].call(null,this):void 0},triggerElectric:methodOp(function(text){triggerElectric(this,text)}),findPosH:function(from,amount,unit,visually){var dir=1;if(0>amount){dir=-1;amount=-amount}for(var i=0,cur=clipPos(this.doc,from);amount>i;++i){cur=findPosH(this.doc,cur,dir,unit,visually);if(cur.hitSide)break}return cur},moveH:methodOp(function(dir,unit){var cm=this;cm.extendSelectionsBy(function(range){return cm.display.shift||cm.doc.extend||range.empty()?findPosH(cm.doc,range.head,dir,unit,cm.options.rtlMoveVisually):0>dir?range.from():range.to()},sel_move)}),deleteH:methodOp(function(dir,unit){var sel=this.doc.sel,doc=this.doc;sel.somethingSelected()?doc.replaceSelection("",null,"+delete"):deleteNearSelection(this,function(range){var other=findPosH(doc,range.head,dir,unit,!1);return 0>dir?{from:other,to:range.head}:{from:range.head,to:other}})}),findPosV:function(from,amount,unit,goalColumn){var dir=1,x=goalColumn;if(0>amount){dir=-1;amount=-amount}for(var i=0,cur=clipPos(this.doc,from);amount>i;++i){var coords=cursorCoords(this,cur,"div");null==x?x=coords.left:coords.left=x;cur=findPosV(this,coords,dir,unit);if(cur.hitSide)break}return cur},moveV:methodOp(function(dir,unit){var cm=this,doc=this.doc,goals=[],collapse=!cm.display.shift&&!doc.extend&&doc.sel.somethingSelected();doc.extendSelectionsBy(function(range){if(collapse)return 0>dir?range.from():range.to();var headPos=cursorCoords(cm,range.head,"div");null!=range.goalColumn&&(headPos.left=range.goalColumn);goals.push(headPos.left);var pos=findPosV(cm,headPos,dir,unit);"page"==unit&&range==doc.sel.primary()&&addToScrollPos(cm,null,charCoords(cm,pos,"div").top-headPos.top);return pos},sel_move);if(goals.length)for(var i=0;i<doc.sel.ranges.length;i++)doc.sel.ranges[i].goalColumn=goals[i]}),findWordAt:function(pos){var doc=this.doc,line=getLine(doc,pos.line).text,start=pos.ch,end=pos.ch;if(line){var helper=this.getHelper(pos,"wordChars");(pos.xRel<0||end==line.length)&&start?--start:++end;for(var startChar=line.charAt(start),check=isWordChar(startChar,helper)?function(ch){return isWordChar(ch,helper)}:/\s/.test(startChar)?function(ch){return/\s/.test(ch)}:function(ch){return!/\s/.test(ch)&&!isWordChar(ch)};start>0&&check(line.charAt(start-1));)--start;for(;end<line.length&&check(line.charAt(end));)++end}return new Range(Pos(pos.line,start),Pos(pos.line,end))},toggleOverwrite:function(value){if(null==value||value!=this.state.overwrite){(this.state.overwrite=!this.state.overwrite)?addClass(this.display.cursorDiv,"CodeMirror-overwrite"):rmClass(this.display.cursorDiv,"CodeMirror-overwrite");signal(this,"overwriteToggle",this,this.state.overwrite)}},hasFocus:function(){return this.display.input.getField()==activeElt()},isReadOnly:function(){return!(!this.options.readOnly&&!this.doc.cantEdit)},scrollTo:methodOp(function(x,y){(null!=x||null!=y)&&resolveScrollToPos(this);null!=x&&(this.curOp.scrollLeft=x);null!=y&&(this.curOp.scrollTop=y)}),getScrollInfo:function(){var scroller=this.display.scroller;return{left:scroller.scrollLeft,top:scroller.scrollTop,height:scroller.scrollHeight-scrollGap(this)-this.display.barHeight,width:scroller.scrollWidth-scrollGap(this)-this.display.barWidth,clientHeight:displayHeight(this),clientWidth:displayWidth(this)}},scrollIntoView:methodOp(function(range,margin){if(null==range){range={from:this.doc.sel.primary().head,to:null};null==margin&&(margin=this.options.cursorScrollMargin)}else"number"==typeof range?range={from:Pos(range,0),to:null}:null==range.from&&(range={from:range,to:null});range.to||(range.to=range.from);range.margin=margin||0;if(null!=range.from.line){resolveScrollToPos(this);this.curOp.scrollToPos=range}else{var sPos=calculateScrollPos(this,Math.min(range.from.left,range.to.left),Math.min(range.from.top,range.to.top)-range.margin,Math.max(range.from.right,range.to.right),Math.max(range.from.bottom,range.to.bottom)+range.margin);this.scrollTo(sPos.scrollLeft,sPos.scrollTop)}}),setSize:methodOp(function(width,height){function interpret(val){return"number"==typeof val||/^\d+$/.test(String(val))?val+"px":val}var cm=this;null!=width&&(cm.display.wrapper.style.width=interpret(width));null!=height&&(cm.display.wrapper.style.height=interpret(height));cm.options.lineWrapping&&clearLineMeasurementCache(this);var lineNo=cm.display.viewFrom;cm.doc.iter(lineNo,cm.display.viewTo,function(line){if(line.widgets)for(var i=0;i<line.widgets.length;i++)if(line.widgets[i].noHScroll){regLineChange(cm,lineNo,"widget");break}++lineNo});cm.curOp.forceUpdate=!0;signal(cm,"refresh",this)}),operation:function(f){return runInOp(this,f)},refresh:methodOp(function(){var oldHeight=this.display.cachedTextHeight;regChange(this);this.curOp.forceUpdate=!0;clearCaches(this);this.scrollTo(this.doc.scrollLeft,this.doc.scrollTop);updateGutterSpace(this);(null==oldHeight||Math.abs(oldHeight-textHeight(this.display))>.5)&&estimateLineHeights(this);signal(this,"refresh",this)}),swapDoc:methodOp(function(doc){var old=this.doc;old.cm=null;attachDoc(this,doc);clearCaches(this);this.display.input.reset();this.scrollTo(doc.scrollLeft,doc.scrollTop);this.curOp.forceScroll=!0;signalLater(this,"swapDoc",this,old);return old}),getInputField:function(){return this.display.input.getField()},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}};eventMixin(CodeMirror);var defaults=CodeMirror.defaults={},optionHandlers=CodeMirror.optionHandlers={},Init=CodeMirror.Init={toString:function(){return"CodeMirror.Init"}};option("value","",function(cm,val){cm.setValue(val)},!0);option("mode",null,function(cm,val){cm.doc.modeOption=val;loadMode(cm)},!0);option("indentUnit",2,loadMode,!0);option("indentWithTabs",!1);option("smartIndent",!0);option("tabSize",4,function(cm){resetModeState(cm);clearCaches(cm);regChange(cm)},!0);option("lineSeparator",null,function(cm,val){cm.doc.lineSep=val;if(val){var newBreaks=[],lineNo=cm.doc.first;cm.doc.iter(function(line){for(var pos=0;;){var found=line.text.indexOf(val,pos);if(-1==found)break;pos=found+val.length;newBreaks.push(Pos(lineNo,found))}lineNo++});for(var i=newBreaks.length-1;i>=0;i--)replaceRange(cm.doc,val,newBreaks[i],Pos(newBreaks[i].line,newBreaks[i].ch+val.length))}});option("specialChars",/[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g,function(cm,val,old){cm.state.specialChars=new RegExp(val.source+(val.test(" ")?"":"| "),"g");old!=CodeMirror.Init&&cm.refresh()});option("specialCharPlaceholder",defaultSpecialCharPlaceholder,function(cm){cm.refresh()},!0);option("electricChars",!0);option("inputStyle",mobile?"contenteditable":"textarea",function(){throw new Error("inputStyle can not (yet) be changed in a running editor")},!0);option("rtlMoveVisually",!windows);option("wholeLineUpdateBefore",!0);option("theme","default",function(cm){themeChanged(cm);guttersChanged(cm)},!0);option("keyMap","default",function(cm,val,old){var next=getKeyMap(val),prev=old!=CodeMirror.Init&&getKeyMap(old);prev&&prev.detach&&prev.detach(cm,next);next.attach&&next.attach(cm,prev||null)});option("extraKeys",null);option("lineWrapping",!1,wrappingChanged,!0);option("gutters",[],function(cm){setGuttersForLineNumbers(cm.options);guttersChanged(cm)},!0);option("fixedGutter",!0,function(cm,val){cm.display.gutters.style.left=val?compensateForHScroll(cm.display)+"px":"0";cm.refresh()},!0);option("coverGutterNextToScrollbar",!1,function(cm){updateScrollbars(cm)},!0);option("scrollbarStyle","native",function(cm){initScrollbars(cm);updateScrollbars(cm);cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft)},!0);option("lineNumbers",!1,function(cm){setGuttersForLineNumbers(cm.options);guttersChanged(cm)},!0);option("firstLineNumber",1,guttersChanged,!0);option("lineNumberFormatter",function(integer){return integer},guttersChanged,!0);option("showCursorWhenSelecting",!1,updateSelection,!0);option("resetSelectionOnContextMenu",!0);option("lineWiseCopyCut",!0);option("readOnly",!1,function(cm,val){if("nocursor"==val){onBlur(cm);cm.display.input.blur();cm.display.disabled=!0}else cm.display.disabled=!1;cm.display.input.readOnlyChanged(val)});option("disableInput",!1,function(cm,val){val||cm.display.input.reset()},!0);option("dragDrop",!0,dragDropChanged);option("allowDropFileTypes",null);option("cursorBlinkRate",530);option("cursorScrollMargin",0);option("cursorHeight",1,updateSelection,!0);option("singleCursorHeightPerLine",!0,updateSelection,!0);option("workTime",100);option("workDelay",100);option("flattenSpans",!0,resetModeState,!0);option("addModeClass",!1,resetModeState,!0);option("pollInterval",100);option("undoDepth",200,function(cm,val){cm.doc.history.undoDepth=val});option("historyEventDelay",1250);option("viewportMargin",10,function(cm){cm.refresh()},!0);option("maxHighlightLength",1e4,resetModeState,!0);option("moveInputWithCursor",!0,function(cm,val){val||cm.display.input.resetPosition()});option("tabindex",null,function(cm,val){cm.display.input.getField().tabIndex=val||""});option("autofocus",null);var modes=CodeMirror.modes={},mimeModes=CodeMirror.mimeModes={};CodeMirror.defineMode=function(name,mode){CodeMirror.defaults.mode||"null"==name||(CodeMirror.defaults.mode=name);arguments.length>2&&(mode.dependencies=Array.prototype.slice.call(arguments,2));modes[name]=mode};CodeMirror.defineMIME=function(mime,spec){mimeModes[mime]=spec};CodeMirror.resolveMode=function(spec){if("string"==typeof spec&&mimeModes.hasOwnProperty(spec))spec=mimeModes[spec];else if(spec&&"string"==typeof spec.name&&mimeModes.hasOwnProperty(spec.name)){var found=mimeModes[spec.name];"string"==typeof found&&(found={name:found});spec=createObj(found,spec);spec.name=found.name}else if("string"==typeof spec&&/^[\w\-]+\/[\w\-]+\+xml$/.test(spec))return CodeMirror.resolveMode("application/xml");return"string"==typeof spec?{name:spec}:spec||{name:"null"}};CodeMirror.getMode=function(options,spec){var spec=CodeMirror.resolveMode(spec),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.hasOwnProperty(prop)&&(modeObj["_"+prop]=modeObj[prop]);modeObj[prop]=exts[prop]}}modeObj.name=spec.name;spec.helperType&&(modeObj.helperType=spec.helperType);if(spec.modeProps)for(var prop in spec.modeProps)modeObj[prop]=spec.modeProps[prop];return modeObj};CodeMirror.defineMode("null",function(){return{token:function(stream){stream.skipToEnd()}}});CodeMirror.defineMIME("text/plain","null");var modeExtensions=CodeMirror.modeExtensions={};CodeMirror.extendMode=function(mode,properties){var exts=modeExtensions.hasOwnProperty(mode)?modeExtensions[mode]:modeExtensions[mode]={};copyObj(properties,exts)};CodeMirror.defineExtension=function(name,func){CodeMirror.prototype[name]=func};CodeMirror.defineDocExtension=function(name,func){Doc.prototype[name]=func};CodeMirror.defineOption=option;var initHooks=[];CodeMirror.defineInitHook=function(f){initHooks.push(f)};var helpers=CodeMirror.helpers={};CodeMirror.registerHelper=function(type,name,value){helpers.hasOwnProperty(type)||(helpers[type]=CodeMirror[type]={_global:[]});helpers[type][name]=value};CodeMirror.registerGlobalHelper=function(type,name,predicate,value){CodeMirror.registerHelper(type,name,value);helpers[type]._global.push({pred:predicate,val:value})};var copyState=CodeMirror.copyState=function(mode,state){if(state===!0)return state;if(mode.copyState)return mode.copyState(state);var nstate={};for(var n in state){var val=state[n];val instanceof Array&&(val=val.concat([]));nstate[n]=val}return nstate},startState=CodeMirror.startState=function(mode,a1,a2){return mode.startState?mode.startState(a1,a2):!0};CodeMirror.innerMode=function(mode,state){for(;mode.innerMode;){var info=mode.innerMode(state);if(!info||info.mode==mode)break;state=info.state;mode=info.mode}return info||{mode:mode,state:state}};var commands=CodeMirror.commands={selectAll:function(cm){cm.setSelection(Pos(cm.firstLine(),0),Pos(cm.lastLine()),sel_dontScroll)},singleSelection:function(cm){cm.setSelection(cm.getCursor("anchor"),cm.getCursor("head"),sel_dontScroll)},killLine:function(cm){deleteNearSelection(cm,function(range){if(range.empty()){var len=getLine(cm.doc,range.head.line).text.length;return range.head.ch==len&&range.head.line<cm.lastLine()?{from:range.head,to:Pos(range.head.line+1,0)}:{from:range.head,to:Pos(range.head.line,len)}}return{from:range.from(),to:range.to()}})},deleteLine:function(cm){deleteNearSelection(cm,function(range){return{from:Pos(range.from().line,0),to:clipPos(cm.doc,Pos(range.to().line+1,0))}})},delLineLeft:function(cm){deleteNearSelection(cm,function(range){return{from:Pos(range.from().line,0),to:range.from()}})},delWrappedLineLeft:function(cm){deleteNearSelection(cm,function(range){var top=cm.charCoords(range.head,"div").top+5,leftPos=cm.coordsChar({left:0,top:top},"div");return{from:leftPos,to:range.from()}})},delWrappedLineRight:function(cm){deleteNearSelection(cm,function(range){var top=cm.charCoords(range.head,"div").top+5,rightPos=cm.coordsChar({left:cm.display.lineDiv.offsetWidth+100,top:top},"div");return{from:range.from(),to:rightPos}})},undo:function(cm){cm.undo()},redo:function(cm){cm.redo()},undoSelection:function(cm){cm.undoSelection()},redoSelection:function(cm){cm.redoSelection()},goDocStart:function(cm){cm.extendSelection(Pos(cm.firstLine(),0))},goDocEnd:function(cm){cm.extendSelection(Pos(cm.lastLine()))},goLineStart:function(cm){cm.extendSelectionsBy(function(range){return lineStart(cm,range.head.line)},{origin:"+move",bias:1})},goLineStartSmart:function(cm){cm.extendSelectionsBy(function(range){return lineStartSmart(cm,range.head)},{origin:"+move",bias:1})},goLineEnd:function(cm){cm.extendSelectionsBy(function(range){return lineEnd(cm,range.head.line)},{origin:"+move",bias:-1})},goLineRight:function(cm){cm.extendSelectionsBy(function(range){var top=cm.charCoords(range.head,"div").top+5;return cm.coordsChar({left:cm.display.lineDiv.offsetWidth+100,top:top},"div")},sel_move)},goLineLeft:function(cm){cm.extendSelectionsBy(function(range){var top=cm.charCoords(range.head,"div").top+5;return cm.coordsChar({left:0,top:top},"div")},sel_move)},goLineLeftSmart:function(cm){cm.extendSelectionsBy(function(range){var top=cm.charCoords(range.head,"div").top+5,pos=cm.coordsChar({left:0,top:top},"div");return pos.ch<cm.getLine(pos.line).search(/\S/)?lineStartSmart(cm,range.head):pos},sel_move)},goLineUp:function(cm){cm.moveV(-1,"line")},goLineDown:function(cm){cm.moveV(1,"line")},goPageUp:function(cm){cm.moveV(-1,"page")},goPageDown:function(cm){cm.moveV(1,"page")},goCharLeft:function(cm){cm.moveH(-1,"char")},goCharRight:function(cm){cm.moveH(1,"char")},goColumnLeft:function(cm){cm.moveH(-1,"column")},goColumnRight:function(cm){cm.moveH(1,"column")},goWordLeft:function(cm){cm.moveH(-1,"word")},goGroupRight:function(cm){cm.moveH(1,"group")},goGroupLeft:function(cm){cm.moveH(-1,"group")},goWordRight:function(cm){cm.moveH(1,"word")},delCharBefore:function(cm){cm.deleteH(-1,"char")},delCharAfter:function(cm){cm.deleteH(1,"char")},delWordBefore:function(cm){cm.deleteH(-1,"word")},delWordAfter:function(cm){cm.deleteH(1,"word")},delGroupBefore:function(cm){cm.deleteH(-1,"group")},delGroupAfter:function(cm){cm.deleteH(1,"group")},indentAuto:function(cm){cm.indentSelection("smart")},indentMore:function(cm){cm.indentSelection("add")},indentLess:function(cm){cm.indentSelection("subtract")},insertTab:function(cm){cm.replaceSelection(" ")},insertSoftTab:function(cm){for(var spaces=[],ranges=cm.listSelections(),tabSize=cm.options.tabSize,i=0;i<ranges.length;i++){var pos=ranges[i].from(),col=countColumn(cm.getLine(pos.line),pos.ch,tabSize);spaces.push(new Array(tabSize-col%tabSize+1).join(" "))}cm.replaceSelections(spaces)},defaultTab:function(cm){cm.somethingSelected()?cm.indentSelection("add"):cm.execCommand("insertTab")},transposeChars:function(cm){runInOp(cm,function(){for(var ranges=cm.listSelections(),newSel=[],i=0;i<ranges.length;i++){var cur=ranges[i].head,line=getLine(cm.doc,cur.line).text;if(line){cur.ch==line.length&&(cur=new Pos(cur.line,cur.ch-1));if(cur.ch>0){cur=new Pos(cur.line,cur.ch+1);cm.replaceRange(line.charAt(cur.ch-1)+line.charAt(cur.ch-2),Pos(cur.line,cur.ch-2),cur,"+transpose")}else if(cur.line>cm.doc.first){var prev=getLine(cm.doc,cur.line-1).text;prev&&cm.replaceRange(line.charAt(0)+cm.doc.lineSeparator()+prev.charAt(prev.length-1),Pos(cur.line-1,prev.length-1),Pos(cur.line,1),"+transpose")}}newSel.push(new Range(cur,cur))}cm.setSelections(newSel)})},newlineAndIndent:function(cm){runInOp(cm,function(){for(var len=cm.listSelections().length,i=0;len>i;i++){var range=cm.listSelections()[i];cm.replaceRange(cm.doc.lineSeparator(),range.anchor,range.head,"+input");cm.indentLine(range.from().line+1,null,!0)}ensureCursorVisible(cm)})},toggleOverwrite:function(cm){cm.toggleOverwrite()}},keyMap=CodeMirror.keyMap={};keyMap.basic={Left:"goCharLeft",Right:"goCharRight",Up:"goLineUp",Down:"goLineDown",End:"goLineEnd",Home:"goLineStartSmart",PageUp:"goPageUp",PageDown:"goPageDown",Delete:"delCharAfter",Backspace:"delCharBefore","Shift-Backspace":"delCharBefore",Tab:"defaultTab","Shift-Tab":"indentAuto",Enter:"newlineAndIndent",Insert:"toggleOverwrite",Esc:"singleSelection"};keyMap.pcDefault={"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Up":"goLineUp","Ctrl-Down":"goLineDown","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev","Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection",fallthrough:"basic"};keyMap.emacsy={"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Alt-F":"goWordRight","Alt-B":"goWordLeft","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-D":"delWordAfter","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars"};keyMap.macDefault={"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Home":"goDocStart","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineLeft","Cmd-Right":"goLineRight","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace","Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delWrappedLineLeft","Cmd-Delete":"delWrappedLineRight","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection","Ctrl-Up":"goDocStart","Ctrl-Down":"goDocEnd",fallthrough:["basic","emacsy"]};keyMap["default"]=mac?keyMap.macDefault:keyMap.pcDefault;CodeMirror.normalizeKeyMap=function(keymap){var copy={};for(var keyname in keymap)if(keymap.hasOwnProperty(keyname)){var value=keymap[keyname];if(/^(name|fallthrough|(de|at)tach)$/.test(keyname))continue;if("..."==value){delete keymap[keyname];continue}for(var keys=map(keyname.split(" "),normalizeKeyName),i=0;i<keys.length;i++){var val,name;if(i==keys.length-1){name=keys.join(" ");val=value}else{name=keys.slice(0,i+1).join(" ");val="..."}var prev=copy[name];if(prev){if(prev!=val)throw new Error("Inconsistent bindings for "+name)}else copy[name]=val}delete keymap[keyname]}for(var prop in copy)keymap[prop]=copy[prop];return keymap};var lookupKey=CodeMirror.lookupKey=function(key,map,handle,context){map=getKeyMap(map);var found=map.call?map.call(key,context):map[key];if(found===!1)return"nothing";if("..."===found)return"multi";if(null!=found&&handle(found))return"handled";if(map.fallthrough){if("[object Array]"!=Object.prototype.toString.call(map.fallthrough))return lookupKey(key,map.fallthrough,handle,context);for(var i=0;i<map.fallthrough.length;i++){var result=lookupKey(key,map.fallthrough[i],handle,context);if(result)return result}}},isModifierKey=CodeMirror.isModifierKey=function(value){var name="string"==typeof value?value:keyNames[value.keyCode];return"Ctrl"==name||"Alt"==name||"Shift"==name||"Mod"==name},keyName=CodeMirror.keyName=function(event,noShift){if(presto&&34==event.keyCode&&event["char"])return!1;var base=keyNames[event.keyCode],name=base;if(null==name||event.altGraphKey)return!1;event.altKey&&"Alt"!=base&&(name="Alt-"+name);(flipCtrlCmd?event.metaKey:event.ctrlKey)&&"Ctrl"!=base&&(name="Ctrl-"+name);(flipCtrlCmd?event.ctrlKey:event.metaKey)&&"Cmd"!=base&&(name="Cmd-"+name);!noShift&&event.shiftKey&&"Shift"!=base&&(name="Shift-"+name);return name};CodeMirror.fromTextArea=function(textarea,options){function save(){textarea.value=cm.getValue()}options=options?copyObj(options):{};options.value=textarea.value;!options.tabindex&&textarea.tabIndex&&(options.tabindex=textarea.tabIndex);!options.placeholder&&textarea.placeholder&&(options.placeholder=textarea.placeholder);if(null==options.autofocus){var hasFocus=activeElt();options.autofocus=hasFocus==textarea||null!=textarea.getAttribute("autofocus")&&hasFocus==document.body}if(textarea.form){on(textarea.form,"submit",save);if(!options.leaveSubmitMethodAlone){var form=textarea.form,realSubmit=form.submit;try{var wrappedSubmit=form.submit=function(){save();form.submit=realSubmit;form.submit();form.submit=wrappedSubmit}}catch(e){}}}options.finishInit=function(cm){cm.save=save;cm.getTextArea=function(){return textarea};cm.toTextArea=function(){cm.toTextArea=isNaN;save();textarea.parentNode.removeChild(cm.getWrapperElement());textarea.style.display="";if(textarea.form){off(textarea.form,"submit",save);"function"==typeof textarea.form.submit&&(textarea.form.submit=realSubmit)}}};textarea.style.display="none";var cm=CodeMirror(function(node){textarea.parentNode.insertBefore(node,textarea.nextSibling)},options);return cm};var StringStream=CodeMirror.StringStream=function(string,tabSize){this.pos=this.start=0;this.string=string;this.tabSize=tabSize||8;this.lastColumnPos=this.lastColumnValue=0;this.lineStart=0};StringStream.prototype={eol:function(){return this.pos>=this.string.length},sol:function(){return this.pos==this.lineStart},peek:function(){return this.string.charAt(this.pos)||void 0},next:function(){return this.pos<this.string.length?this.string.charAt(this.pos++):void 0},eat:function(match){var ch=this.string.charAt(this.pos);if("string"==typeof match)var ok=ch==match;else var ok=ch&&(match.test?match.test(ch):match(ch));if(ok){++this.pos;return ch}},eatWhile:function(match){
7
- for(var start=this.pos;this.eat(match););return this.pos>start},eatSpace:function(){for(var start=this.pos;/[\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!0}},backUp:function(n){this.pos-=n},column:function(){if(this.lastColumnPos<this.start){this.lastColumnValue=countColumn(this.string,this.start,this.tabSize,this.lastColumnPos,this.lastColumnValue);this.lastColumnPos=this.start}return this.lastColumnValue-(this.lineStart?countColumn(this.string,this.lineStart,this.tabSize):0)},indentation:function(){return countColumn(this.string,null,this.tabSize)-(this.lineStart?countColumn(this.string,this.lineStart,this.tabSize):0)},match:function(pattern,consume,caseInsensitive){if("string"!=typeof pattern){var match=this.string.slice(this.pos).match(pattern);if(match&&match.index>0)return null;match&&consume!==!1&&(this.pos+=match[0].length);return match}var cased=function(str){return caseInsensitive?str.toLowerCase():str},substr=this.string.substr(this.pos,pattern.length);if(cased(substr)==cased(pattern)){consume!==!1&&(this.pos+=pattern.length);return!0}},current:function(){return this.string.slice(this.start,this.pos)},hideFirstChars:function(n,inner){this.lineStart+=n;try{return inner()}finally{this.lineStart-=n}}};var nextMarkerId=0,TextMarker=CodeMirror.TextMarker=function(doc,type){this.lines=[];this.type=type;this.doc=doc;this.id=++nextMarkerId};eventMixin(TextMarker);TextMarker.prototype.clear=function(){if(!this.explicitlyCleared){var cm=this.doc.cm,withOp=cm&&!cm.curOp;withOp&&startOperation(cm);if(hasHandler(this,"clear")){var found=this.find();found&&signalLater(this,"clear",found.from,found.to)}for(var min=null,max=null,i=0;i<this.lines.length;++i){var line=this.lines[i],span=getMarkedSpanFor(line.markedSpans,this);if(cm&&!this.collapsed)regLineChange(cm,lineNo(line),"text");else if(cm){null!=span.to&&(max=lineNo(line));null!=span.from&&(min=lineNo(line))}line.markedSpans=removeMarkedSpan(line.markedSpans,span);null==span.from&&this.collapsed&&!lineIsHidden(this.doc,line)&&cm&&updateLineHeight(line,textHeight(cm.display))}if(cm&&this.collapsed&&!cm.options.lineWrapping)for(var i=0;i<this.lines.length;++i){var visual=visualLine(this.lines[i]),len=lineLength(visual);if(len>cm.display.maxLineLength){cm.display.maxLine=visual;cm.display.maxLineLength=len;cm.display.maxLineChanged=!0}}null!=min&&cm&&this.collapsed&&regChange(cm,min,max+1);this.lines.length=0;this.explicitlyCleared=!0;if(this.atomic&&this.doc.cantEdit){this.doc.cantEdit=!1;cm&&reCheckSelection(cm.doc)}cm&&signalLater(cm,"markerCleared",cm,this);withOp&&endOperation(cm);this.parent&&this.parent.clear()}};TextMarker.prototype.find=function(side,lineObj){null==side&&"bookmark"==this.type&&(side=1);for(var from,to,i=0;i<this.lines.length;++i){var line=this.lines[i],span=getMarkedSpanFor(line.markedSpans,this);if(null!=span.from){from=Pos(lineObj?line:lineNo(line),span.from);if(-1==side)return from}if(null!=span.to){to=Pos(lineObj?line:lineNo(line),span.to);if(1==side)return to}}return from&&{from:from,to:to}};TextMarker.prototype.changed=function(){var pos=this.find(-1,!0),widget=this,cm=this.doc.cm;pos&&cm&&runInOp(cm,function(){var line=pos.line,lineN=lineNo(pos.line),view=findViewForLine(cm,lineN);if(view){clearLineMeasurementCacheFor(view);cm.curOp.selectionChanged=cm.curOp.forceUpdate=!0}cm.curOp.updateMaxLine=!0;if(!lineIsHidden(widget.doc,line)&&null!=widget.height){var oldHeight=widget.height;widget.height=null;var dHeight=widgetHeight(widget)-oldHeight;dHeight&&updateLineHeight(line,line.height+dHeight)}})};TextMarker.prototype.attachLine=function(line){if(!this.lines.length&&this.doc.cm){var op=this.doc.cm.curOp;op.maybeHiddenMarkers&&-1!=indexOf(op.maybeHiddenMarkers,this)||(op.maybeUnhiddenMarkers||(op.maybeUnhiddenMarkers=[])).push(this)}this.lines.push(line)};TextMarker.prototype.detachLine=function(line){this.lines.splice(indexOf(this.lines,line),1);if(!this.lines.length&&this.doc.cm){var op=this.doc.cm.curOp;(op.maybeHiddenMarkers||(op.maybeHiddenMarkers=[])).push(this)}};var nextMarkerId=0,SharedTextMarker=CodeMirror.SharedTextMarker=function(markers,primary){this.markers=markers;this.primary=primary;for(var i=0;i<markers.length;++i)markers[i].parent=this};eventMixin(SharedTextMarker);SharedTextMarker.prototype.clear=function(){if(!this.explicitlyCleared){this.explicitlyCleared=!0;for(var i=0;i<this.markers.length;++i)this.markers[i].clear();signalLater(this,"clear")}};SharedTextMarker.prototype.find=function(side,lineObj){return this.primary.find(side,lineObj)};var LineWidget=CodeMirror.LineWidget=function(doc,node,options){if(options)for(var opt in options)options.hasOwnProperty(opt)&&(this[opt]=options[opt]);this.doc=doc;this.node=node};eventMixin(LineWidget);LineWidget.prototype.clear=function(){var cm=this.doc.cm,ws=this.line.widgets,line=this.line,no=lineNo(line);if(null!=no&&ws){for(var i=0;i<ws.length;++i)ws[i]==this&&ws.splice(i--,1);ws.length||(line.widgets=null);var height=widgetHeight(this);updateLineHeight(line,Math.max(0,line.height-height));cm&&runInOp(cm,function(){adjustScrollWhenAboveVisible(cm,line,-height);regLineChange(cm,no,"widget")})}};LineWidget.prototype.changed=function(){var oldH=this.height,cm=this.doc.cm,line=this.line;this.height=null;var diff=widgetHeight(this)-oldH;if(diff){updateLineHeight(line,line.height+diff);cm&&runInOp(cm,function(){cm.curOp.forceUpdate=!0;adjustScrollWhenAboveVisible(cm,line,diff)})}};var Line=CodeMirror.Line=function(text,markedSpans,estimateHeight){this.text=text;attachMarkedSpans(this,markedSpans);this.height=estimateHeight?estimateHeight(this):1};eventMixin(Line);Line.prototype.lineNo=function(){return lineNo(this)};var styleToClassCache={},styleToClassCacheWithMode={};LeafChunk.prototype={chunkSize:function(){return this.lines.length},removeInner:function(at,n){for(var i=at,e=at+n;e>i;++i){var line=this.lines[i];this.height-=line.height;cleanUpLine(line);signalLater(line,"delete")}this.lines.splice(at,n)},collapse:function(lines){lines.push.apply(lines,this.lines)},insertInner:function(at,lines,height){this.height+=height;this.lines=this.lines.slice(0,at).concat(lines).concat(this.lines.slice(at));for(var i=0;i<lines.length;++i)lines[i].parent=this},iterN:function(at,n,op){for(var e=at+n;e>at;++at)if(op(this.lines[at]))return!0}};BranchChunk.prototype={chunkSize:function(){return this.size},removeInner:function(at,n){this.size-=n;for(var i=0;i<this.children.length;++i){var child=this.children[i],sz=child.chunkSize();if(sz>at){var rm=Math.min(n,sz-at),oldHeight=child.height;child.removeInner(at,rm);this.height-=oldHeight-child.height;if(sz==rm){this.children.splice(i--,1);child.parent=null}if(0==(n-=rm))break;at=0}else at-=sz}if(this.size-n<25&&(this.children.length>1||!(this.children[0]instanceof LeafChunk))){var lines=[];this.collapse(lines);this.children=[new LeafChunk(lines)];this.children[0].parent=this}},collapse:function(lines){for(var i=0;i<this.children.length;++i)this.children[i].collapse(lines)},insertInner:function(at,lines,height){this.size+=lines.length;this.height+=height;for(var i=0;i<this.children.length;++i){var child=this.children[i],sz=child.chunkSize();if(sz>=at){child.insertInner(at,lines,height);if(child.lines&&child.lines.length>50){for(;child.lines.length>50;){var spilled=child.lines.splice(child.lines.length-25,25),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)){var me=this;do{var spilled=me.children.splice(me.children.length-5,5),sibling=new BranchChunk(spilled);if(me.parent){me.size-=sibling.size;me.height-=sibling.height;var myIndex=indexOf(me.parent.children,me);me.parent.children.splice(myIndex+1,0,sibling)}else{var copy=new BranchChunk(me.children);copy.parent=me;me.children=[copy,sibling];me=copy}sibling.parent=me.parent}while(me.children.length>10);me.parent.maybeSpill()}},iterN:function(at,n,op){for(var i=0;i<this.children.length;++i){var child=this.children[i],sz=child.chunkSize();if(sz>at){var used=Math.min(n,sz-at);if(child.iterN(at,used,op))return!0;if(0==(n-=used))break;at=0}else at-=sz}}};var nextDocId=0,Doc=CodeMirror.Doc=function(text,mode,firstLine,lineSep){if(!(this instanceof Doc))return new Doc(text,mode,firstLine,lineSep);null==firstLine&&(firstLine=0);BranchChunk.call(this,[new LeafChunk([new Line("",null)])]);this.first=firstLine;this.scrollTop=this.scrollLeft=0;this.cantEdit=!1;this.cleanGeneration=1;this.frontier=firstLine;var start=Pos(firstLine,0);this.sel=simpleSelection(start);this.history=new History(null);this.id=++nextDocId;this.modeOption=mode;this.lineSep=lineSep;this.extend=!1;"string"==typeof text&&(text=this.splitLines(text));updateDoc(this,{from:start,to:start,text:text});setSelection(this,simpleSelection(start),sel_dontScroll)};Doc.prototype=createObj(BranchChunk.prototype,{constructor:Doc,iter:function(from,to,op){op?this.iterN(from-this.first,to-from,op):this.iterN(this.first,this.first+this.size,from)},insert:function(at,lines){for(var height=0,i=0;i<lines.length;++i)height+=lines[i].height;this.insertInner(at-this.first,lines,height)},remove:function(at,n){this.removeInner(at-this.first,n)},getValue:function(lineSep){var lines=getLines(this,this.first,this.first+this.size);return lineSep===!1?lines:lines.join(lineSep||this.lineSeparator())},setValue:docMethodOp(function(code){var top=Pos(this.first,0),last=this.first+this.size-1;makeChange(this,{from:top,to:Pos(last,getLine(this,last).text.length),text:this.splitLines(code),origin:"setValue",full:!0},!0);setSelection(this,simpleSelection(top))}),replaceRange:function(code,from,to,origin){from=clipPos(this,from);to=to?clipPos(this,to):from;replaceRange(this,code,from,to,origin)},getRange:function(from,to,lineSep){var lines=getBetween(this,clipPos(this,from),clipPos(this,to));return lineSep===!1?lines:lines.join(lineSep||this.lineSeparator())},getLine:function(line){var l=this.getLineHandle(line);return l&&l.text},getLineHandle:function(line){return isLine(this,line)?getLine(this,line):void 0},getLineNumber:function(line){return lineNo(line)},getLineHandleVisualStart:function(line){"number"==typeof line&&(line=getLine(this,line));return visualLine(line)},lineCount:function(){return this.size},firstLine:function(){return this.first},lastLine:function(){return this.first+this.size-1},clipPos:function(pos){return clipPos(this,pos)},getCursor:function(start){var pos,range=this.sel.primary();pos=null==start||"head"==start?range.head:"anchor"==start?range.anchor:"end"==start||"to"==start||start===!1?range.to():range.from();return pos},listSelections:function(){return this.sel.ranges},somethingSelected:function(){return this.sel.somethingSelected()},setCursor:docMethodOp(function(line,ch,options){setSimpleSelection(this,clipPos(this,"number"==typeof line?Pos(line,ch||0):line),null,options)}),setSelection:docMethodOp(function(anchor,head,options){setSimpleSelection(this,clipPos(this,anchor),clipPos(this,head||anchor),options)}),extendSelection:docMethodOp(function(head,other,options){extendSelection(this,clipPos(this,head),other&&clipPos(this,other),options)}),extendSelections:docMethodOp(function(heads,options){extendSelections(this,clipPosArray(this,heads),options)}),extendSelectionsBy:docMethodOp(function(f,options){var heads=map(this.sel.ranges,f);extendSelections(this,clipPosArray(this,heads),options)}),setSelections:docMethodOp(function(ranges,primary,options){if(ranges.length){for(var i=0,out=[];i<ranges.length;i++)out[i]=new Range(clipPos(this,ranges[i].anchor),clipPos(this,ranges[i].head));null==primary&&(primary=Math.min(ranges.length-1,this.sel.primIndex));setSelection(this,normalizeSelection(out,primary),options)}}),addSelection:docMethodOp(function(anchor,head,options){var ranges=this.sel.ranges.slice(0);ranges.push(new Range(clipPos(this,anchor),clipPos(this,head||anchor)));setSelection(this,normalizeSelection(ranges,ranges.length-1),options)}),getSelection:function(lineSep){for(var lines,ranges=this.sel.ranges,i=0;i<ranges.length;i++){var sel=getBetween(this,ranges[i].from(),ranges[i].to());lines=lines?lines.concat(sel):sel}return lineSep===!1?lines:lines.join(lineSep||this.lineSeparator())},getSelections:function(lineSep){for(var parts=[],ranges=this.sel.ranges,i=0;i<ranges.length;i++){var sel=getBetween(this,ranges[i].from(),ranges[i].to());lineSep!==!1&&(sel=sel.join(lineSep||this.lineSeparator()));parts[i]=sel}return parts},replaceSelection:function(code,collapse,origin){for(var dup=[],i=0;i<this.sel.ranges.length;i++)dup[i]=code;this.replaceSelections(dup,collapse,origin||"+input")},replaceSelections:docMethodOp(function(code,collapse,origin){for(var changes=[],sel=this.sel,i=0;i<sel.ranges.length;i++){var range=sel.ranges[i];changes[i]={from:range.from(),to:range.to(),text:this.splitLines(code[i]),origin:origin}}for(var newSel=collapse&&"end"!=collapse&&computeReplacedSel(this,changes,collapse),i=changes.length-1;i>=0;i--)makeChange(this,changes[i]);newSel?setSelectionReplaceHistory(this,newSel):this.cm&&ensureCursorVisible(this.cm)}),undo:docMethodOp(function(){makeChangeFromHistory(this,"undo")}),redo:docMethodOp(function(){makeChangeFromHistory(this,"redo")}),undoSelection:docMethodOp(function(){makeChangeFromHistory(this,"undo",!0)}),redoSelection:docMethodOp(function(){makeChangeFromHistory(this,"redo",!0)}),setExtending:function(val){this.extend=val},getExtending:function(){return this.extend},historySize:function(){for(var hist=this.history,done=0,undone=0,i=0;i<hist.done.length;i++)hist.done[i].ranges||++done;for(var i=0;i<hist.undone.length;i++)hist.undone[i].ranges||++undone;return{undo:done,redo:undone}},clearHistory:function(){this.history=new History(this.history.maxGeneration)},markClean:function(){this.cleanGeneration=this.changeGeneration(!0)},changeGeneration:function(forceSplit){forceSplit&&(this.history.lastOp=this.history.lastSelOp=this.history.lastOrigin=null);return this.history.generation},isClean:function(gen){return this.history.generation==(gen||this.cleanGeneration)},getHistory:function(){return{done:copyHistoryArray(this.history.done),undone:copyHistoryArray(this.history.undone)}},setHistory:function(histData){var hist=this.history=new History(this.history.maxGeneration);hist.done=copyHistoryArray(histData.done.slice(0),null,!0);hist.undone=copyHistoryArray(histData.undone.slice(0),null,!0)},addLineClass:docMethodOp(function(handle,where,cls){return changeLine(this,handle,"gutter"==where?"gutter":"class",function(line){var prop="text"==where?"textClass":"background"==where?"bgClass":"gutter"==where?"gutterClass":"wrapClass";if(line[prop]){if(classTest(cls).test(line[prop]))return!1;line[prop]+=" "+cls}else line[prop]=cls;return!0})}),removeLineClass:docMethodOp(function(handle,where,cls){return changeLine(this,handle,"gutter"==where?"gutter":"class",function(line){var prop="text"==where?"textClass":"background"==where?"bgClass":"gutter"==where?"gutterClass":"wrapClass",cur=line[prop];if(!cur)return!1;if(null==cls)line[prop]=null;else{var found=cur.match(classTest(cls));if(!found)return!1;var end=found.index+found[0].length;line[prop]=cur.slice(0,found.index)+(found.index&&end!=cur.length?" ":"")+cur.slice(end)||null}return!0})}),addLineWidget:docMethodOp(function(handle,node,options){return addLineWidget(this,handle,node,options)}),removeLineWidget:function(widget){widget.clear()},markText:function(from,to,options){return markText(this,clipPos(this,from),clipPos(this,to),options,options&&options.type||"range")},setBookmark:function(pos,options){var realOpts={replacedWith:options&&(null==options.nodeType?options.widget:options),insertLeft:options&&options.insertLeft,clearWhenEmpty:!1,shared:options&&options.shared,handleMouseEvents:options&&options.handleMouseEvents};pos=clipPos(this,pos);return markText(this,pos,pos,realOpts,"bookmark")},findMarksAt:function(pos){pos=clipPos(this,pos);var markers=[],spans=getLine(this,pos.line).markedSpans;if(spans)for(var i=0;i<spans.length;++i){var span=spans[i];(null==span.from||span.from<=pos.ch)&&(null==span.to||span.to>=pos.ch)&&markers.push(span.marker.parent||span.marker)}return markers},findMarks:function(from,to,filter){from=clipPos(this,from);to=clipPos(this,to);var found=[],lineNo=from.line;this.iter(from.line,to.line+1,function(line){var spans=line.markedSpans;if(spans)for(var i=0;i<spans.length;i++){var span=spans[i];null!=span.to&&lineNo==from.line&&from.ch>=span.to||null==span.from&&lineNo!=from.line||null!=span.from&&lineNo==to.line&&span.from>=to.ch||filter&&!filter(span.marker)||found.push(span.marker.parent||span.marker)}++lineNo});return found},getAllMarks:function(){var markers=[];this.iter(function(line){var sps=line.markedSpans;if(sps)for(var i=0;i<sps.length;++i)null!=sps[i].from&&markers.push(sps[i].marker)});return markers},posFromIndex:function(off){var ch,lineNo=this.first,sepSize=this.lineSeparator().length;this.iter(function(line){var sz=line.text.length+sepSize;if(sz>off){ch=off;return!0}off-=sz;++lineNo});return clipPos(this,Pos(lineNo,ch))},indexFromPos:function(coords){coords=clipPos(this,coords);var index=coords.ch;if(coords.line<this.first||coords.ch<0)return 0;var sepSize=this.lineSeparator().length;this.iter(this.first,coords.line,function(line){index+=line.text.length+sepSize});return index},copy:function(copyHistory){var doc=new Doc(getLines(this,this.first,this.first+this.size),this.modeOption,this.first,this.lineSep);doc.scrollTop=this.scrollTop;doc.scrollLeft=this.scrollLeft;doc.sel=this.sel;doc.extend=!1;if(copyHistory){doc.history.undoDepth=this.history.undoDepth;doc.setHistory(this.getHistory())}return doc},linkedDoc:function(options){options||(options={});var from=this.first,to=this.first+this.size;null!=options.from&&options.from>from&&(from=options.from);null!=options.to&&options.to<to&&(to=options.to);var copy=new Doc(getLines(this,from,to),options.mode||this.modeOption,from,this.lineSep);options.sharedHist&&(copy.history=this.history);(this.linked||(this.linked=[])).push({doc:copy,sharedHist:options.sharedHist});copy.linked=[{doc:this,isParent:!0,sharedHist:options.sharedHist}];copySharedMarkers(copy,findSharedMarkers(this));return copy},unlinkDoc:function(other){other instanceof CodeMirror&&(other=other.doc);if(this.linked)for(var i=0;i<this.linked.length;++i){var link=this.linked[i];if(link.doc==other){this.linked.splice(i,1);other.unlinkDoc(this);detachSharedMarkers(findSharedMarkers(this));break}}if(other.history==this.history){var splitIds=[other.id];linkedDocs(other,function(doc){splitIds.push(doc.id)},!0);other.history=new History(null);other.history.done=copyHistoryArray(this.history.done,splitIds);other.history.undone=copyHistoryArray(this.history.undone,splitIds)}},iterLinkedDocs:function(f){linkedDocs(this,f)},getMode:function(){return this.mode},getEditor:function(){return this.cm},splitLines:function(str){return this.lineSep?str.split(this.lineSep):splitLinesAuto(str)},lineSeparator:function(){return this.lineSep||"\n"}});Doc.prototype.eachLine=Doc.prototype.iter;var dontDelegate="iter insert remove copy getEditor constructor".split(" ");for(var prop in Doc.prototype)Doc.prototype.hasOwnProperty(prop)&&indexOf(dontDelegate,prop)<0&&(CodeMirror.prototype[prop]=function(method){return function(){return method.apply(this.doc,arguments)}}(Doc.prototype[prop]));eventMixin(Doc);var e_preventDefault=CodeMirror.e_preventDefault=function(e){e.preventDefault?e.preventDefault():e.returnValue=!1},e_stopPropagation=CodeMirror.e_stopPropagation=function(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0},e_stop=CodeMirror.e_stop=function(e){e_preventDefault(e);e_stopPropagation(e)},on=CodeMirror.on=function(emitter,type,f){if(emitter.addEventListener)emitter.addEventListener(type,f,!1);else if(emitter.attachEvent)emitter.attachEvent("on"+type,f);else{var map=emitter._handlers||(emitter._handlers={}),arr=map[type]||(map[type]=[]);arr.push(f)}},noHandlers=[],off=CodeMirror.off=function(emitter,type,f){if(emitter.removeEventListener)emitter.removeEventListener(type,f,!1);else if(emitter.detachEvent)emitter.detachEvent("on"+type,f);else for(var handlers=getHandlers(emitter,type,!1),i=0;i<handlers.length;++i)if(handlers[i]==f){handlers.splice(i,1);break}},signal=CodeMirror.signal=function(emitter,type){var handlers=getHandlers(emitter,type,!0);if(handlers.length)for(var args=Array.prototype.slice.call(arguments,2),i=0;i<handlers.length;++i)handlers[i].apply(null,args)},orphanDelayedCallbacks=null,scrollerGap=30,Pass=CodeMirror.Pass={toString:function(){return"CodeMirror.Pass"}},sel_dontScroll={scroll:!1},sel_mouse={origin:"*mouse"},sel_move={origin:"+move"};Delayed.prototype.set=function(ms,f){clearTimeout(this.id);this.id=setTimeout(f,ms)};var countColumn=CodeMirror.countColumn=function(string,end,tabSize,startIndex,startValue){if(null==end){end=string.search(/[^\s\u00a0]/);-1==end&&(end=string.length)}for(var i=startIndex||0,n=startValue||0;;){var nextTab=string.indexOf(" ",i);if(0>nextTab||nextTab>=end)return n+(end-i);n+=nextTab-i;n+=tabSize-n%tabSize;i=nextTab+1}},findColumn=CodeMirror.findColumn=function(string,goal,tabSize){for(var pos=0,col=0;;){var nextTab=string.indexOf(" ",pos);-1==nextTab&&(nextTab=string.length);var skipped=nextTab-pos;if(nextTab==string.length||col+skipped>=goal)return pos+Math.min(skipped,goal-col);col+=nextTab-pos;col+=tabSize-col%tabSize;pos=nextTab+1;if(col>=goal)return pos}},spaceStrs=[""],selectInput=function(node){node.select()};ios?selectInput=function(node){node.selectionStart=0;node.selectionEnd=node.value.length}:ie&&(selectInput=function(node){try{node.select()}catch(_e){}});var range,nonASCIISingleCaseWordChar=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,isWordCharBasic=CodeMirror.isWordChar=function(ch){return/\w/.test(ch)||ch>"€"&&(ch.toUpperCase()!=ch.toLowerCase()||nonASCIISingleCaseWordChar.test(ch))},extendingChars=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;range=document.createRange?function(node,start,end,endNode){var r=document.createRange();r.setEnd(endNode||node,end);r.setStart(node,start);return r}:function(node,start,end){var r=document.body.createTextRange();try{r.moveToElementText(node.parentNode)}catch(e){return r}r.collapse(!0);r.moveEnd("character",end);r.moveStart("character",start);return r};var contains=CodeMirror.contains=function(parent,child){3==child.nodeType&&(child=child.parentNode);if(parent.contains)return parent.contains(child);do{11==child.nodeType&&(child=child.host);if(child==parent)return!0}while(child=child.parentNode)};ie&&11>ie_version&&(activeElt=function(){try{return document.activeElement}catch(e){return document.body}});var zwspSupported,badBidiRects,rmClass=CodeMirror.rmClass=function(node,cls){var current=node.className,match=classTest(cls).exec(current);if(match){var after=current.slice(match.index+match[0].length);node.className=current.slice(0,match.index)+(after?match[1]+after:"")}},addClass=CodeMirror.addClass=function(node,cls){var current=node.className;classTest(cls).test(current)||(node.className+=(current?" ":"")+cls)},globalsRegistered=!1,dragAndDrop=function(){if(ie&&9>ie_version)return!1;var div=elt("div");return"draggable"in div||"dragDrop"in div}(),splitLinesAuto=CodeMirror.splitLines=3!="\n\nb".split(/\n/).length?function(string){for(var pos=0,result=[],l=string.length;l>=pos;){var nl=string.indexOf("\n",pos);-1==nl&&(nl=string.length);var line=string.slice(pos,"\r"==string.charAt(nl-1)?nl-1:nl),rt=line.indexOf("\r");if(-1!=rt){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/)},hasSelection=window.getSelection?function(te){try{return te.selectionStart!=te.selectionEnd}catch(e){return!1}}:function(te){try{var range=te.ownerDocument.selection.createRange()}catch(e){}return range&&range.parentElement()==te?0!=range.compareEndPoints("StartToEnd",range):!1},hasCopyEvent=function(){var e=elt("div");if("oncopy"in e)return!0;e.setAttribute("oncopy","return;");return"function"==typeof e.oncopy}(),badZoomedRects=null,keyNames=CodeMirror.keyNames={3:"Enter",8:"Backspace",9:"Tab",13:"Enter",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"CapsLock",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"Left",38:"Up",39:"Right",40:"Down",44:"PrintScrn",45:"Insert",46:"Delete",59:";",61:"=",91:"Mod",92:"Mod",93:"Mod",106:"*",107:"=",109:"-",110:".",111:"/",127:"Delete",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'",63232:"Up",63233:"Down",63234:"Left",63235:"Right",63272:"Delete",63273:"Home",63275:"End",63276:"PageUp",63277:"PageDown",63302:"Insert"};!function(){for(var i=0;10>i;i++)keyNames[i+48]=keyNames[i+96]=String(i);for(var i=65;90>=i;i++)keyNames[i]=String.fromCharCode(i);for(var i=1;12>=i;i++)keyNames[i+111]=keyNames[i+63235]="F"+i}();var bidiOther,bidiOrdering=function(){function charType(code){return 247>=code?lowTypes.charAt(code):code>=1424&&1524>=code?"R":code>=1536&&1773>=code?arabicTypes.charAt(code-1536):code>=1774&&2220>=code?"r":code>=8192&&8203>=code?"w":8204==code?"b":"L"}function BidiSpan(level,from,to){this.level=level;this.from=from;this.to=to}var lowTypes="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",arabicTypes="rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm",bidiRE=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,isNeutral=/[stwN]/,isStrong=/[LRr]/,countsAsLeft=/[Lb1n]/,countsAsNum=/[1n]/,outerType="L";return function(str){if(!bidiRE.test(str))return!1;for(var type,len=str.length,types=[],i=0;len>i;++i)types.push(type=charType(str.charCodeAt(i)));for(var i=0,prev=outerType;len>i;++i){var type=types[i];"m"==type?types[i]=prev:prev=type}for(var i=0,cur=outerType;len>i;++i){var type=types[i];if("1"==type&&"r"==cur)types[i]="n";else if(isStrong.test(type)){cur=type;"r"==type&&(types[i]="R")}}for(var i=1,prev=types[0];len-1>i;++i){var type=types[i];"+"==type&&"1"==prev&&"1"==types[i+1]?types[i]="1":","!=type||prev!=types[i+1]||"1"!=prev&&"n"!=prev||(types[i]=prev);prev=type}for(var i=0;len>i;++i){var type=types[i];if(","==type)types[i]="N";else if("%"==type){for(var end=i+1;len>end&&"%"==types[end];++end);for(var replace=i&&"!"==types[i-1]||len>end&&"1"==types[end]?"1":"N",j=i;end>j;++j)types[j]=replace;i=end-1}}for(var i=0,cur=outerType;len>i;++i){var type=types[i];"L"==cur&&"1"==type?types[i]="L":isStrong.test(type)&&(cur=type)}for(var i=0;len>i;++i)if(isNeutral.test(types[i])){for(var end=i+1;len>end&&isNeutral.test(types[end]);++end);for(var before="L"==(i?types[i-1]:outerType),after="L"==(len>end?types[end]:outerType),replace=before||after?"L":"R",j=i;end>j;++j)types[j]=replace;i=end-1}for(var m,order=[],i=0;len>i;)if(countsAsLeft.test(types[i])){var start=i;for(++i;len>i&&countsAsLeft.test(types[i]);++i);order.push(new BidiSpan(0,start,i))}else{var pos=i,at=order.length;for(++i;len>i&&"L"!=types[i];++i);for(var j=pos;i>j;)if(countsAsNum.test(types[j])){j>pos&&order.splice(at,0,new BidiSpan(1,pos,j));var nstart=j;for(++j;i>j&&countsAsNum.test(types[j]);++j);order.splice(at,0,new BidiSpan(2,nstart,j));pos=j}else++j;i>pos&&order.splice(at,0,new BidiSpan(1,pos,i))}if(1==order[0].level&&(m=str.match(/^\s+/))){order[0].from=m[0].length;order.unshift(new BidiSpan(0,0,m[0].length))}if(1==lst(order).level&&(m=str.match(/\s+$/))){lst(order).to-=m[0].length;order.push(new BidiSpan(0,len-m[0].length,len))}2==order[0].level&&order.unshift(new BidiSpan(1,order[0].to,order[0].to));order[0].level!=lst(order).level&&order.push(new BidiSpan(order[0].level,len,len));return order}}();CodeMirror.version="5.14.2";return CodeMirror});
 
1
+ !function(global,factory){"object"==typeof exports&&"undefined"!=typeof module?module.exports=factory():"function"==typeof define&&define.amd?define(factory):global.CodeMirror=factory()}(this,function(){"use strict";function classTest(cls){return new RegExp("(^|\\s)"+cls+"(?:$|\\s)\\s*")}function removeChildren(e){for(var count=e.childNodes.length;count>0;--count)e.removeChild(e.firstChild);return e}function removeChildrenAndAdd(parent,e){return removeChildren(parent).appendChild(e)}function elt(tag,content,className,style){var e=document.createElement(tag);className&&(e.className=className);style&&(e.style.cssText=style);if("string"==typeof content)e.appendChild(document.createTextNode(content));else if(content)for(var i=0;i<content.length;++i)e.appendChild(content[i]);return e}function contains(parent,child){3==child.nodeType&&(child=child.parentNode);if(parent.contains)return parent.contains(child);do{11==child.nodeType&&(child=child.host);if(child==parent)return!0}while(child=child.parentNode)}function activeElt(){var activeElement;try{activeElement=document.activeElement}catch(e){activeElement=document.body||null}for(;activeElement&&activeElement.root&&activeElement.root.activeElement;)activeElement=activeElement.root.activeElement;return activeElement}function addClass(node,cls){var current=node.className;classTest(cls).test(current)||(node.className+=(current?" ":"")+cls)}function joinClasses(a,b){for(var as=a.split(" "),i=0;i<as.length;i++)as[i]&&!classTest(as[i]).test(b)&&(b+=" "+as[i]);return b}function bind(f){var args=Array.prototype.slice.call(arguments,1);return function(){return f.apply(null,args)}}function copyObj(obj,target,overwrite){target||(target={});for(var prop in obj)!obj.hasOwnProperty(prop)||overwrite===!1&&target.hasOwnProperty(prop)||(target[prop]=obj[prop]);return target}function countColumn(string,end,tabSize,startIndex,startValue){if(null==end){end=string.search(/[^\s\u00a0]/);end==-1&&(end=string.length)}for(var i=startIndex||0,n=startValue||0;;){var nextTab=string.indexOf("\t",i);if(nextTab<0||nextTab>=end)return n+(end-i);n+=nextTab-i;n+=tabSize-n%tabSize;i=nextTab+1}}function Delayed(){this.id=null}function indexOf(array,elt){for(var i=0;i<array.length;++i)if(array[i]==elt)return i;return-1}function findColumn(string,goal,tabSize){for(var pos=0,col=0;;){var nextTab=string.indexOf("\t",pos);nextTab==-1&&(nextTab=string.length);var skipped=nextTab-pos;if(nextTab==string.length||col+skipped>=goal)return pos+Math.min(skipped,goal-col);col+=nextTab-pos;col+=tabSize-col%tabSize;pos=nextTab+1;if(col>=goal)return pos}}function spaceStr(n){for(;spaceStrs.length<=n;)spaceStrs.push(lst(spaceStrs)+" ");return spaceStrs[n]}function lst(arr){return arr[arr.length-1]}function map(array,f){for(var out=[],i=0;i<array.length;i++)out[i]=f(array[i],i);return out}function insertSorted(array,value,score){for(var pos=0,priority=score(value);pos<array.length&&score(array[pos])<=priority;)pos++;array.splice(pos,0,value)}function nothing(){}function createObj(base,props){var inst;if(Object.create)inst=Object.create(base);else{nothing.prototype=base;inst=new nothing}props&&copyObj(props,inst);return inst}function isWordCharBasic(ch){return/\w/.test(ch)||ch>"€"&&(ch.toUpperCase()!=ch.toLowerCase()||nonASCIISingleCaseWordChar.test(ch))}function isWordChar(ch,helper){return helper?!!(helper.source.indexOf("\\w")>-1&&isWordCharBasic(ch))||helper.test(ch):isWordCharBasic(ch)}function isEmpty(obj){for(var n in obj)if(obj.hasOwnProperty(n)&&obj[n])return!1;return!0}function isExtendingChar(ch){return ch.charCodeAt(0)>=768&&extendingChars.test(ch)}function Display(place,doc,input){var d=this;this.input=input;d.scrollbarFiller=elt("div",null,"CodeMirror-scrollbar-filler");d.scrollbarFiller.setAttribute("cm-not-content","true");d.gutterFiller=elt("div",null,"CodeMirror-gutter-filler");d.gutterFiller.setAttribute("cm-not-content","true");d.lineDiv=elt("div",null,"CodeMirror-code");d.selectionDiv=elt("div",null,null,"position: relative; z-index: 1");d.cursorDiv=elt("div",null,"CodeMirror-cursors");d.measure=elt("div",null,"CodeMirror-measure");d.lineMeasure=elt("div",null,"CodeMirror-measure");d.lineSpace=elt("div",[d.measure,d.lineMeasure,d.selectionDiv,d.cursorDiv,d.lineDiv],null,"position: relative; outline: none");d.mover=elt("div",[elt("div",[d.lineSpace],"CodeMirror-lines")],null,"position: relative");d.sizer=elt("div",[d.mover],"CodeMirror-sizer");d.sizerWidth=null;d.heightForcer=elt("div",null,null,"position: absolute; height: "+scrollerGap+"px; width: 1px;");d.gutters=elt("div",null,"CodeMirror-gutters");d.lineGutter=null;d.scroller=elt("div",[d.sizer,d.heightForcer,d.gutters],"CodeMirror-scroll");d.scroller.setAttribute("tabIndex","-1");d.wrapper=elt("div",[d.scrollbarFiller,d.gutterFiller,d.scroller],"CodeMirror");if(ie&&ie_version<8){d.gutters.style.zIndex=-1;d.scroller.style.paddingRight=0}webkit||gecko&&mobile||(d.scroller.draggable=!0);place&&(place.appendChild?place.appendChild(d.wrapper):place(d.wrapper));d.viewFrom=d.viewTo=doc.first;d.reportedViewFrom=d.reportedViewTo=doc.first;d.view=[];d.renderedView=null;d.externalMeasured=null;d.viewOffset=0;d.lastWrapHeight=d.lastWrapWidth=0;d.updateLineNumbers=null;d.nativeBarWidth=d.barHeight=d.barWidth=0;d.scrollbarsClipped=!1;d.lineNumWidth=d.lineNumInnerWidth=d.lineNumChars=null;d.alignWidgets=!1;d.cachedCharWidth=d.cachedTextHeight=d.cachedPaddingH=null;d.maxLine=null;d.maxLineLength=0;d.maxLineChanged=!1;d.wheelDX=d.wheelDY=d.wheelStartX=d.wheelStartY=null;d.shift=!1;d.selForContextMenu=null;d.activeTouch=null;input.init(d)}function getLine(doc,n){n-=doc.first;if(n<0||n>=doc.size)throw new Error("There is no line "+(n+doc.first)+" in the document.");for(var chunk=doc;!chunk.lines;)for(var i=0;;++i){var child=chunk.children[i],sz=child.chunkSize();if(n<sz){chunk=child;break}n-=sz}return chunk.lines[n]}function getBetween(doc,start,end){var out=[],n=start.line;doc.iter(start.line,end.line+1,function(line){var text=line.text;n==end.line&&(text=text.slice(0,end.ch));n==start.line&&(text=text.slice(start.ch));out.push(text);++n});return out}function getLines(doc,from,to){var out=[];doc.iter(from,to,function(line){out.push(line.text)});return out}function updateLineHeight(line,height){var diff=height-line.height;if(diff)for(var n=line;n;n=n.parent)n.height+=diff}function lineNo(line){if(null==line.parent)return null;for(var cur=line.parent,no=indexOf(cur.lines,line),chunk=cur.parent;chunk;cur=chunk,chunk=chunk.parent)for(var i=0;chunk.children[i]!=cur;++i)no+=chunk.children[i].chunkSize();return no+cur.first}function lineAtHeight(chunk,h){var n=chunk.first;outer:do{for(var i$1=0;i$1<chunk.children.length;++i$1){var child=chunk.children[i$1],ch=child.height;if(h<ch){chunk=child;continue outer}h-=ch;n+=child.chunkSize()}return n}while(!chunk.lines);for(var i=0;i<chunk.lines.length;++i){var line=chunk.lines[i],lh=line.height;if(h<lh)break;h-=lh}return n+i}function isLine(doc,l){return l>=doc.first&&l<doc.first+doc.size}function lineNumberFor(options,i){return String(options.lineNumberFormatter(i+options.firstLineNumber))}function Pos(line,ch){if(!(this instanceof Pos))return new Pos(line,ch);this.line=line;this.ch=ch}function cmp(a,b){return a.line-b.line||a.ch-b.ch}function copyPos(x){return Pos(x.line,x.ch)}function maxPos(a,b){return cmp(a,b)<0?b:a}function minPos(a,b){return cmp(a,b)<0?a:b}function clipLine(doc,n){return Math.max(doc.first,Math.min(n,doc.first+doc.size-1))}function clipPos(doc,pos){if(pos.line<doc.first)return Pos(doc.first,0);var last=doc.first+doc.size-1;return pos.line>last?Pos(last,getLine(doc,last).text.length):clipToLen(pos,getLine(doc,pos.line).text.length)}function clipToLen(pos,linelen){var ch=pos.ch;return null==ch||ch>linelen?Pos(pos.line,linelen):ch<0?Pos(pos.line,0):pos}function clipPosArray(doc,array){for(var out=[],i=0;i<array.length;i++)out[i]=clipPos(doc,array[i]);return out}function seeReadOnlySpans(){sawReadOnlySpans=!0}function seeCollapsedSpans(){sawCollapsedSpans=!0}function MarkedSpan(marker,from,to){this.marker=marker;this.from=from;this.to=to}function getMarkedSpanFor(spans,marker){if(spans)for(var i=0;i<spans.length;++i){var span=spans[i];if(span.marker==marker)return span}}function removeMarkedSpan(spans,span){for(var r,i=0;i<spans.length;++i)spans[i]!=span&&(r||(r=[])).push(spans[i]);return r}function addMarkedSpan(line,span){line.markedSpans=line.markedSpans?line.markedSpans.concat([span]):[span];span.marker.attachLine(line)}function markedSpansBefore(old,startCh,isInsert){var nw;if(old)for(var i=0;i<old.length;++i){var span=old[i],marker=span.marker,startsBefore=null==span.from||(marker.inclusiveLeft?span.from<=startCh:span.from<startCh);if(startsBefore||span.from==startCh&&"bookmark"==marker.type&&(!isInsert||!span.marker.insertLeft)){var endsAfter=null==span.to||(marker.inclusiveRight?span.to>=startCh:span.to>startCh);(nw||(nw=[])).push(new MarkedSpan(marker,span.from,endsAfter?null:span.to))}}return nw}function markedSpansAfter(old,endCh,isInsert){var nw;if(old)for(var i=0;i<old.length;++i){var span=old[i],marker=span.marker,endsAfter=null==span.to||(marker.inclusiveRight?span.to>=endCh:span.to>endCh);if(endsAfter||span.from==endCh&&"bookmark"==marker.type&&(!isInsert||span.marker.insertLeft)){var startsBefore=null==span.from||(marker.inclusiveLeft?span.from<=endCh:span.from<endCh);(nw||(nw=[])).push(new MarkedSpan(marker,startsBefore?null:span.from-endCh,null==span.to?null:span.to-endCh))}}return nw}function stretchSpansOverChange(doc,change){if(change.full)return null;var oldFirst=isLine(doc,change.from.line)&&getLine(doc,change.from.line).markedSpans,oldLast=isLine(doc,change.to.line)&&getLine(doc,change.to.line).markedSpans;if(!oldFirst&&!oldLast)return null;var startCh=change.from.ch,endCh=change.to.ch,isInsert=0==cmp(change.from,change.to),first=markedSpansBefore(oldFirst,startCh,isInsert),last=markedSpansAfter(oldLast,endCh,isInsert),sameLine=1==change.text.length,offset=lst(change.text).length+(sameLine?startCh:0);if(first)for(var i=0;i<first.length;++i){var span=first[i];if(null==span.to){var found=getMarkedSpanFor(last,span.marker);found?sameLine&&(span.to=null==found.to?null:found.to+offset):span.to=startCh}}if(last)for(var i$1=0;i$1<last.length;++i$1){var span$1=last[i$1];null!=span$1.to&&(span$1.to+=offset);if(null==span$1.from){var found$1=getMarkedSpanFor(first,span$1.marker);if(!found$1){span$1.from=offset;sameLine&&(first||(first=[])).push(span$1)}}else{span$1.from+=offset;sameLine&&(first||(first=[])).push(span$1)}}first&&(first=clearEmptySpans(first));last&&last!=first&&(last=clearEmptySpans(last));var newMarkers=[first];if(!sameLine){var gapMarkers,gap=change.text.length-2;if(gap>0&&first)for(var i$2=0;i$2<first.length;++i$2)null==first[i$2].to&&(gapMarkers||(gapMarkers=[])).push(new MarkedSpan(first[i$2].marker,null,null));for(var i$3=0;i$3<gap;++i$3)newMarkers.push(gapMarkers);newMarkers.push(last)}return newMarkers}function clearEmptySpans(spans){for(var i=0;i<spans.length;++i){var span=spans[i];null!=span.from&&span.from==span.to&&span.marker.clearWhenEmpty!==!1&&spans.splice(i--,1)}return spans.length?spans:null}function removeReadOnlyRanges(doc,from,to){var markers=null;doc.iter(from.line,to.line+1,function(line){if(line.markedSpans)for(var i=0;i<line.markedSpans.length;++i){var mark=line.markedSpans[i].marker;!mark.readOnly||markers&&indexOf(markers,mark)!=-1||(markers||(markers=[])).push(mark)}});if(!markers)return null;for(var parts=[{from:from,to:to}],i=0;i<markers.length;++i)for(var mk=markers[i],m=mk.find(0),j=0;j<parts.length;++j){var p=parts[j];if(!(cmp(p.to,m.from)<0||cmp(p.from,m.to)>0)){var newParts=[j,1],dfrom=cmp(p.from,m.from),dto=cmp(p.to,m.to);(dfrom<0||!mk.inclusiveLeft&&!dfrom)&&newParts.push({from:p.from,to:m.from});(dto>0||!mk.inclusiveRight&&!dto)&&newParts.push({from:m.to,to:p.to});parts.splice.apply(parts,newParts);j+=newParts.length-1}}return parts}function detachMarkedSpans(line){var spans=line.markedSpans;if(spans){for(var i=0;i<spans.length;++i)spans[i].marker.detachLine(line);line.markedSpans=null}}function attachMarkedSpans(line,spans){if(spans){for(var i=0;i<spans.length;++i)spans[i].marker.attachLine(line);line.markedSpans=spans}}function extraLeft(marker){return marker.inclusiveLeft?-1:0}function extraRight(marker){return marker.inclusiveRight?1:0}function compareCollapsedMarkers(a,b){var lenDiff=a.lines.length-b.lines.length;if(0!=lenDiff)return lenDiff;var aPos=a.find(),bPos=b.find(),fromCmp=cmp(aPos.from,bPos.from)||extraLeft(a)-extraLeft(b);if(fromCmp)return-fromCmp;var toCmp=cmp(aPos.to,bPos.to)||extraRight(a)-extraRight(b);return toCmp?toCmp:b.id-a.id}function collapsedSpanAtSide(line,start){var found,sps=sawCollapsedSpans&&line.markedSpans;if(sps)for(var sp=void 0,i=0;i<sps.length;++i){sp=sps[i];sp.marker.collapsed&&null==(start?sp.from:sp.to)&&(!found||compareCollapsedMarkers(found,sp.marker)<0)&&(found=sp.marker)}return found}function collapsedSpanAtStart(line){return collapsedSpanAtSide(line,!0)}function collapsedSpanAtEnd(line){return collapsedSpanAtSide(line,!1)}function conflictingCollapsedRange(doc,lineNo,from,to,marker){var line=getLine(doc,lineNo),sps=sawCollapsedSpans&&line.markedSpans;if(sps)for(var i=0;i<sps.length;++i){var sp=sps[i];if(sp.marker.collapsed){var found=sp.marker.find(0),fromCmp=cmp(found.from,from)||extraLeft(sp.marker)-extraLeft(marker),toCmp=cmp(found.to,to)||extraRight(sp.marker)-extraRight(marker);if(!(fromCmp>=0&&toCmp<=0||fromCmp<=0&&toCmp>=0)&&(fromCmp<=0&&(sp.marker.inclusiveRight&&marker.inclusiveLeft?cmp(found.to,from)>=0:cmp(found.to,from)>0)||fromCmp>=0&&(sp.marker.inclusiveRight&&marker.inclusiveLeft?cmp(found.from,to)<=0:cmp(found.from,to)<0)))return!0}}}function visualLine(line){for(var merged;merged=collapsedSpanAtStart(line);)line=merged.find(-1,!0).line;return line}function visualLineContinued(line){for(var merged,lines;merged=collapsedSpanAtEnd(line);){line=merged.find(1,!0).line;(lines||(lines=[])).push(line)}return lines}function visualLineNo(doc,lineN){var line=getLine(doc,lineN),vis=visualLine(line);return line==vis?lineN:lineNo(vis)}function visualLineEndNo(doc,lineN){if(lineN>doc.lastLine())return lineN;var merged,line=getLine(doc,lineN);if(!lineIsHidden(doc,line))return lineN;for(;merged=collapsedSpanAtEnd(line);)line=merged.find(1,!0).line;return lineNo(line)+1}function lineIsHidden(doc,line){var sps=sawCollapsedSpans&&line.markedSpans;if(sps)for(var sp=void 0,i=0;i<sps.length;++i){sp=sps[i];if(sp.marker.collapsed){if(null==sp.from)return!0;if(!sp.marker.widgetNode&&0==sp.from&&sp.marker.inclusiveLeft&&lineIsHiddenInner(doc,line,sp))return!0}}}function lineIsHiddenInner(doc,line,span){if(null==span.to){var end=span.marker.find(1,!0);return lineIsHiddenInner(doc,end.line,getMarkedSpanFor(end.line.markedSpans,span.marker))}if(span.marker.inclusiveRight&&span.to==line.text.length)return!0;for(var sp=void 0,i=0;i<line.markedSpans.length;++i){sp=line.markedSpans[i];if(sp.marker.collapsed&&!sp.marker.widgetNode&&sp.from==span.to&&(null==sp.to||sp.to!=span.from)&&(sp.marker.inclusiveLeft||span.marker.inclusiveRight)&&lineIsHiddenInner(doc,line,sp))return!0}}function heightAtLine(lineObj){lineObj=visualLine(lineObj);for(var h=0,chunk=lineObj.parent,i=0;i<chunk.lines.length;++i){var line=chunk.lines[i];if(line==lineObj)break;h+=line.height}for(var p=chunk.parent;p;chunk=p,p=chunk.parent)for(var i$1=0;i$1<p.children.length;++i$1){var cur=p.children[i$1];if(cur==chunk)break;h+=cur.height}return h}function lineLength(line){if(0==line.height)return 0;for(var merged,len=line.text.length,cur=line;merged=collapsedSpanAtStart(cur);){var found=merged.find(0,!0);cur=found.from.line;len+=found.from.ch-found.to.ch}cur=line;for(;merged=collapsedSpanAtEnd(cur);){var found$1=merged.find(0,!0);len-=cur.text.length-found$1.from.ch;cur=found$1.to.line;len+=cur.text.length-found$1.to.ch}return len}function findMaxLine(cm){var d=cm.display,doc=cm.doc;d.maxLine=getLine(doc,doc.first);d.maxLineLength=lineLength(d.maxLine);d.maxLineChanged=!0;doc.iter(function(line){var len=lineLength(line);if(len>d.maxLineLength){d.maxLineLength=len;d.maxLine=line}})}function iterateBidiSections(order,from,to,f){if(!order)return f(from,to,"ltr");for(var found=!1,i=0;i<order.length;++i){var part=order[i];if(part.from<to&&part.to>from||from==to&&part.to==from){f(Math.max(part.from,from),Math.min(part.to,to),1==part.level?"rtl":"ltr");found=!0}}found||f(from,to,"ltr")}function bidiLeft(part){return part.level%2?part.to:part.from}function bidiRight(part){return part.level%2?part.from:part.to}function lineLeft(line){var order=getOrder(line);return order?bidiLeft(order[0]):0}function lineRight(line){var order=getOrder(line);return order?bidiRight(lst(order)):line.text.length}function compareBidiLevel(order,a,b){var linedir=order[0].level;return a==linedir||b!=linedir&&a<b}function getBidiPartAt(order,pos){var found;bidiOther=null;for(var i=0;i<order.length;++i){var cur=order[i];if(cur.from<pos&&cur.to>pos)return i;if(cur.from==pos||cur.to==pos){if(null!=found){if(compareBidiLevel(order,cur.level,order[found].level)){cur.from!=cur.to&&(bidiOther=found);return i}cur.from!=cur.to&&(bidiOther=i);return found}found=i}}return found}function moveInLine(line,pos,dir,byUnit){if(!byUnit)return pos+dir;do pos+=dir;while(pos>0&&isExtendingChar(line.text.charAt(pos)));return pos}function moveVisually(line,start,dir,byUnit){var bidi=getOrder(line);if(!bidi)return moveLogically(line,start,dir,byUnit);for(var pos=getBidiPartAt(bidi,start),part=bidi[pos],target=moveInLine(line,start,part.level%2?-dir:dir,byUnit);;){if(target>part.from&&target<part.to)return target;if(target==part.from||target==part.to){if(getBidiPartAt(bidi,target)==pos)return target;part=bidi[pos+=dir];return dir>0==part.level%2?part.to:part.from}part=bidi[pos+=dir];if(!part)return null;target=dir>0==part.level%2?moveInLine(line,part.to,-1,byUnit):moveInLine(line,part.from,1,byUnit)}}function moveLogically(line,start,dir,byUnit){var target=start+dir;if(byUnit)for(;target>0&&isExtendingChar(line.text.charAt(target));)target+=dir;return target<0||target>line.text.length?null:target}function getOrder(line){var order=line.order;null==order&&(order=line.order=bidiOrdering(line.text));return order}function getHandlers(emitter,type){return emitter._handlers&&emitter._handlers[type]||noHandlers}function off(emitter,type,f){if(emitter.removeEventListener)emitter.removeEventListener(type,f,!1);else if(emitter.detachEvent)emitter.detachEvent("on"+type,f);else{var map=emitter._handlers,arr=map&&map[type];if(arr){var index=indexOf(arr,f);index>-1&&(map[type]=arr.slice(0,index).concat(arr.slice(index+1)))}}}function signal(emitter,type){var handlers=getHandlers(emitter,type);if(handlers.length)for(var args=Array.prototype.slice.call(arguments,2),i=0;i<handlers.length;++i)handlers[i].apply(null,args)}function signalDOMEvent(cm,e,override){"string"==typeof e&&(e={type:e,preventDefault:function(){this.defaultPrevented=!0}});signal(cm,override||e.type,cm,e);return e_defaultPrevented(e)||e.codemirrorIgnore}function signalCursorActivity(cm){var arr=cm._handlers&&cm._handlers.cursorActivity;if(arr)for(var set=cm.curOp.cursorActivityHandlers||(cm.curOp.cursorActivityHandlers=[]),i=0;i<arr.length;++i)indexOf(set,arr[i])==-1&&set.push(arr[i])}function hasHandler(emitter,type){return getHandlers(emitter,type).length>0}function eventMixin(ctor){ctor.prototype.on=function(type,f){on(this,type,f)};ctor.prototype.off=function(type,f){off(this,type,f)}}function e_preventDefault(e){e.preventDefault?e.preventDefault():e.returnValue=!1}function e_stopPropagation(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0}function e_defaultPrevented(e){return null!=e.defaultPrevented?e.defaultPrevented:0==e.returnValue}function e_stop(e){e_preventDefault(e);e_stopPropagation(e)}function e_target(e){return e.target||e.srcElement}function e_button(e){var b=e.which;null==b&&(1&e.button?b=1:2&e.button?b=3:4&e.button&&(b=2));mac&&e.ctrlKey&&1==b&&(b=3);return b}function zeroWidthElement(measure){if(null==zwspSupported){var test=elt("span","​");removeChildrenAndAdd(measure,elt("span",[test,document.createTextNode("x")]));0!=measure.firstChild.offsetHeight&&(zwspSupported=test.offsetWidth<=1&&test.offsetHeight>2&&!(ie&&ie_version<8))}var node=zwspSupported?elt("span","​"):elt("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px");node.setAttribute("cm-text","");return node}function hasBadBidiRects(measure){if(null!=badBidiRects)return badBidiRects;var txt=removeChildrenAndAdd(measure,document.createTextNode("AخA")),r0=range(txt,0,1).getBoundingClientRect(),r1=range(txt,1,2).getBoundingClientRect();removeChildren(measure);return!(!r0||r0.left==r0.right)&&(badBidiRects=r1.right-r0.right<3)}function hasBadZoomedRects(measure){if(null!=badZoomedRects)return badZoomedRects;var node=removeChildrenAndAdd(measure,elt("span","x")),normal=node.getBoundingClientRect(),fromRange=range(node,0,1).getBoundingClientRect();return badZoomedRects=Math.abs(normal.left-fromRange.left)>1}function defineMode(name,mode){arguments.length>2&&(mode.dependencies=Array.prototype.slice.call(arguments,2));modes[name]=mode}function defineMIME(mime,spec){mimeModes[mime]=spec}function resolveMode(spec){if("string"==typeof spec&&mimeModes.hasOwnProperty(spec))spec=mimeModes[spec];else if(spec&&"string"==typeof spec.name&&mimeModes.hasOwnProperty(spec.name)){var found=mimeModes[spec.name];"string"==typeof found&&(found={name:found});spec=createObj(found,spec);spec.name=found.name}else{if("string"==typeof spec&&/^[\w\-]+\/[\w\-]+\+xml$/.test(spec))return resolveMode("application/xml");if("string"==typeof spec&&/^[\w\-]+\/[\w\-]+\+json$/.test(spec))return resolveMode("application/json")}return"string"==typeof spec?{name:spec}:spec||{name:"null"}}function getMode(options,spec){spec=resolveMode(spec);var mfactory=modes[spec.name];if(!mfactory)return getMode(options,"text/plain");var modeObj=mfactory(options,spec);if(modeExtensions.hasOwnProperty(spec.name)){var exts=modeExtensions[spec.name];for(var prop in exts)if(exts.hasOwnProperty(prop)){modeObj.hasOwnProperty(prop)&&(modeObj["_"+prop]=modeObj[prop]);modeObj[prop]=exts[prop]}}modeObj.name=spec.name;spec.helperType&&(modeObj.helperType=spec.helperType);if(spec.modeProps)for(var prop$1 in spec.modeProps)modeObj[prop$1]=spec.modeProps[prop$1];return modeObj}function extendMode(mode,properties){var exts=modeExtensions.hasOwnProperty(mode)?modeExtensions[mode]:modeExtensions[mode]={};copyObj(properties,exts)}function copyState(mode,state){if(state===!0)return state;if(mode.copyState)return mode.copyState(state);var nstate={};for(var n in state){var val=state[n];val instanceof Array&&(val=val.concat([]));nstate[n]=val}return nstate}function innerMode(mode,state){for(var info;mode.innerMode;){info=mode.innerMode(state);if(!info||info.mode==mode)break;state=info.state;mode=info.mode}return info||{mode:mode,state:state}}function startState(mode,a1,a2){return!mode.startState||mode.startState(a1,a2)}function highlightLine(cm,line,state,forceToEnd){var st=[cm.state.modeGen],lineClasses={};runMode(cm,line.text,cm.doc.mode,state,function(end,style){return st.push(end,style)},lineClasses,forceToEnd);for(var loop=function(o){var overlay=cm.state.overlays[o],i=1,at=0;runMode(cm,line.text,overlay.mode,!0,function(end,style){for(var start=i;at<end;){var i_end=st[i];i_end>end&&st.splice(i,1,end,st[i+1],i_end);i+=2;at=Math.min(end,i_end)}if(style)if(overlay.opaque){st.splice(start,i-start,end,"overlay "+style);i=start+2}else for(;start<i;start+=2){var cur=st[start+1];st[start+1]=(cur?cur+" ":"")+"overlay "+style}},lineClasses)},o=0;o<cm.state.overlays.length;++o)loop(o);return{styles:st,classes:lineClasses.bgClass||lineClasses.textClass?lineClasses:null}}function getLineStyles(cm,line,updateFrontier){if(!line.styles||line.styles[0]!=cm.state.modeGen){var state=getStateBefore(cm,lineNo(line)),result=highlightLine(cm,line,line.text.length>cm.options.maxHighlightLength?copyState(cm.doc.mode,state):state);line.stateAfter=state;line.styles=result.styles;result.classes?line.styleClasses=result.classes:line.styleClasses&&(line.styleClasses=null);updateFrontier===cm.doc.frontier&&cm.doc.frontier++}return line.styles}function getStateBefore(cm,n,precise){var doc=cm.doc,display=cm.display;if(!doc.mode.startState)return!0;var pos=findStartLine(cm,n,precise),state=pos>doc.first&&getLine(doc,pos-1).stateAfter;state=state?copyState(doc.mode,state):startState(doc.mode);doc.iter(pos,n,function(line){processLine(cm,line.text,state);var save=pos==n-1||pos%5==0||pos>=display.viewFrom&&pos<display.viewTo;line.stateAfter=save?copyState(doc.mode,state):null;++pos});precise&&(doc.frontier=pos);return state}function processLine(cm,text,state,startAt){var mode=cm.doc.mode,stream=new StringStream(text,cm.options.tabSize);stream.start=stream.pos=startAt||0;""==text&&callBlankLine(mode,state);for(;!stream.eol();){readToken(mode,stream,state);stream.start=stream.pos}}function callBlankLine(mode,state){if(mode.blankLine)return mode.blankLine(state);if(mode.innerMode){var inner=innerMode(mode,state);return inner.mode.blankLine?inner.mode.blankLine(inner.state):void 0}}function readToken(mode,stream,state,inner){for(var i=0;i<10;i++){inner&&(inner[0]=innerMode(mode,state).mode);var style=mode.token(stream,state);if(stream.pos>stream.start)return style}throw new Error("Mode "+mode.name+" failed to advance stream.")}function takeToken(cm,pos,precise,asArray){var style,getObj=function(copy){return{start:stream.start,end:stream.pos,string:stream.current(),type:style||null,state:copy?copyState(doc.mode,state):state}},doc=cm.doc,mode=doc.mode;pos=clipPos(doc,pos);var tokens,line=getLine(doc,pos.line),state=getStateBefore(cm,pos.line,precise),stream=new StringStream(line.text,cm.options.tabSize);asArray&&(tokens=[]);for(;(asArray||stream.pos<pos.ch)&&!stream.eol();){stream.start=stream.pos;style=readToken(mode,stream,state);asArray&&tokens.push(getObj(!0))}return asArray?tokens:getObj()}function extractLineClasses(type,output){if(type)for(;;){var lineClass=type.match(/(?:^|\s+)line-(background-)?(\S+)/);if(!lineClass)break;type=type.slice(0,lineClass.index)+type.slice(lineClass.index+lineClass[0].length);var prop=lineClass[1]?"bgClass":"textClass";null==output[prop]?output[prop]=lineClass[2]:new RegExp("(?:^|s)"+lineClass[2]+"(?:$|s)").test(output[prop])||(output[prop]+=" "+lineClass[2])}return type}function runMode(cm,text,mode,state,f,lineClasses,forceToEnd){var flattenSpans=mode.flattenSpans;null==flattenSpans&&(flattenSpans=cm.options.flattenSpans);var style,curStart=0,curStyle=null,stream=new StringStream(text,cm.options.tabSize),inner=cm.options.addModeClass&&[null];""==text&&extractLineClasses(callBlankLine(mode,state),lineClasses);for(;!stream.eol();){if(stream.pos>cm.options.maxHighlightLength){flattenSpans=!1;forceToEnd&&processLine(cm,text,state,stream.pos);stream.pos=text.length;style=null}else style=extractLineClasses(readToken(mode,stream,state,inner),lineClasses);if(inner){var mName=inner[0].name;mName&&(style="m-"+(style?mName+" "+style:mName))}if(!flattenSpans||curStyle!=style){for(;curStart<stream.start;){curStart=Math.min(stream.start,curStart+5e3);f(curStart,curStyle)}curStyle=style}stream.start=stream.pos}for(;curStart<stream.pos;){var pos=Math.min(stream.pos,curStart+5e3);f(pos,curStyle);curStart=pos}}function findStartLine(cm,n,precise){for(var minindent,minline,doc=cm.doc,lim=precise?-1:n-(cm.doc.mode.innerMode?1e3:100),search=n;search>lim;--search){if(search<=doc.first)return doc.first;var line=getLine(doc,search-1);if(line.stateAfter&&(!precise||search<=doc.frontier))return search;var indented=countColumn(line.text,null,cm.options.tabSize);if(null==minline||minindent>indented){minline=search-1;minindent=indented}}return minline}function Line(text,markedSpans,estimateHeight){this.text=text;attachMarkedSpans(this,markedSpans);this.height=estimateHeight?estimateHeight(this):1}function updateLine(line,text,markedSpans,estimateHeight){line.text=text;line.stateAfter&&(line.stateAfter=null);line.styles&&(line.styles=null);null!=line.order&&(line.order=null);detachMarkedSpans(line);attachMarkedSpans(line,markedSpans);var estHeight=estimateHeight?estimateHeight(line):1;estHeight!=line.height&&updateLineHeight(line,estHeight)}function cleanUpLine(line){line.parent=null;detachMarkedSpans(line)}function interpretTokenStyle(style,options){if(!style||/^\s*$/.test(style))return null;var cache=options.addModeClass?styleToClassCacheWithMode:styleToClassCache;return cache[style]||(cache[style]=style.replace(/\S+/g,"cm-$&"))}function buildLineContent(cm,lineView){var content=elt("span",null,null,webkit?"padding-right: .1px":null),builder={pre:elt("pre",[content],"CodeMirror-line"),content:content,col:0,pos:0,cm:cm,trailingSpace:!1,splitSpaces:(ie||webkit)&&cm.getOption("lineWrapping")};lineView.measure={};for(var i=0;i<=(lineView.rest?lineView.rest.length:0);i++){var line=i?lineView.rest[i-1]:lineView.line,order=void 0;builder.pos=0;builder.addToken=buildToken;hasBadBidiRects(cm.display.measure)&&(order=getOrder(line))&&(builder.addToken=buildTokenBadBidi(builder.addToken,order));builder.map=[];var allowFrontierUpdate=lineView!=cm.display.externalMeasured&&lineNo(line);insertLineContent(line,builder,getLineStyles(cm,line,allowFrontierUpdate));if(line.styleClasses){line.styleClasses.bgClass&&(builder.bgClass=joinClasses(line.styleClasses.bgClass,builder.bgClass||""));line.styleClasses.textClass&&(builder.textClass=joinClasses(line.styleClasses.textClass,builder.textClass||""))}0==builder.map.length&&builder.map.push(0,0,builder.content.appendChild(zeroWidthElement(cm.display.measure)));if(0==i){lineView.measure.map=builder.map;lineView.measure.cache={}}else{(lineView.measure.maps||(lineView.measure.maps=[])).push(builder.map);(lineView.measure.caches||(lineView.measure.caches=[])).push({})}}if(webkit){var last=builder.content.lastChild;(/\bcm-tab\b/.test(last.className)||last.querySelector&&last.querySelector(".cm-tab"))&&(builder.content.className="cm-tab-wrap-hack")}signal(cm,"renderLine",cm,lineView.line,builder.pre);builder.pre.className&&(builder.textClass=joinClasses(builder.pre.className,builder.textClass||""));return builder}function defaultSpecialCharPlaceholder(ch){var token=elt("span","•","cm-invalidchar");token.title="\\u"+ch.charCodeAt(0).toString(16);token.setAttribute("aria-label",token.title);return token}function buildToken(builder,text,style,startStyle,endStyle,title,css){if(text){var content,displayText=builder.splitSpaces?splitSpaces(text,builder.trailingSpace):text,special=builder.cm.state.specialChars,mustWrap=!1;if(special.test(text)){content=document.createDocumentFragment();for(var pos=0;;){special.lastIndex=pos;var m=special.exec(text),skipped=m?m.index-pos:text.length-pos;if(skipped){var txt=document.createTextNode(displayText.slice(pos,pos+skipped));ie&&ie_version<9?content.appendChild(elt("span",[txt])):content.appendChild(txt);builder.map.push(builder.pos,builder.pos+skipped,txt);builder.col+=skipped;builder.pos+=skipped}if(!m)break;pos+=skipped+1;var txt$1=void 0;if("\t"==m[0]){var tabSize=builder.cm.options.tabSize,tabWidth=tabSize-builder.col%tabSize;txt$1=content.appendChild(elt("span",spaceStr(tabWidth),"cm-tab"));txt$1.setAttribute("role","presentation");txt$1.setAttribute("cm-text","\t");builder.col+=tabWidth}else if("\r"==m[0]||"\n"==m[0]){txt$1=content.appendChild(elt("span","\r"==m[0]?"␍":"␤","cm-invalidchar"));txt$1.setAttribute("cm-text",m[0]);builder.col+=1}else{txt$1=builder.cm.options.specialCharPlaceholder(m[0]);txt$1.setAttribute("cm-text",m[0]);ie&&ie_version<9?content.appendChild(elt("span",[txt$1])):content.appendChild(txt$1);builder.col+=1}builder.map.push(builder.pos,builder.pos+1,txt$1);builder.pos++}}else{builder.col+=text.length;content=document.createTextNode(displayText);builder.map.push(builder.pos,builder.pos+text.length,content);ie&&ie_version<9&&(mustWrap=!0);builder.pos+=text.length;
2
+ }builder.trailingSpace=32==displayText.charCodeAt(text.length-1);if(style||startStyle||endStyle||mustWrap||css){var fullStyle=style||"";startStyle&&(fullStyle+=startStyle);endStyle&&(fullStyle+=endStyle);var token=elt("span",[content],fullStyle,css);title&&(token.title=title);return builder.content.appendChild(token)}builder.content.appendChild(content)}}function splitSpaces(text,trailingBefore){if(text.length>1&&!/ /.test(text))return text;for(var spaceBefore=trailingBefore,result="",i=0;i<text.length;i++){var ch=text.charAt(i);" "!=ch||!spaceBefore||i!=text.length-1&&32!=text.charCodeAt(i+1)||(ch=" ");result+=ch;spaceBefore=" "==ch}return result}function buildTokenBadBidi(inner,order){return function(builder,text,style,startStyle,endStyle,title,css){style=style?style+" cm-force-border":"cm-force-border";for(var start=builder.pos,end=start+text.length;;){for(var part=void 0,i=0;i<order.length;i++){part=order[i];if(part.to>start&&part.from<=start)break}if(part.to>=end)return inner(builder,text,style,startStyle,endStyle,title,css);inner(builder,text.slice(0,part.to-start),style,startStyle,null,title,css);startStyle=null;text=text.slice(part.to-start);start=part.to}}}function buildCollapsedSpan(builder,size,marker,ignoreWidget){var widget=!ignoreWidget&&marker.widgetNode;widget&&builder.map.push(builder.pos,builder.pos+size,widget);if(!ignoreWidget&&builder.cm.display.input.needsContentAttribute){widget||(widget=builder.content.appendChild(document.createElement("span")));widget.setAttribute("cm-marker",marker.id)}if(widget){builder.cm.display.input.setUneditable(widget);builder.content.appendChild(widget)}builder.pos+=size;builder.trailingSpace=!1}function insertLineContent(line,builder,styles){var spans=line.markedSpans,allText=line.text,at=0;if(spans)for(var style,css,spanStyle,spanEndStyle,spanStartStyle,title,collapsed,len=allText.length,pos=0,i=1,text="",nextChange=0;;){if(nextChange==pos){spanStyle=spanEndStyle=spanStartStyle=title=css="";collapsed=null;nextChange=1/0;for(var foundBookmarks=[],endStyles=void 0,j=0;j<spans.length;++j){var sp=spans[j],m=sp.marker;if("bookmark"==m.type&&sp.from==pos&&m.widgetNode)foundBookmarks.push(m);else if(sp.from<=pos&&(null==sp.to||sp.to>pos||m.collapsed&&sp.to==pos&&sp.from==pos)){if(null!=sp.to&&sp.to!=pos&&nextChange>sp.to){nextChange=sp.to;spanEndStyle=""}m.className&&(spanStyle+=" "+m.className);m.css&&(css=(css?css+";":"")+m.css);m.startStyle&&sp.from==pos&&(spanStartStyle+=" "+m.startStyle);m.endStyle&&sp.to==nextChange&&(endStyles||(endStyles=[])).push(m.endStyle,sp.to);m.title&&!title&&(title=m.title);m.collapsed&&(!collapsed||compareCollapsedMarkers(collapsed.marker,m)<0)&&(collapsed=sp)}else sp.from>pos&&nextChange>sp.from&&(nextChange=sp.from)}if(endStyles)for(var j$1=0;j$1<endStyles.length;j$1+=2)endStyles[j$1+1]==nextChange&&(spanEndStyle+=" "+endStyles[j$1]);if(!collapsed||collapsed.from==pos)for(var j$2=0;j$2<foundBookmarks.length;++j$2)buildCollapsedSpan(builder,0,foundBookmarks[j$2]);if(collapsed&&(collapsed.from||0)==pos){buildCollapsedSpan(builder,(null==collapsed.to?len+1:collapsed.to)-pos,collapsed.marker,null==collapsed.from);if(null==collapsed.to)return;collapsed.to==pos&&(collapsed=!1)}}if(pos>=len)break;for(var upto=Math.min(len,nextChange);;){if(text){var end=pos+text.length;if(!collapsed){var tokenText=end>upto?text.slice(0,upto-pos):text;builder.addToken(builder,tokenText,style?style+spanStyle:spanStyle,spanStartStyle,pos+tokenText.length==nextChange?spanEndStyle:"",title,css)}if(end>=upto){text=text.slice(upto-pos);pos=upto;break}pos=end;spanStartStyle=""}text=allText.slice(at,at=styles[i++]);style=interpretTokenStyle(styles[i++],builder.cm.options)}}else for(var i$1=1;i$1<styles.length;i$1+=2)builder.addToken(builder,allText.slice(at,at=styles[i$1]),interpretTokenStyle(styles[i$1+1],builder.cm.options))}function LineView(doc,line,lineN){this.line=line;this.rest=visualLineContinued(line);this.size=this.rest?lineNo(lst(this.rest))-lineN+1:1;this.node=this.text=null;this.hidden=lineIsHidden(doc,line)}function buildViewArray(cm,from,to){for(var nextPos,array=[],pos=from;pos<to;pos=nextPos){var view=new LineView(cm.doc,getLine(cm.doc,pos),pos);nextPos=pos+view.size;array.push(view)}return array}function pushOperation(op){operationGroup?operationGroup.ops.push(op):op.ownsGroup=operationGroup={ops:[op],delayedCallbacks:[]}}function fireCallbacksForOps(group){var callbacks=group.delayedCallbacks,i=0;do{for(;i<callbacks.length;i++)callbacks[i].call(null);for(var j=0;j<group.ops.length;j++){var op=group.ops[j];if(op.cursorActivityHandlers)for(;op.cursorActivityCalled<op.cursorActivityHandlers.length;)op.cursorActivityHandlers[op.cursorActivityCalled++].call(null,op.cm)}}while(i<callbacks.length)}function finishOperation(op,endCb){var group=op.ownsGroup;if(group)try{fireCallbacksForOps(group)}finally{operationGroup=null;endCb(group)}}function signalLater(emitter,type){var arr=getHandlers(emitter,type);if(arr.length){var list,args=Array.prototype.slice.call(arguments,2);if(operationGroup)list=operationGroup.delayedCallbacks;else if(orphanDelayedCallbacks)list=orphanDelayedCallbacks;else{list=orphanDelayedCallbacks=[];setTimeout(fireOrphanDelayed,0)}for(var loop=function(i){list.push(function(){return arr[i].apply(null,args)})},i=0;i<arr.length;++i)loop(i)}}function fireOrphanDelayed(){var delayed=orphanDelayedCallbacks;orphanDelayedCallbacks=null;for(var i=0;i<delayed.length;++i)delayed[i]()}function updateLineForChanges(cm,lineView,lineN,dims){for(var j=0;j<lineView.changes.length;j++){var type=lineView.changes[j];"text"==type?updateLineText(cm,lineView):"gutter"==type?updateLineGutter(cm,lineView,lineN,dims):"class"==type?updateLineClasses(lineView):"widget"==type&&updateLineWidgets(cm,lineView,dims)}lineView.changes=null}function ensureLineWrapped(lineView){if(lineView.node==lineView.text){lineView.node=elt("div",null,null,"position: relative");lineView.text.parentNode&&lineView.text.parentNode.replaceChild(lineView.node,lineView.text);lineView.node.appendChild(lineView.text);ie&&ie_version<8&&(lineView.node.style.zIndex=2)}return lineView.node}function updateLineBackground(lineView){var cls=lineView.bgClass?lineView.bgClass+" "+(lineView.line.bgClass||""):lineView.line.bgClass;cls&&(cls+=" CodeMirror-linebackground");if(lineView.background)if(cls)lineView.background.className=cls;else{lineView.background.parentNode.removeChild(lineView.background);lineView.background=null}else if(cls){var wrap=ensureLineWrapped(lineView);lineView.background=wrap.insertBefore(elt("div",null,cls),wrap.firstChild)}}function getLineContent(cm,lineView){var ext=cm.display.externalMeasured;if(ext&&ext.line==lineView.line){cm.display.externalMeasured=null;lineView.measure=ext.measure;return ext.built}return buildLineContent(cm,lineView)}function updateLineText(cm,lineView){var cls=lineView.text.className,built=getLineContent(cm,lineView);lineView.text==lineView.node&&(lineView.node=built.pre);lineView.text.parentNode.replaceChild(built.pre,lineView.text);lineView.text=built.pre;if(built.bgClass!=lineView.bgClass||built.textClass!=lineView.textClass){lineView.bgClass=built.bgClass;lineView.textClass=built.textClass;updateLineClasses(lineView)}else cls&&(lineView.text.className=cls)}function updateLineClasses(lineView){updateLineBackground(lineView);lineView.line.wrapClass?ensureLineWrapped(lineView).className=lineView.line.wrapClass:lineView.node!=lineView.text&&(lineView.node.className="");var textClass=lineView.textClass?lineView.textClass+" "+(lineView.line.textClass||""):lineView.line.textClass;lineView.text.className=textClass||""}function updateLineGutter(cm,lineView,lineN,dims){if(lineView.gutter){lineView.node.removeChild(lineView.gutter);lineView.gutter=null}if(lineView.gutterBackground){lineView.node.removeChild(lineView.gutterBackground);lineView.gutterBackground=null}if(lineView.line.gutterClass){var wrap=ensureLineWrapped(lineView);lineView.gutterBackground=elt("div",null,"CodeMirror-gutter-background "+lineView.line.gutterClass,"left: "+(cm.options.fixedGutter?dims.fixedPos:-dims.gutterTotalWidth)+"px; width: "+dims.gutterTotalWidth+"px");wrap.insertBefore(lineView.gutterBackground,lineView.text)}var markers=lineView.line.gutterMarkers;if(cm.options.lineNumbers||markers){var wrap$1=ensureLineWrapped(lineView),gutterWrap=lineView.gutter=elt("div",null,"CodeMirror-gutter-wrapper","left: "+(cm.options.fixedGutter?dims.fixedPos:-dims.gutterTotalWidth)+"px");cm.display.input.setUneditable(gutterWrap);wrap$1.insertBefore(gutterWrap,lineView.text);lineView.line.gutterClass&&(gutterWrap.className+=" "+lineView.line.gutterClass);!cm.options.lineNumbers||markers&&markers["CodeMirror-linenumbers"]||(lineView.lineNumber=gutterWrap.appendChild(elt("div",lineNumberFor(cm.options,lineN),"CodeMirror-linenumber CodeMirror-gutter-elt","left: "+dims.gutterLeft["CodeMirror-linenumbers"]+"px; width: "+cm.display.lineNumInnerWidth+"px")));if(markers)for(var k=0;k<cm.options.gutters.length;++k){var id=cm.options.gutters[k],found=markers.hasOwnProperty(id)&&markers[id];found&&gutterWrap.appendChild(elt("div",[found],"CodeMirror-gutter-elt","left: "+dims.gutterLeft[id]+"px; width: "+dims.gutterWidth[id]+"px"))}}}function updateLineWidgets(cm,lineView,dims){lineView.alignable&&(lineView.alignable=null);for(var node=lineView.node.firstChild,next=void 0;node;node=next){next=node.nextSibling;"CodeMirror-linewidget"==node.className&&lineView.node.removeChild(node)}insertLineWidgets(cm,lineView,dims)}function buildLineElement(cm,lineView,lineN,dims){var built=getLineContent(cm,lineView);lineView.text=lineView.node=built.pre;built.bgClass&&(lineView.bgClass=built.bgClass);built.textClass&&(lineView.textClass=built.textClass);updateLineClasses(lineView);updateLineGutter(cm,lineView,lineN,dims);insertLineWidgets(cm,lineView,dims);return lineView.node}function insertLineWidgets(cm,lineView,dims){insertLineWidgetsFor(cm,lineView.line,lineView,dims,!0);if(lineView.rest)for(var i=0;i<lineView.rest.length;i++)insertLineWidgetsFor(cm,lineView.rest[i],lineView,dims,!1)}function insertLineWidgetsFor(cm,line,lineView,dims,allowAbove){if(line.widgets)for(var wrap=ensureLineWrapped(lineView),i=0,ws=line.widgets;i<ws.length;++i){var widget=ws[i],node=elt("div",[widget.node],"CodeMirror-linewidget");widget.handleMouseEvents||node.setAttribute("cm-ignore-events","true");positionLineWidget(widget,node,lineView,dims);cm.display.input.setUneditable(node);allowAbove&&widget.above?wrap.insertBefore(node,lineView.gutter||lineView.text):wrap.appendChild(node);signalLater(widget,"redraw")}}function positionLineWidget(widget,node,lineView,dims){if(widget.noHScroll){(lineView.alignable||(lineView.alignable=[])).push(node);var width=dims.wrapperWidth;node.style.left=dims.fixedPos+"px";if(!widget.coverGutter){width-=dims.gutterTotalWidth;node.style.paddingLeft=dims.gutterTotalWidth+"px"}node.style.width=width+"px"}if(widget.coverGutter){node.style.zIndex=5;node.style.position="relative";widget.noHScroll||(node.style.marginLeft=-dims.gutterTotalWidth+"px")}}function widgetHeight(widget){if(null!=widget.height)return widget.height;var cm=widget.doc.cm;if(!cm)return 0;if(!contains(document.body,widget.node)){var parentStyle="position: relative;";widget.coverGutter&&(parentStyle+="margin-left: -"+cm.display.gutters.offsetWidth+"px;");widget.noHScroll&&(parentStyle+="width: "+cm.display.wrapper.clientWidth+"px;");removeChildrenAndAdd(cm.display.measure,elt("div",[widget.node],null,parentStyle))}return widget.height=widget.node.parentNode.offsetHeight}function eventInWidget(display,e){for(var n=e_target(e);n!=display.wrapper;n=n.parentNode)if(!n||1==n.nodeType&&"true"==n.getAttribute("cm-ignore-events")||n.parentNode==display.sizer&&n!=display.mover)return!0}function paddingTop(display){return display.lineSpace.offsetTop}function paddingVert(display){return display.mover.offsetHeight-display.lineSpace.offsetHeight}function paddingH(display){if(display.cachedPaddingH)return display.cachedPaddingH;var e=removeChildrenAndAdd(display.measure,elt("pre","x")),style=window.getComputedStyle?window.getComputedStyle(e):e.currentStyle,data={left:parseInt(style.paddingLeft),right:parseInt(style.paddingRight)};isNaN(data.left)||isNaN(data.right)||(display.cachedPaddingH=data);return data}function scrollGap(cm){return scrollerGap-cm.display.nativeBarWidth}function displayWidth(cm){return cm.display.scroller.clientWidth-scrollGap(cm)-cm.display.barWidth}function displayHeight(cm){return cm.display.scroller.clientHeight-scrollGap(cm)-cm.display.barHeight}function ensureLineHeights(cm,lineView,rect){var wrapping=cm.options.lineWrapping,curWidth=wrapping&&displayWidth(cm);if(!lineView.measure.heights||wrapping&&lineView.measure.width!=curWidth){var heights=lineView.measure.heights=[];if(wrapping){lineView.measure.width=curWidth;for(var rects=lineView.text.firstChild.getClientRects(),i=0;i<rects.length-1;i++){var cur=rects[i],next=rects[i+1];Math.abs(cur.bottom-next.bottom)>2&&heights.push((cur.bottom+next.top)/2-rect.top)}}heights.push(rect.bottom-rect.top)}}function mapFromLineView(lineView,line,lineN){if(lineView.line==line)return{map:lineView.measure.map,cache:lineView.measure.cache};for(var i=0;i<lineView.rest.length;i++)if(lineView.rest[i]==line)return{map:lineView.measure.maps[i],cache:lineView.measure.caches[i]};for(var i$1=0;i$1<lineView.rest.length;i$1++)if(lineNo(lineView.rest[i$1])>lineN)return{map:lineView.measure.maps[i$1],cache:lineView.measure.caches[i$1],before:!0}}function updateExternalMeasurement(cm,line){line=visualLine(line);var lineN=lineNo(line),view=cm.display.externalMeasured=new LineView(cm.doc,line,lineN);view.lineN=lineN;var built=view.built=buildLineContent(cm,view);view.text=built.pre;removeChildrenAndAdd(cm.display.lineMeasure,built.pre);return view}function measureChar(cm,line,ch,bias){return measureCharPrepared(cm,prepareMeasureForLine(cm,line),ch,bias)}function findViewForLine(cm,lineN){if(lineN>=cm.display.viewFrom&&lineN<cm.display.viewTo)return cm.display.view[findViewIndex(cm,lineN)];var ext=cm.display.externalMeasured;return ext&&lineN>=ext.lineN&&lineN<ext.lineN+ext.size?ext:void 0}function prepareMeasureForLine(cm,line){var lineN=lineNo(line),view=findViewForLine(cm,lineN);if(view&&!view.text)view=null;else if(view&&view.changes){updateLineForChanges(cm,view,lineN,getDimensions(cm));cm.curOp.forceUpdate=!0}view||(view=updateExternalMeasurement(cm,line));var info=mapFromLineView(view,line,lineN);return{line:line,view:view,rect:null,map:info.map,cache:info.cache,before:info.before,hasHeights:!1}}function measureCharPrepared(cm,prepared,ch,bias,varHeight){prepared.before&&(ch=-1);var found,key=ch+(bias||"");if(prepared.cache.hasOwnProperty(key))found=prepared.cache[key];else{prepared.rect||(prepared.rect=prepared.view.text.getBoundingClientRect());if(!prepared.hasHeights){ensureLineHeights(cm,prepared.view,prepared.rect);prepared.hasHeights=!0}found=measureCharInner(cm,prepared,ch,bias);found.bogus||(prepared.cache[key]=found)}return{left:found.left,right:found.right,top:varHeight?found.rtop:found.top,bottom:varHeight?found.rbottom:found.bottom}}function nodeAndOffsetInLineMap(map,ch,bias){for(var node,start,end,collapse,mStart,mEnd,i=0;i<map.length;i+=3){mStart=map[i];mEnd=map[i+1];if(ch<mStart){start=0;end=1;collapse="left"}else if(ch<mEnd){start=ch-mStart;end=start+1}else if(i==map.length-3||ch==mEnd&&map[i+3]>ch){end=mEnd-mStart;start=end-1;ch>=mEnd&&(collapse="right")}if(null!=start){node=map[i+2];mStart==mEnd&&bias==(node.insertLeft?"left":"right")&&(collapse=bias);if("left"==bias&&0==start)for(;i&&map[i-2]==map[i-3]&&map[i-1].insertLeft;){node=map[(i-=3)+2];collapse="left"}if("right"==bias&&start==mEnd-mStart)for(;i<map.length-3&&map[i+3]==map[i+4]&&!map[i+5].insertLeft;){node=map[(i+=3)+2];collapse="right"}break}}return{node:node,start:start,end:end,collapse:collapse,coverStart:mStart,coverEnd:mEnd}}function getUsefulRect(rects,bias){var rect=nullRect;if("left"==bias)for(var i=0;i<rects.length&&(rect=rects[i]).left==rect.right;i++);else for(var i$1=rects.length-1;i$1>=0&&(rect=rects[i$1]).left==rect.right;i$1--);return rect}function measureCharInner(cm,prepared,ch,bias){var rect,place=nodeAndOffsetInLineMap(prepared.map,ch,bias),node=place.node,start=place.start,end=place.end,collapse=place.collapse;if(3==node.nodeType){for(var i$1=0;i$1<4;i$1++){for(;start&&isExtendingChar(prepared.line.text.charAt(place.coverStart+start));)--start;for(;place.coverStart+end<place.coverEnd&&isExtendingChar(prepared.line.text.charAt(place.coverStart+end));)++end;rect=ie&&ie_version<9&&0==start&&end==place.coverEnd-place.coverStart?node.parentNode.getBoundingClientRect():getUsefulRect(range(node,start,end).getClientRects(),bias);if(rect.left||rect.right||0==start)break;end=start;start-=1;collapse="right"}ie&&ie_version<11&&(rect=maybeUpdateRectForZooming(cm.display.measure,rect))}else{start>0&&(collapse=bias="right");var rects;rect=cm.options.lineWrapping&&(rects=node.getClientRects()).length>1?rects["right"==bias?rects.length-1:0]:node.getBoundingClientRect()}if(ie&&ie_version<9&&!start&&(!rect||!rect.left&&!rect.right)){var rSpan=node.parentNode.getClientRects()[0];rect=rSpan?{left:rSpan.left,right:rSpan.left+charWidth(cm.display),top:rSpan.top,bottom:rSpan.bottom}:nullRect}for(var rtop=rect.top-prepared.rect.top,rbot=rect.bottom-prepared.rect.top,mid=(rtop+rbot)/2,heights=prepared.view.measure.heights,i=0;i<heights.length-1&&!(mid<heights[i]);i++);var top=i?heights[i-1]:0,bot=heights[i],result={left:("right"==collapse?rect.right:rect.left)-prepared.rect.left,right:("left"==collapse?rect.left:rect.right)-prepared.rect.left,top:top,bottom:bot};rect.left||rect.right||(result.bogus=!0);if(!cm.options.singleCursorHeightPerLine){result.rtop=rtop;result.rbottom=rbot}return result}function maybeUpdateRectForZooming(measure,rect){if(!window.screen||null==screen.logicalXDPI||screen.logicalXDPI==screen.deviceXDPI||!hasBadZoomedRects(measure))return rect;var scaleX=screen.logicalXDPI/screen.deviceXDPI,scaleY=screen.logicalYDPI/screen.deviceYDPI;return{left:rect.left*scaleX,right:rect.right*scaleX,top:rect.top*scaleY,bottom:rect.bottom*scaleY}}function clearLineMeasurementCacheFor(lineView){if(lineView.measure){lineView.measure.cache={};lineView.measure.heights=null;if(lineView.rest)for(var i=0;i<lineView.rest.length;i++)lineView.measure.caches[i]={}}}function clearLineMeasurementCache(cm){cm.display.externalMeasure=null;removeChildren(cm.display.lineMeasure);for(var i=0;i<cm.display.view.length;i++)clearLineMeasurementCacheFor(cm.display.view[i])}function clearCaches(cm){clearLineMeasurementCache(cm);cm.display.cachedCharWidth=cm.display.cachedTextHeight=cm.display.cachedPaddingH=null;cm.options.lineWrapping||(cm.display.maxLineChanged=!0);cm.display.lineNumChars=null}function pageScrollX(){return window.pageXOffset||(document.documentElement||document.body).scrollLeft}function pageScrollY(){return window.pageYOffset||(document.documentElement||document.body).scrollTop}function intoCoordSystem(cm,lineObj,rect,context,includeWidgets){if(!includeWidgets&&lineObj.widgets)for(var i=0;i<lineObj.widgets.length;++i)if(lineObj.widgets[i].above){var size=widgetHeight(lineObj.widgets[i]);rect.top+=size;rect.bottom+=size}if("line"==context)return rect;context||(context="local");var yOff=heightAtLine(lineObj);"local"==context?yOff+=paddingTop(cm.display):yOff-=cm.display.viewOffset;if("page"==context||"window"==context){var lOff=cm.display.lineSpace.getBoundingClientRect();yOff+=lOff.top+("window"==context?0:pageScrollY());var xOff=lOff.left+("window"==context?0:pageScrollX());rect.left+=xOff;rect.right+=xOff}rect.top+=yOff;rect.bottom+=yOff;return rect}function fromCoordSystem(cm,coords,context){if("div"==context)return coords;var left=coords.left,top=coords.top;if("page"==context){left-=pageScrollX();top-=pageScrollY()}else if("local"==context||!context){var localBox=cm.display.sizer.getBoundingClientRect();left+=localBox.left;top+=localBox.top}var lineSpaceBox=cm.display.lineSpace.getBoundingClientRect();return{left:left-lineSpaceBox.left,top:top-lineSpaceBox.top}}function charCoords(cm,pos,context,lineObj,bias){lineObj||(lineObj=getLine(cm.doc,pos.line));return intoCoordSystem(cm,lineObj,measureChar(cm,lineObj,pos.ch,bias),context)}function cursorCoords(cm,pos,context,lineObj,preparedMeasure,varHeight){function get(ch,right){var m=measureCharPrepared(cm,preparedMeasure,ch,right?"right":"left",varHeight);right?m.left=m.right:m.right=m.left;return intoCoordSystem(cm,lineObj,m,context)}function getBidi(ch,partPos){var part=order[partPos],right=part.level%2;if(ch==bidiLeft(part)&&partPos&&part.level<order[partPos-1].level){part=order[--partPos];ch=bidiRight(part)-(part.level%2?0:1);right=!0}else if(ch==bidiRight(part)&&partPos<order.length-1&&part.level<order[partPos+1].level){part=order[++partPos];ch=bidiLeft(part)-part.level%2;right=!1}return right&&ch==part.to&&ch>part.from?get(ch-1):get(ch,right)}lineObj=lineObj||getLine(cm.doc,pos.line);preparedMeasure||(preparedMeasure=prepareMeasureForLine(cm,lineObj));var order=getOrder(lineObj),ch=pos.ch;if(!order)return get(ch);var partPos=getBidiPartAt(order,ch),val=getBidi(ch,partPos);null!=bidiOther&&(val.other=getBidi(ch,bidiOther));return val}function estimateCoords(cm,pos){var left=0;pos=clipPos(cm.doc,pos);cm.options.lineWrapping||(left=charWidth(cm.display)*pos.ch);var lineObj=getLine(cm.doc,pos.line),top=heightAtLine(lineObj)+paddingTop(cm.display);return{left:left,right:left,top:top,bottom:top+lineObj.height}}function PosWithInfo(line,ch,outside,xRel){var pos=Pos(line,ch);pos.xRel=xRel;outside&&(pos.outside=!0);return pos}function coordsChar(cm,x,y){var doc=cm.doc;y+=cm.display.viewOffset;if(y<0)return PosWithInfo(doc.first,0,!0,-1);var lineN=lineAtHeight(doc,y),last=doc.first+doc.size-1;if(lineN>last)return PosWithInfo(doc.first+doc.size-1,getLine(doc,last).text.length,!0,1);x<0&&(x=0);for(var lineObj=getLine(doc,lineN);;){var found=coordsCharInner(cm,lineObj,lineN,x,y),merged=collapsedSpanAtEnd(lineObj),mergedPos=merged&&merged.find(0,!0);if(!merged||!(found.ch>mergedPos.from.ch||found.ch==mergedPos.from.ch&&found.xRel>0))return found;lineN=lineNo(lineObj=mergedPos.to.line)}}function coordsCharInner(cm,lineObj,lineNo,x,y){function getX(ch){var sp=cursorCoords(cm,Pos(lineNo,ch),"line",lineObj,preparedMeasure);wrongLine=!0;if(innerOff>sp.bottom)return sp.left-adjust;if(innerOff<sp.top)return sp.left+adjust;wrongLine=!1;return sp.left}var innerOff=y-heightAtLine(lineObj),wrongLine=!1,adjust=2*cm.display.wrapper.clientWidth,preparedMeasure=prepareMeasureForLine(cm,lineObj),bidi=getOrder(lineObj),dist=lineObj.text.length,from=lineLeft(lineObj),to=lineRight(lineObj),fromX=getX(from),fromOutside=wrongLine,toX=getX(to),toOutside=wrongLine;if(x>toX)return PosWithInfo(lineNo,to,toOutside,1);for(;;){if(bidi?to==from||to==moveVisually(lineObj,from,1):to-from<=1){var ch=x<fromX||x-fromX<=toX-x?from:to,outside=ch==from?fromOutside:toOutside,xDiff=x-(ch==from?fromX:toX);if(toOutside&&!bidi&&!/\s/.test(lineObj.text.charAt(ch))&&xDiff>0&&ch<lineObj.text.length&&preparedMeasure.view.measure.heights.length>1){var charSize=measureCharPrepared(cm,preparedMeasure,ch,"right");if(innerOff<=charSize.bottom&&innerOff>=charSize.top&&Math.abs(x-charSize.right)<xDiff){outside=!1;ch++;xDiff=x-charSize.right}}for(;isExtendingChar(lineObj.text.charAt(ch));)++ch;var pos=PosWithInfo(lineNo,ch,outside,xDiff<-1?-1:xDiff>1?1:0);return pos}var step=Math.ceil(dist/2),middle=from+step;if(bidi){middle=from;for(var i=0;i<step;++i)middle=moveVisually(lineObj,middle,1)}var middleX=getX(middle);if(middleX>x){to=middle;toX=middleX;(toOutside=wrongLine)&&(toX+=1e3);dist=step}else{from=middle;fromX=middleX;fromOutside=wrongLine;dist-=step}}}function textHeight(display){if(null!=display.cachedTextHeight)return display.cachedTextHeight;if(null==measureText){measureText=elt("pre");for(var i=0;i<49;++i){measureText.appendChild(document.createTextNode("x"));measureText.appendChild(elt("br"))}measureText.appendChild(document.createTextNode("x"))}removeChildrenAndAdd(display.measure,measureText);var height=measureText.offsetHeight/50;height>3&&(display.cachedTextHeight=height);removeChildren(display.measure);return height||1}function charWidth(display){if(null!=display.cachedCharWidth)return display.cachedCharWidth;var anchor=elt("span","xxxxxxxxxx"),pre=elt("pre",[anchor]);removeChildrenAndAdd(display.measure,pre);var rect=anchor.getBoundingClientRect(),width=(rect.right-rect.left)/10;width>2&&(display.cachedCharWidth=width);return width||10}function getDimensions(cm){for(var d=cm.display,left={},width={},gutterLeft=d.gutters.clientLeft,n=d.gutters.firstChild,i=0;n;n=n.nextSibling,++i){left[cm.options.gutters[i]]=n.offsetLeft+n.clientLeft+gutterLeft;width[cm.options.gutters[i]]=n.clientWidth}return{fixedPos:compensateForHScroll(d),gutterTotalWidth:d.gutters.offsetWidth,gutterLeft:left,gutterWidth:width,wrapperWidth:d.wrapper.clientWidth}}function compensateForHScroll(display){return display.scroller.getBoundingClientRect().left-display.sizer.getBoundingClientRect().left}function estimateHeight(cm){var th=textHeight(cm.display),wrapping=cm.options.lineWrapping,perLine=wrapping&&Math.max(5,cm.display.scroller.clientWidth/charWidth(cm.display)-3);return function(line){if(lineIsHidden(cm.doc,line))return 0;var widgetsHeight=0;if(line.widgets)for(var i=0;i<line.widgets.length;i++)line.widgets[i].height&&(widgetsHeight+=line.widgets[i].height);return wrapping?widgetsHeight+(Math.ceil(line.text.length/perLine)||1)*th:widgetsHeight+th}}function estimateLineHeights(cm){var doc=cm.doc,est=estimateHeight(cm);doc.iter(function(line){var estHeight=est(line);estHeight!=line.height&&updateLineHeight(line,estHeight)})}function posFromMouse(cm,e,liberal,forRect){var display=cm.display;if(!liberal&&"true"==e_target(e).getAttribute("cm-not-content"))return null;var x,y,space=display.lineSpace.getBoundingClientRect();try{x=e.clientX-space.left;y=e.clientY-space.top}catch(e){return null}var line,coords=coordsChar(cm,x,y);if(forRect&&1==coords.xRel&&(line=getLine(cm.doc,coords.line).text).length==coords.ch){var colDiff=countColumn(line,line.length,cm.options.tabSize)-line.length;coords=Pos(coords.line,Math.max(0,Math.round((x-paddingH(cm.display).left)/charWidth(cm.display))-colDiff))}return coords}function findViewIndex(cm,n){if(n>=cm.display.viewTo)return null;n-=cm.display.viewFrom;if(n<0)return null;for(var view=cm.display.view,i=0;i<view.length;i++){n-=view[i].size;if(n<0)return i}}function updateSelection(cm){cm.display.input.showSelection(cm.display.input.prepareSelection())}function prepareSelection(cm,primary){for(var doc=cm.doc,result={},curFragment=result.cursors=document.createDocumentFragment(),selFragment=result.selection=document.createDocumentFragment(),i=0;i<doc.sel.ranges.length;i++)if(primary!==!1||i!=doc.sel.primIndex){var range=doc.sel.ranges[i];if(!(range.from().line>=cm.display.viewTo||range.to().line<cm.display.viewFrom)){var collapsed=range.empty();(collapsed||cm.options.showCursorWhenSelecting)&&drawSelectionCursor(cm,range.head,curFragment);collapsed||drawSelectionRange(cm,range,selFragment)}}return result}function drawSelectionCursor(cm,head,output){var pos=cursorCoords(cm,head,"div",null,null,!cm.options.singleCursorHeightPerLine),cursor=output.appendChild(elt("div"," ","CodeMirror-cursor"));cursor.style.left=pos.left+"px";cursor.style.top=pos.top+"px";cursor.style.height=Math.max(0,pos.bottom-pos.top)*cm.options.cursorHeight+"px";if(pos.other){var otherCursor=output.appendChild(elt("div"," ","CodeMirror-cursor CodeMirror-secondarycursor"));otherCursor.style.display="";otherCursor.style.left=pos.other.left+"px";otherCursor.style.top=pos.other.top+"px";otherCursor.style.height=.85*(pos.other.bottom-pos.other.top)+"px"}}function drawSelectionRange(cm,range,output){function add(left,top,width,bottom){top<0&&(top=0);top=Math.round(top);bottom=Math.round(bottom);fragment.appendChild(elt("div",null,"CodeMirror-selected","position: absolute; left: "+left+"px;\n top: "+top+"px; width: "+(null==width?rightSide-left:width)+"px;\n height: "+(bottom-top)+"px"))}function drawForLine(line,fromArg,toArg){function coords(ch,bias){return charCoords(cm,Pos(line,ch),"div",lineObj,bias)}var start,end,lineObj=getLine(doc,line),lineLen=lineObj.text.length;iterateBidiSections(getOrder(lineObj),fromArg||0,null==toArg?lineLen:toArg,function(from,to,dir){var rightPos,left,right,leftPos=coords(from,"left");if(from==to){rightPos=leftPos;left=right=leftPos.left}else{rightPos=coords(to-1,"right");if("rtl"==dir){var tmp=leftPos;leftPos=rightPos;rightPos=tmp}left=leftPos.left;right=rightPos.right}null==fromArg&&0==from&&(left=leftSide);if(rightPos.top-leftPos.top>3){add(left,leftPos.top,null,leftPos.bottom);left=leftSide;leftPos.bottom<rightPos.top&&add(left,leftPos.bottom,null,rightPos.top)}null==toArg&&to==lineLen&&(right=rightSide);(!start||leftPos.top<start.top||leftPos.top==start.top&&leftPos.left<start.left)&&(start=leftPos);(!end||rightPos.bottom>end.bottom||rightPos.bottom==end.bottom&&rightPos.right>end.right)&&(end=rightPos);left<leftSide+1&&(left=leftSide);add(left,rightPos.top,right-left,rightPos.bottom)});return{start:start,end:end}}var display=cm.display,doc=cm.doc,fragment=document.createDocumentFragment(),padding=paddingH(cm.display),leftSide=padding.left,rightSide=Math.max(display.sizerWidth,displayWidth(cm)-display.sizer.offsetLeft)-padding.right,sFrom=range.from(),sTo=range.to();if(sFrom.line==sTo.line)drawForLine(sFrom.line,sFrom.ch,sTo.ch);else{var fromLine=getLine(doc,sFrom.line),toLine=getLine(doc,sTo.line),singleVLine=visualLine(fromLine)==visualLine(toLine),leftEnd=drawForLine(sFrom.line,sFrom.ch,singleVLine?fromLine.text.length+1:null).end,rightStart=drawForLine(sTo.line,singleVLine?0:null,sTo.ch).start;if(singleVLine)if(leftEnd.top<rightStart.top-2){add(leftEnd.right,leftEnd.top,null,leftEnd.bottom);add(leftSide,rightStart.top,rightStart.left,rightStart.bottom)}else add(leftEnd.right,leftEnd.top,rightStart.left-leftEnd.right,leftEnd.bottom);leftEnd.bottom<rightStart.top&&add(leftSide,leftEnd.bottom,null,rightStart.top)}output.appendChild(fragment)}function restartBlink(cm){if(cm.state.focused){var display=cm.display;clearInterval(display.blinker);var on=!0;display.cursorDiv.style.visibility="";cm.options.cursorBlinkRate>0?display.blinker=setInterval(function(){return display.cursorDiv.style.visibility=(on=!on)?"":"hidden"},cm.options.cursorBlinkRate):cm.options.cursorBlinkRate<0&&(display.cursorDiv.style.visibility="hidden")}}function ensureFocus(cm){if(!cm.state.focused){cm.display.input.focus();onFocus(cm)}}function delayBlurEvent(cm){cm.state.delayingBlurEvent=!0;setTimeout(function(){if(cm.state.delayingBlurEvent){cm.state.delayingBlurEvent=!1;onBlur(cm)}},100)}function onFocus(cm,e){cm.state.delayingBlurEvent&&(cm.state.delayingBlurEvent=!1);if("nocursor"!=cm.options.readOnly){if(!cm.state.focused){signal(cm,"focus",cm,e);cm.state.focused=!0;addClass(cm.display.wrapper,"CodeMirror-focused");if(!cm.curOp&&cm.display.selForContextMenu!=cm.doc.sel){cm.display.input.reset();webkit&&setTimeout(function(){return cm.display.input.reset(!0)},20)}cm.display.input.receivedFocus()}restartBlink(cm)}}function onBlur(cm,e){if(!cm.state.delayingBlurEvent){if(cm.state.focused){signal(cm,"blur",cm,e);cm.state.focused=!1;rmClass(cm.display.wrapper,"CodeMirror-focused")}clearInterval(cm.display.blinker);setTimeout(function(){cm.state.focused||(cm.display.shift=!1)},150)}}function alignHorizontally(cm){var display=cm.display,view=display.view;if(display.alignWidgets||display.gutters.firstChild&&cm.options.fixedGutter){for(var comp=compensateForHScroll(display)-display.scroller.scrollLeft+cm.doc.scrollLeft,gutterW=display.gutters.offsetWidth,left=comp+"px",i=0;i<view.length;i++)if(!view[i].hidden){if(cm.options.fixedGutter){view[i].gutter&&(view[i].gutter.style.left=left);
3
+ view[i].gutterBackground&&(view[i].gutterBackground.style.left=left)}var align=view[i].alignable;if(align)for(var j=0;j<align.length;j++)align[j].style.left=left}cm.options.fixedGutter&&(display.gutters.style.left=comp+gutterW+"px")}}function maybeUpdateLineNumberWidth(cm){if(!cm.options.lineNumbers)return!1;var doc=cm.doc,last=lineNumberFor(cm.options,doc.first+doc.size-1),display=cm.display;if(last.length!=display.lineNumChars){var test=display.measure.appendChild(elt("div",[elt("div",last)],"CodeMirror-linenumber CodeMirror-gutter-elt")),innerW=test.firstChild.offsetWidth,padding=test.offsetWidth-innerW;display.lineGutter.style.width="";display.lineNumInnerWidth=Math.max(innerW,display.lineGutter.offsetWidth-padding)+1;display.lineNumWidth=display.lineNumInnerWidth+padding;display.lineNumChars=display.lineNumInnerWidth?last.length:-1;display.lineGutter.style.width=display.lineNumWidth+"px";updateGutterSpace(cm);return!0}return!1}function updateHeightsInViewport(cm){for(var display=cm.display,prevBottom=display.lineDiv.offsetTop,i=0;i<display.view.length;i++){var cur=display.view[i],height=void 0;if(!cur.hidden){if(ie&&ie_version<8){var bot=cur.node.offsetTop+cur.node.offsetHeight;height=bot-prevBottom;prevBottom=bot}else{var box=cur.node.getBoundingClientRect();height=box.bottom-box.top}var diff=cur.line.height-height;height<2&&(height=textHeight(display));if(diff>.001||diff<-.001){updateLineHeight(cur.line,height);updateWidgetHeight(cur.line);if(cur.rest)for(var j=0;j<cur.rest.length;j++)updateWidgetHeight(cur.rest[j])}}}}function updateWidgetHeight(line){if(line.widgets)for(var i=0;i<line.widgets.length;++i)line.widgets[i].height=line.widgets[i].node.parentNode.offsetHeight}function visibleLines(display,doc,viewport){var top=viewport&&null!=viewport.top?Math.max(0,viewport.top):display.scroller.scrollTop;top=Math.floor(top-paddingTop(display));var bottom=viewport&&null!=viewport.bottom?viewport.bottom:top+display.wrapper.clientHeight,from=lineAtHeight(doc,top),to=lineAtHeight(doc,bottom);if(viewport&&viewport.ensure){var ensureFrom=viewport.ensure.from.line,ensureTo=viewport.ensure.to.line;if(ensureFrom<from){from=ensureFrom;to=lineAtHeight(doc,heightAtLine(getLine(doc,ensureFrom))+display.wrapper.clientHeight)}else if(Math.min(ensureTo,doc.lastLine())>=to){from=lineAtHeight(doc,heightAtLine(getLine(doc,ensureTo))-display.wrapper.clientHeight);to=ensureTo}}return{from:from,to:Math.max(to,from+1)}}function setScrollTop(cm,val){if(!(Math.abs(cm.doc.scrollTop-val)<2)){cm.doc.scrollTop=val;gecko||updateDisplaySimple(cm,{top:val});cm.display.scroller.scrollTop!=val&&(cm.display.scroller.scrollTop=val);cm.display.scrollbars.setScrollTop(val);gecko&&updateDisplaySimple(cm);startWorker(cm,100)}}function setScrollLeft(cm,val,isScroller){if(!(isScroller?val==cm.doc.scrollLeft:Math.abs(cm.doc.scrollLeft-val)<2)){val=Math.min(val,cm.display.scroller.scrollWidth-cm.display.scroller.clientWidth);cm.doc.scrollLeft=val;alignHorizontally(cm);cm.display.scroller.scrollLeft!=val&&(cm.display.scroller.scrollLeft=val);cm.display.scrollbars.setScrollLeft(val)}}function wheelEventDelta(e){var dx=e.wheelDeltaX,dy=e.wheelDeltaY;null==dx&&e.detail&&e.axis==e.HORIZONTAL_AXIS&&(dx=e.detail);null==dy&&e.detail&&e.axis==e.VERTICAL_AXIS?dy=e.detail:null==dy&&(dy=e.wheelDelta);return{x:dx,y:dy}}function wheelEventPixels(e){var delta=wheelEventDelta(e);delta.x*=wheelPixelsPerUnit;delta.y*=wheelPixelsPerUnit;return delta}function onScrollWheel(cm,e){var delta=wheelEventDelta(e),dx=delta.x,dy=delta.y,display=cm.display,scroll=display.scroller,canScrollX=scroll.scrollWidth>scroll.clientWidth,canScrollY=scroll.scrollHeight>scroll.clientHeight;if(dx&&canScrollX||dy&&canScrollY){if(dy&&mac&&webkit)outer:for(var cur=e.target,view=display.view;cur!=scroll;cur=cur.parentNode)for(var i=0;i<view.length;i++)if(view[i].node==cur){cm.display.currentWheelTarget=cur;break outer}if(!dx||gecko||presto||null==wheelPixelsPerUnit){if(dy&&null!=wheelPixelsPerUnit){var pixels=dy*wheelPixelsPerUnit,top=cm.doc.scrollTop,bot=top+display.wrapper.clientHeight;pixels<0?top=Math.max(0,top+pixels-50):bot=Math.min(cm.doc.height,bot+pixels+50);updateDisplaySimple(cm,{top:top,bottom:bot})}if(wheelSamples<20)if(null==display.wheelStartX){display.wheelStartX=scroll.scrollLeft;display.wheelStartY=scroll.scrollTop;display.wheelDX=dx;display.wheelDY=dy;setTimeout(function(){if(null!=display.wheelStartX){var movedX=scroll.scrollLeft-display.wheelStartX,movedY=scroll.scrollTop-display.wheelStartY,sample=movedY&&display.wheelDY&&movedY/display.wheelDY||movedX&&display.wheelDX&&movedX/display.wheelDX;display.wheelStartX=display.wheelStartY=null;if(sample){wheelPixelsPerUnit=(wheelPixelsPerUnit*wheelSamples+sample)/(wheelSamples+1);++wheelSamples}}},200)}else{display.wheelDX+=dx;display.wheelDY+=dy}}else{dy&&canScrollY&&setScrollTop(cm,Math.max(0,Math.min(scroll.scrollTop+dy*wheelPixelsPerUnit,scroll.scrollHeight-scroll.clientHeight)));setScrollLeft(cm,Math.max(0,Math.min(scroll.scrollLeft+dx*wheelPixelsPerUnit,scroll.scrollWidth-scroll.clientWidth)));(!dy||dy&&canScrollY)&&e_preventDefault(e);display.wheelStartX=null}}}function measureForScrollbars(cm){var d=cm.display,gutterW=d.gutters.offsetWidth,docH=Math.round(cm.doc.height+paddingVert(cm.display));return{clientHeight:d.scroller.clientHeight,viewHeight:d.wrapper.clientHeight,scrollWidth:d.scroller.scrollWidth,clientWidth:d.scroller.clientWidth,viewWidth:d.wrapper.clientWidth,barLeft:cm.options.fixedGutter?gutterW:0,docHeight:docH,scrollHeight:docH+scrollGap(cm)+d.barHeight,nativeBarWidth:d.nativeBarWidth,gutterWidth:gutterW}}function updateScrollbars(cm,measure){measure||(measure=measureForScrollbars(cm));var startWidth=cm.display.barWidth,startHeight=cm.display.barHeight;updateScrollbarsInner(cm,measure);for(var i=0;i<4&&startWidth!=cm.display.barWidth||startHeight!=cm.display.barHeight;i++){startWidth!=cm.display.barWidth&&cm.options.lineWrapping&&updateHeightsInViewport(cm);updateScrollbarsInner(cm,measureForScrollbars(cm));startWidth=cm.display.barWidth;startHeight=cm.display.barHeight}}function updateScrollbarsInner(cm,measure){var d=cm.display,sizes=d.scrollbars.update(measure);d.sizer.style.paddingRight=(d.barWidth=sizes.right)+"px";d.sizer.style.paddingBottom=(d.barHeight=sizes.bottom)+"px";d.heightForcer.style.borderBottom=sizes.bottom+"px solid transparent";if(sizes.right&&sizes.bottom){d.scrollbarFiller.style.display="block";d.scrollbarFiller.style.height=sizes.bottom+"px";d.scrollbarFiller.style.width=sizes.right+"px"}else d.scrollbarFiller.style.display="";if(sizes.bottom&&cm.options.coverGutterNextToScrollbar&&cm.options.fixedGutter){d.gutterFiller.style.display="block";d.gutterFiller.style.height=sizes.bottom+"px";d.gutterFiller.style.width=measure.gutterWidth+"px"}else d.gutterFiller.style.display=""}function initScrollbars(cm){if(cm.display.scrollbars){cm.display.scrollbars.clear();cm.display.scrollbars.addClass&&rmClass(cm.display.wrapper,cm.display.scrollbars.addClass)}cm.display.scrollbars=new scrollbarModel[cm.options.scrollbarStyle](function(node){cm.display.wrapper.insertBefore(node,cm.display.scrollbarFiller);on(node,"mousedown",function(){cm.state.focused&&setTimeout(function(){return cm.display.input.focus()},0)});node.setAttribute("cm-not-content","true")},function(pos,axis){"horizontal"==axis?setScrollLeft(cm,pos):setScrollTop(cm,pos)},cm);cm.display.scrollbars.addClass&&addClass(cm.display.wrapper,cm.display.scrollbars.addClass)}function maybeScrollWindow(cm,coords){if(!signalDOMEvent(cm,"scrollCursorIntoView")){var display=cm.display,box=display.sizer.getBoundingClientRect(),doScroll=null;coords.top+box.top<0?doScroll=!0:coords.bottom+box.top>(window.innerHeight||document.documentElement.clientHeight)&&(doScroll=!1);if(null!=doScroll&&!phantom){var scrollNode=elt("div","​",null,"position: absolute;\n top: "+(coords.top-display.viewOffset-paddingTop(cm.display))+"px;\n height: "+(coords.bottom-coords.top+scrollGap(cm)+display.barHeight)+"px;\n left: "+coords.left+"px; width: 2px;");cm.display.lineSpace.appendChild(scrollNode);scrollNode.scrollIntoView(doScroll);cm.display.lineSpace.removeChild(scrollNode)}}}function scrollPosIntoView(cm,pos,end,margin){null==margin&&(margin=0);for(var coords,limit=0;limit<5;limit++){var changed=!1;coords=cursorCoords(cm,pos);var endCoords=end&&end!=pos?cursorCoords(cm,end):coords,scrollPos=calculateScrollPos(cm,Math.min(coords.left,endCoords.left),Math.min(coords.top,endCoords.top)-margin,Math.max(coords.left,endCoords.left),Math.max(coords.bottom,endCoords.bottom)+margin),startTop=cm.doc.scrollTop,startLeft=cm.doc.scrollLeft;if(null!=scrollPos.scrollTop){setScrollTop(cm,scrollPos.scrollTop);Math.abs(cm.doc.scrollTop-startTop)>1&&(changed=!0)}if(null!=scrollPos.scrollLeft){setScrollLeft(cm,scrollPos.scrollLeft);Math.abs(cm.doc.scrollLeft-startLeft)>1&&(changed=!0)}if(!changed)break}return coords}function scrollIntoView(cm,x1,y1,x2,y2){var scrollPos=calculateScrollPos(cm,x1,y1,x2,y2);null!=scrollPos.scrollTop&&setScrollTop(cm,scrollPos.scrollTop);null!=scrollPos.scrollLeft&&setScrollLeft(cm,scrollPos.scrollLeft)}function calculateScrollPos(cm,x1,y1,x2,y2){var display=cm.display,snapMargin=textHeight(cm.display);y1<0&&(y1=0);var screentop=cm.curOp&&null!=cm.curOp.scrollTop?cm.curOp.scrollTop:display.scroller.scrollTop,screen=displayHeight(cm),result={};y2-y1>screen&&(y2=y1+screen);var docBottom=cm.doc.height+paddingVert(display),atTop=y1<snapMargin,atBottom=y2>docBottom-snapMargin;if(y1<screentop)result.scrollTop=atTop?0:y1;else if(y2>screentop+screen){var newTop=Math.min(y1,(atBottom?docBottom:y2)-screen);newTop!=screentop&&(result.scrollTop=newTop)}var screenleft=cm.curOp&&null!=cm.curOp.scrollLeft?cm.curOp.scrollLeft:display.scroller.scrollLeft,screenw=displayWidth(cm)-(cm.options.fixedGutter?display.gutters.offsetWidth:0),tooWide=x2-x1>screenw;tooWide&&(x2=x1+screenw);x1<10?result.scrollLeft=0:x1<screenleft?result.scrollLeft=Math.max(0,x1-(tooWide?0:10)):x2>screenw+screenleft-3&&(result.scrollLeft=x2+(tooWide?0:10)-screenw);return result}function addToScrollPos(cm,left,top){null==left&&null==top||resolveScrollToPos(cm);null!=left&&(cm.curOp.scrollLeft=(null==cm.curOp.scrollLeft?cm.doc.scrollLeft:cm.curOp.scrollLeft)+left);null!=top&&(cm.curOp.scrollTop=(null==cm.curOp.scrollTop?cm.doc.scrollTop:cm.curOp.scrollTop)+top)}function ensureCursorVisible(cm){resolveScrollToPos(cm);var cur=cm.getCursor(),from=cur,to=cur;if(!cm.options.lineWrapping){from=cur.ch?Pos(cur.line,cur.ch-1):cur;to=Pos(cur.line,cur.ch+1)}cm.curOp.scrollToPos={from:from,to:to,margin:cm.options.cursorScrollMargin,isCursor:!0}}function resolveScrollToPos(cm){var range=cm.curOp.scrollToPos;if(range){cm.curOp.scrollToPos=null;var from=estimateCoords(cm,range.from),to=estimateCoords(cm,range.to),sPos=calculateScrollPos(cm,Math.min(from.left,to.left),Math.min(from.top,to.top)-range.margin,Math.max(from.right,to.right),Math.max(from.bottom,to.bottom)+range.margin);cm.scrollTo(sPos.scrollLeft,sPos.scrollTop)}}function startOperation(cm){cm.curOp={cm:cm,viewChanged:!1,startHeight:cm.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:++nextOpId};pushOperation(cm.curOp)}function endOperation(cm){var op=cm.curOp;finishOperation(op,function(group){for(var i=0;i<group.ops.length;i++)group.ops[i].cm.curOp=null;endOperations(group)})}function endOperations(group){for(var ops=group.ops,i=0;i<ops.length;i++)endOperation_R1(ops[i]);for(var i$1=0;i$1<ops.length;i$1++)endOperation_W1(ops[i$1]);for(var i$2=0;i$2<ops.length;i$2++)endOperation_R2(ops[i$2]);for(var i$3=0;i$3<ops.length;i$3++)endOperation_W2(ops[i$3]);for(var i$4=0;i$4<ops.length;i$4++)endOperation_finish(ops[i$4])}function endOperation_R1(op){var cm=op.cm,display=cm.display;maybeClipScrollbars(cm);op.updateMaxLine&&findMaxLine(cm);op.mustUpdate=op.viewChanged||op.forceUpdate||null!=op.scrollTop||op.scrollToPos&&(op.scrollToPos.from.line<display.viewFrom||op.scrollToPos.to.line>=display.viewTo)||display.maxLineChanged&&cm.options.lineWrapping;op.update=op.mustUpdate&&new DisplayUpdate(cm,op.mustUpdate&&{top:op.scrollTop,ensure:op.scrollToPos},op.forceUpdate)}function endOperation_W1(op){op.updatedDisplay=op.mustUpdate&&updateDisplayIfNeeded(op.cm,op.update)}function endOperation_R2(op){var cm=op.cm,display=cm.display;op.updatedDisplay&&updateHeightsInViewport(cm);op.barMeasure=measureForScrollbars(cm);if(display.maxLineChanged&&!cm.options.lineWrapping){op.adjustWidthTo=measureChar(cm,display.maxLine,display.maxLine.text.length).left+3;cm.display.sizerWidth=op.adjustWidthTo;op.barMeasure.scrollWidth=Math.max(display.scroller.clientWidth,display.sizer.offsetLeft+op.adjustWidthTo+scrollGap(cm)+cm.display.barWidth);op.maxScrollLeft=Math.max(0,display.sizer.offsetLeft+op.adjustWidthTo-displayWidth(cm))}(op.updatedDisplay||op.selectionChanged)&&(op.preparedSelection=display.input.prepareSelection(op.focus))}function endOperation_W2(op){var cm=op.cm;if(null!=op.adjustWidthTo){cm.display.sizer.style.minWidth=op.adjustWidthTo+"px";op.maxScrollLeft<cm.doc.scrollLeft&&setScrollLeft(cm,Math.min(cm.display.scroller.scrollLeft,op.maxScrollLeft),!0);cm.display.maxLineChanged=!1}var takeFocus=op.focus&&op.focus==activeElt()&&(!document.hasFocus||document.hasFocus());op.preparedSelection&&cm.display.input.showSelection(op.preparedSelection,takeFocus);(op.updatedDisplay||op.startHeight!=cm.doc.height)&&updateScrollbars(cm,op.barMeasure);op.updatedDisplay&&setDocumentHeight(cm,op.barMeasure);op.selectionChanged&&restartBlink(cm);cm.state.focused&&op.updateInput&&cm.display.input.reset(op.typing);takeFocus&&ensureFocus(op.cm)}function endOperation_finish(op){var cm=op.cm,display=cm.display,doc=cm.doc;op.updatedDisplay&&postUpdateDisplay(cm,op.update);null==display.wheelStartX||null==op.scrollTop&&null==op.scrollLeft&&!op.scrollToPos||(display.wheelStartX=display.wheelStartY=null);if(null!=op.scrollTop&&(display.scroller.scrollTop!=op.scrollTop||op.forceScroll)){doc.scrollTop=Math.max(0,Math.min(display.scroller.scrollHeight-display.scroller.clientHeight,op.scrollTop));display.scrollbars.setScrollTop(doc.scrollTop);display.scroller.scrollTop=doc.scrollTop}if(null!=op.scrollLeft&&(display.scroller.scrollLeft!=op.scrollLeft||op.forceScroll)){doc.scrollLeft=Math.max(0,Math.min(display.scroller.scrollWidth-display.scroller.clientWidth,op.scrollLeft));display.scrollbars.setScrollLeft(doc.scrollLeft);display.scroller.scrollLeft=doc.scrollLeft;alignHorizontally(cm)}if(op.scrollToPos){var coords=scrollPosIntoView(cm,clipPos(doc,op.scrollToPos.from),clipPos(doc,op.scrollToPos.to),op.scrollToPos.margin);op.scrollToPos.isCursor&&cm.state.focused&&maybeScrollWindow(cm,coords)}var hidden=op.maybeHiddenMarkers,unhidden=op.maybeUnhiddenMarkers;if(hidden)for(var i=0;i<hidden.length;++i)hidden[i].lines.length||signal(hidden[i],"hide");if(unhidden)for(var i$1=0;i$1<unhidden.length;++i$1)unhidden[i$1].lines.length&&signal(unhidden[i$1],"unhide");display.wrapper.offsetHeight&&(doc.scrollTop=cm.display.scroller.scrollTop);op.changeObjs&&signal(cm,"changes",cm,op.changeObjs);op.update&&op.update.finish()}function runInOp(cm,f){if(cm.curOp)return f();startOperation(cm);try{return f()}finally{endOperation(cm)}}function operation(cm,f){return function(){if(cm.curOp)return f.apply(cm,arguments);startOperation(cm);try{return f.apply(cm,arguments)}finally{endOperation(cm)}}}function methodOp(f){return function(){if(this.curOp)return f.apply(this,arguments);startOperation(this);try{return f.apply(this,arguments)}finally{endOperation(this)}}}function docMethodOp(f){return function(){var cm=this.cm;if(!cm||cm.curOp)return f.apply(this,arguments);startOperation(cm);try{return f.apply(this,arguments)}finally{endOperation(cm)}}}function regChange(cm,from,to,lendiff){null==from&&(from=cm.doc.first);null==to&&(to=cm.doc.first+cm.doc.size);lendiff||(lendiff=0);var display=cm.display;lendiff&&to<display.viewTo&&(null==display.updateLineNumbers||display.updateLineNumbers>from)&&(display.updateLineNumbers=from);cm.curOp.viewChanged=!0;if(from>=display.viewTo)sawCollapsedSpans&&visualLineNo(cm.doc,from)<display.viewTo&&resetView(cm);else if(to<=display.viewFrom)if(sawCollapsedSpans&&visualLineEndNo(cm.doc,to+lendiff)>display.viewFrom)resetView(cm);else{display.viewFrom+=lendiff;display.viewTo+=lendiff}else if(from<=display.viewFrom&&to>=display.viewTo)resetView(cm);else if(from<=display.viewFrom){var cut=viewCuttingPoint(cm,to,to+lendiff,1);if(cut){display.view=display.view.slice(cut.index);display.viewFrom=cut.lineN;display.viewTo+=lendiff}else resetView(cm)}else if(to>=display.viewTo){var cut$1=viewCuttingPoint(cm,from,from,-1);if(cut$1){display.view=display.view.slice(0,cut$1.index);display.viewTo=cut$1.lineN}else resetView(cm)}else{var cutTop=viewCuttingPoint(cm,from,from,-1),cutBot=viewCuttingPoint(cm,to,to+lendiff,1);if(cutTop&&cutBot){display.view=display.view.slice(0,cutTop.index).concat(buildViewArray(cm,cutTop.lineN,cutBot.lineN)).concat(display.view.slice(cutBot.index));display.viewTo+=lendiff}else resetView(cm)}var ext=display.externalMeasured;ext&&(to<ext.lineN?ext.lineN+=lendiff:from<ext.lineN+ext.size&&(display.externalMeasured=null))}function regLineChange(cm,line,type){cm.curOp.viewChanged=!0;var display=cm.display,ext=cm.display.externalMeasured;ext&&line>=ext.lineN&&line<ext.lineN+ext.size&&(display.externalMeasured=null);if(!(line<display.viewFrom||line>=display.viewTo)){var lineView=display.view[findViewIndex(cm,line)];if(null!=lineView.node){var arr=lineView.changes||(lineView.changes=[]);indexOf(arr,type)==-1&&arr.push(type)}}}function resetView(cm){cm.display.viewFrom=cm.display.viewTo=cm.doc.first;cm.display.view=[];cm.display.viewOffset=0}function viewCuttingPoint(cm,oldN,newN,dir){var diff,index=findViewIndex(cm,oldN),view=cm.display.view;if(!sawCollapsedSpans||newN==cm.doc.first+cm.doc.size)return{index:index,lineN:newN};for(var n=cm.display.viewFrom,i=0;i<index;i++)n+=view[i].size;if(n!=oldN){if(dir>0){if(index==view.length-1)return null;diff=n+view[index].size-oldN;index++}else diff=n-oldN;oldN+=diff;newN+=diff}for(;visualLineNo(cm.doc,newN)!=newN;){if(index==(dir<0?0:view.length-1))return null;newN+=dir*view[index-(dir<0?1:0)].size;index+=dir}return{index:index,lineN:newN}}function adjustView(cm,from,to){var display=cm.display,view=display.view;if(0==view.length||from>=display.viewTo||to<=display.viewFrom){display.view=buildViewArray(cm,from,to);display.viewFrom=from}else{display.viewFrom>from?display.view=buildViewArray(cm,from,display.viewFrom).concat(display.view):display.viewFrom<from&&(display.view=display.view.slice(findViewIndex(cm,from)));display.viewFrom=from;display.viewTo<to?display.view=display.view.concat(buildViewArray(cm,display.viewTo,to)):display.viewTo>to&&(display.view=display.view.slice(0,findViewIndex(cm,to)))}display.viewTo=to}function countDirtyView(cm){for(var view=cm.display.view,dirty=0,i=0;i<view.length;i++){var lineView=view[i];lineView.hidden||lineView.node&&!lineView.changes||++dirty}return dirty}function startWorker(cm,time){cm.doc.mode.startState&&cm.doc.frontier<cm.display.viewTo&&cm.state.highlight.set(time,bind(highlightWorker,cm))}function highlightWorker(cm){var doc=cm.doc;doc.frontier<doc.first&&(doc.frontier=doc.first);if(!(doc.frontier>=cm.display.viewTo)){var end=+new Date+cm.options.workTime,state=copyState(doc.mode,getStateBefore(cm,doc.frontier)),changedLines=[];doc.iter(doc.frontier,Math.min(doc.first+doc.size,cm.display.viewTo+500),function(line){if(doc.frontier>=cm.display.viewFrom){var oldStyles=line.styles,tooLong=line.text.length>cm.options.maxHighlightLength,highlighted=highlightLine(cm,line,tooLong?copyState(doc.mode,state):state,!0);line.styles=highlighted.styles;var oldCls=line.styleClasses,newCls=highlighted.classes;newCls?line.styleClasses=newCls:oldCls&&(line.styleClasses=null);for(var ischange=!oldStyles||oldStyles.length!=line.styles.length||oldCls!=newCls&&(!oldCls||!newCls||oldCls.bgClass!=newCls.bgClass||oldCls.textClass!=newCls.textClass),i=0;!ischange&&i<oldStyles.length;++i)ischange=oldStyles[i]!=line.styles[i];ischange&&changedLines.push(doc.frontier);line.stateAfter=tooLong?state:copyState(doc.mode,state)}else{line.text.length<=cm.options.maxHighlightLength&&processLine(cm,line.text,state);line.stateAfter=doc.frontier%5==0?copyState(doc.mode,state):null}++doc.frontier;if(+new Date>end){startWorker(cm,cm.options.workDelay);return!0}});changedLines.length&&runInOp(cm,function(){for(var i=0;i<changedLines.length;i++)regLineChange(cm,changedLines[i],"text")})}}function maybeClipScrollbars(cm){var display=cm.display;if(!display.scrollbarsClipped&&display.scroller.offsetWidth){display.nativeBarWidth=display.scroller.offsetWidth-display.scroller.clientWidth;display.heightForcer.style.height=scrollGap(cm)+"px";display.sizer.style.marginBottom=-display.nativeBarWidth+"px";display.sizer.style.borderRightWidth=scrollGap(cm)+"px";display.scrollbarsClipped=!0}}function updateDisplayIfNeeded(cm,update){var display=cm.display,doc=cm.doc;if(update.editorIsHidden){resetView(cm);return!1}if(!update.force&&update.visible.from>=display.viewFrom&&update.visible.to<=display.viewTo&&(null==display.updateLineNumbers||display.updateLineNumbers>=display.viewTo)&&display.renderedView==display.view&&0==countDirtyView(cm))return!1;if(maybeUpdateLineNumberWidth(cm)){resetView(cm);update.dims=getDimensions(cm)}var end=doc.first+doc.size,from=Math.max(update.visible.from-cm.options.viewportMargin,doc.first),to=Math.min(end,update.visible.to+cm.options.viewportMargin);display.viewFrom<from&&from-display.viewFrom<20&&(from=Math.max(doc.first,display.viewFrom));display.viewTo>to&&display.viewTo-to<20&&(to=Math.min(end,display.viewTo));if(sawCollapsedSpans){from=visualLineNo(cm.doc,from);to=visualLineEndNo(cm.doc,to)}var different=from!=display.viewFrom||to!=display.viewTo||display.lastWrapHeight!=update.wrapperHeight||display.lastWrapWidth!=update.wrapperWidth;adjustView(cm,from,to);display.viewOffset=heightAtLine(getLine(cm.doc,display.viewFrom));cm.display.mover.style.top=display.viewOffset+"px";var toUpdate=countDirtyView(cm);if(!different&&0==toUpdate&&!update.force&&display.renderedView==display.view&&(null==display.updateLineNumbers||display.updateLineNumbers>=display.viewTo))return!1;var focused=activeElt();toUpdate>4&&(display.lineDiv.style.display="none");patchDisplay(cm,display.updateLineNumbers,update.dims);toUpdate>4&&(display.lineDiv.style.display="");display.renderedView=display.view;focused&&activeElt()!=focused&&focused.offsetHeight&&focused.focus();removeChildren(display.cursorDiv);removeChildren(display.selectionDiv);display.gutters.style.height=display.sizer.style.minHeight=0;if(different){display.lastWrapHeight=update.wrapperHeight;display.lastWrapWidth=update.wrapperWidth;startWorker(cm,400)}display.updateLineNumbers=null;return!0}function postUpdateDisplay(cm,update){for(var viewport=update.viewport,first=!0;;first=!1){if(!first||!cm.options.lineWrapping||update.oldDisplayWidth==displayWidth(cm)){viewport&&null!=viewport.top&&(viewport={top:Math.min(cm.doc.height+paddingVert(cm.display)-displayHeight(cm),viewport.top)});update.visible=visibleLines(cm.display,cm.doc,viewport);if(update.visible.from>=cm.display.viewFrom&&update.visible.to<=cm.display.viewTo)break}if(!updateDisplayIfNeeded(cm,update))break;updateHeightsInViewport(cm);var barMeasure=measureForScrollbars(cm);updateSelection(cm);updateScrollbars(cm,barMeasure);setDocumentHeight(cm,barMeasure)}update.signal(cm,"update",cm);if(cm.display.viewFrom!=cm.display.reportedViewFrom||cm.display.viewTo!=cm.display.reportedViewTo){update.signal(cm,"viewportChange",cm,cm.display.viewFrom,cm.display.viewTo);cm.display.reportedViewFrom=cm.display.viewFrom;cm.display.reportedViewTo=cm.display.viewTo}}function updateDisplaySimple(cm,viewport){var update=new DisplayUpdate(cm,viewport);if(updateDisplayIfNeeded(cm,update)){updateHeightsInViewport(cm);postUpdateDisplay(cm,update);var barMeasure=measureForScrollbars(cm);updateSelection(cm);updateScrollbars(cm,barMeasure);setDocumentHeight(cm,barMeasure);update.finish()}}function patchDisplay(cm,updateNumbersFrom,dims){function rm(node){var next=node.nextSibling;webkit&&mac&&cm.display.currentWheelTarget==node?node.style.display="none":node.parentNode.removeChild(node);return next}for(var display=cm.display,lineNumbers=cm.options.lineNumbers,container=display.lineDiv,cur=container.firstChild,view=display.view,lineN=display.viewFrom,i=0;i<view.length;i++){var lineView=view[i];if(lineView.hidden);else if(lineView.node&&lineView.node.parentNode==container){for(;cur!=lineView.node;)cur=rm(cur);var updateNumber=lineNumbers&&null!=updateNumbersFrom&&updateNumbersFrom<=lineN&&lineView.lineNumber;if(lineView.changes){indexOf(lineView.changes,"gutter")>-1&&(updateNumber=!1);updateLineForChanges(cm,lineView,lineN,dims)}if(updateNumber){removeChildren(lineView.lineNumber);lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options,lineN)))}cur=lineView.node.nextSibling}else{var node=buildLineElement(cm,lineView,lineN,dims);container.insertBefore(node,cur)}lineN+=lineView.size}for(;cur;)cur=rm(cur)}function updateGutterSpace(cm){var width=cm.display.gutters.offsetWidth;cm.display.sizer.style.marginLeft=width+"px"}function setDocumentHeight(cm,measure){cm.display.sizer.style.minHeight=measure.docHeight+"px";cm.display.heightForcer.style.top=measure.docHeight+"px";cm.display.gutters.style.height=measure.docHeight+cm.display.barHeight+scrollGap(cm)+"px"}function updateGutters(cm){var gutters=cm.display.gutters,specs=cm.options.gutters;removeChildren(gutters);for(var i=0;i<specs.length;++i){var gutterClass=specs[i],gElt=gutters.appendChild(elt("div",null,"CodeMirror-gutter "+gutterClass));if("CodeMirror-linenumbers"==gutterClass){cm.display.lineGutter=gElt;gElt.style.width=(cm.display.lineNumWidth||1)+"px"}}gutters.style.display=i?"":"none";updateGutterSpace(cm)}function setGuttersForLineNumbers(options){var found=indexOf(options.gutters,"CodeMirror-linenumbers");if(found==-1&&options.lineNumbers)options.gutters=options.gutters.concat(["CodeMirror-linenumbers"]);else if(found>-1&&!options.lineNumbers){options.gutters=options.gutters.slice(0);options.gutters.splice(found,1)}}function Selection(ranges,primIndex){this.ranges=ranges;this.primIndex=primIndex}function Range(anchor,head){this.anchor=anchor;this.head=head}function normalizeSelection(ranges,primIndex){var prim=ranges[primIndex];ranges.sort(function(a,b){return cmp(a.from(),b.from())});primIndex=indexOf(ranges,prim);for(var i=1;i<ranges.length;i++){var cur=ranges[i],prev=ranges[i-1];if(cmp(prev.to(),cur.from())>=0){var from=minPos(prev.from(),cur.from()),to=maxPos(prev.to(),cur.to()),inv=prev.empty()?cur.from()==cur.head:prev.from()==prev.head;i<=primIndex&&--primIndex;ranges.splice(--i,2,new Range(inv?to:from,inv?from:to))}}return new Selection(ranges,primIndex)}function simpleSelection(anchor,head){return new Selection([new Range(anchor,head||anchor)],0)}function changeEnd(change){return change.text?Pos(change.from.line+change.text.length-1,lst(change.text).length+(1==change.text.length?change.from.ch:0)):change.to}function adjustForChange(pos,change){if(cmp(pos,change.from)<0)return pos;if(cmp(pos,change.to)<=0)return changeEnd(change);var line=pos.line+change.text.length-(change.to.line-change.from.line)-1,ch=pos.ch;pos.line==change.to.line&&(ch+=changeEnd(change).ch-change.to.ch);return Pos(line,ch)}function computeSelAfterChange(doc,change){for(var out=[],i=0;i<doc.sel.ranges.length;i++){var range=doc.sel.ranges[i];out.push(new Range(adjustForChange(range.anchor,change),adjustForChange(range.head,change)))}return normalizeSelection(out,doc.sel.primIndex)}function offsetPos(pos,old,nw){return pos.line==old.line?Pos(nw.line,pos.ch-old.ch+nw.ch):Pos(nw.line+(pos.line-old.line),pos.ch)}function computeReplacedSel(doc,changes,hint){for(var out=[],oldPrev=Pos(doc.first,0),newPrev=oldPrev,i=0;i<changes.length;i++){var change=changes[i],from=offsetPos(change.from,oldPrev,newPrev),to=offsetPos(changeEnd(change),oldPrev,newPrev);oldPrev=change.to;newPrev=to;if("around"==hint){var range=doc.sel.ranges[i],inv=cmp(range.head,range.anchor)<0;out[i]=new Range(inv?to:from,inv?from:to)}else out[i]=new Range(from,from)}return new Selection(out,doc.sel.primIndex)}function loadMode(cm){cm.doc.mode=getMode(cm.options,cm.doc.modeOption);resetModeState(cm)}function resetModeState(cm){cm.doc.iter(function(line){line.stateAfter&&(line.stateAfter=null);line.styles&&(line.styles=null)});cm.doc.frontier=cm.doc.first;startWorker(cm,100);cm.state.modeGen++;cm.curOp&&regChange(cm)}function isWholeLineUpdate(doc,change){return 0==change.from.ch&&0==change.to.ch&&""==lst(change.text)&&(!doc.cm||doc.cm.options.wholeLineUpdateBefore)}function updateDoc(doc,change,markedSpans,estimateHeight){function spansFor(n){return markedSpans?markedSpans[n]:null}function update(line,text,spans){updateLine(line,text,spans,estimateHeight);signalLater(line,"change",line,change)}function linesFor(start,end){for(var result=[],i=start;i<end;++i)result.push(new Line(text[i],spansFor(i),estimateHeight));return result}var from=change.from,to=change.to,text=change.text,firstLine=getLine(doc,from.line),lastLine=getLine(doc,to.line),lastText=lst(text),lastSpans=spansFor(text.length-1),nlines=to.line-from.line;if(change.full){doc.insert(0,linesFor(0,text.length));doc.remove(text.length,doc.size-text.length)}else if(isWholeLineUpdate(doc,change)){var added=linesFor(0,text.length-1);update(lastLine,lastLine.text,lastSpans);nlines&&doc.remove(from.line,nlines);added.length&&doc.insert(from.line,added)}else if(firstLine==lastLine)if(1==text.length)update(firstLine,firstLine.text.slice(0,from.ch)+lastText+firstLine.text.slice(to.ch),lastSpans);else{var added$1=linesFor(1,text.length-1);added$1.push(new Line(lastText+firstLine.text.slice(to.ch),lastSpans,estimateHeight));update(firstLine,firstLine.text.slice(0,from.ch)+text[0],spansFor(0));doc.insert(from.line+1,added$1)}else if(1==text.length){update(firstLine,firstLine.text.slice(0,from.ch)+text[0]+lastLine.text.slice(to.ch),spansFor(0));doc.remove(from.line+1,nlines)}else{update(firstLine,firstLine.text.slice(0,from.ch)+text[0],spansFor(0));update(lastLine,lastText+lastLine.text.slice(to.ch),lastSpans);var added$2=linesFor(1,text.length-1);nlines>1&&doc.remove(from.line+1,nlines-1);doc.insert(from.line+1,added$2)}signalLater(doc,"change",doc,change)}function linkedDocs(doc,f,sharedHistOnly){function propagate(doc,skip,sharedHist){if(doc.linked)for(var i=0;i<doc.linked.length;++i){var rel=doc.linked[i];if(rel.doc!=skip){var shared=sharedHist&&rel.sharedHist;if(!sharedHistOnly||shared){f(rel.doc,shared);propagate(rel.doc,doc,shared)}}}}propagate(doc,null,!0)}function attachDoc(cm,doc){if(doc.cm)throw new Error("This document is already in use.");cm.doc=doc;doc.cm=cm;estimateLineHeights(cm);loadMode(cm);cm.options.lineWrapping||findMaxLine(cm);cm.options.mode=doc.modeOption;regChange(cm)}function History(startGen){this.done=[];this.undone=[];this.undoDepth=1/0;this.lastModTime=this.lastSelTime=0;this.lastOp=this.lastSelOp=null;this.lastOrigin=this.lastSelOrigin=null;this.generation=this.maxGeneration=startGen||1}function historyChangeFromChange(doc,change){var histChange={from:copyPos(change.from),to:changeEnd(change),text:getBetween(doc,change.from,change.to)};attachLocalSpans(doc,histChange,change.from.line,change.to.line+1);linkedDocs(doc,function(doc){return attachLocalSpans(doc,histChange,change.from.line,change.to.line+1)},!0);return histChange}function clearSelectionEvents(array){for(;array.length;){var last=lst(array);if(!last.ranges)break;array.pop()}}function lastChangeEvent(hist,force){if(force){clearSelectionEvents(hist.done);
4
+ return lst(hist.done)}if(hist.done.length&&!lst(hist.done).ranges)return lst(hist.done);if(hist.done.length>1&&!hist.done[hist.done.length-2].ranges){hist.done.pop();return lst(hist.done)}}function addChangeToHistory(doc,change,selAfter,opId){var hist=doc.history;hist.undone.length=0;var cur,last,time=+new Date;if((hist.lastOp==opId||hist.lastOrigin==change.origin&&change.origin&&("+"==change.origin.charAt(0)&&doc.cm&&hist.lastModTime>time-doc.cm.options.historyEventDelay||"*"==change.origin.charAt(0)))&&(cur=lastChangeEvent(hist,hist.lastOp==opId))){last=lst(cur.changes);0==cmp(change.from,change.to)&&0==cmp(change.from,last.to)?last.to=changeEnd(change):cur.changes.push(historyChangeFromChange(doc,change))}else{var before=lst(hist.done);before&&before.ranges||pushSelectionToHistory(doc.sel,hist.done);cur={changes:[historyChangeFromChange(doc,change)],generation:hist.generation};hist.done.push(cur);for(;hist.done.length>hist.undoDepth;){hist.done.shift();hist.done[0].ranges||hist.done.shift()}}hist.done.push(selAfter);hist.generation=++hist.maxGeneration;hist.lastModTime=hist.lastSelTime=time;hist.lastOp=hist.lastSelOp=opId;hist.lastOrigin=hist.lastSelOrigin=change.origin;last||signal(doc,"historyAdded")}function selectionEventCanBeMerged(doc,origin,prev,sel){var ch=origin.charAt(0);return"*"==ch||"+"==ch&&prev.ranges.length==sel.ranges.length&&prev.somethingSelected()==sel.somethingSelected()&&new Date-doc.history.lastSelTime<=(doc.cm?doc.cm.options.historyEventDelay:500)}function addSelectionToHistory(doc,sel,opId,options){var hist=doc.history,origin=options&&options.origin;opId==hist.lastSelOp||origin&&hist.lastSelOrigin==origin&&(hist.lastModTime==hist.lastSelTime&&hist.lastOrigin==origin||selectionEventCanBeMerged(doc,origin,lst(hist.done),sel))?hist.done[hist.done.length-1]=sel:pushSelectionToHistory(sel,hist.done);hist.lastSelTime=+new Date;hist.lastSelOrigin=origin;hist.lastSelOp=opId;options&&options.clearRedo!==!1&&clearSelectionEvents(hist.undone)}function pushSelectionToHistory(sel,dest){var top=lst(dest);top&&top.ranges&&top.equals(sel)||dest.push(sel)}function attachLocalSpans(doc,change,from,to){var existing=change["spans_"+doc.id],n=0;doc.iter(Math.max(doc.first,from),Math.min(doc.first+doc.size,to),function(line){line.markedSpans&&((existing||(existing=change["spans_"+doc.id]={}))[n]=line.markedSpans);++n})}function removeClearedSpans(spans){if(!spans)return null;for(var out,i=0;i<spans.length;++i)spans[i].marker.explicitlyCleared?out||(out=spans.slice(0,i)):out&&out.push(spans[i]);return out?out.length?out:null:spans}function getOldSpans(doc,change){var found=change["spans_"+doc.id];if(!found)return null;for(var nw=[],i=0;i<change.text.length;++i)nw.push(removeClearedSpans(found[i]));return nw}function mergeOldSpans(doc,change){var old=getOldSpans(doc,change),stretched=stretchSpansOverChange(doc,change);if(!old)return stretched;if(!stretched)return old;for(var i=0;i<old.length;++i){var oldCur=old[i],stretchCur=stretched[i];if(oldCur&&stretchCur)spans:for(var j=0;j<stretchCur.length;++j){for(var span=stretchCur[j],k=0;k<oldCur.length;++k)if(oldCur[k].marker==span.marker)continue spans;oldCur.push(span)}else stretchCur&&(old[i]=stretchCur)}return old}function copyHistoryArray(events,newGroup,instantiateSel){for(var copy=[],i=0;i<events.length;++i){var event=events[i];if(event.ranges)copy.push(instantiateSel?Selection.prototype.deepCopy.call(event):event);else{var changes=event.changes,newChanges=[];copy.push({changes:newChanges});for(var j=0;j<changes.length;++j){var change=changes[j],m=void 0;newChanges.push({from:change.from,to:change.to,text:change.text});if(newGroup)for(var prop in change)if((m=prop.match(/^spans_(\d+)$/))&&indexOf(newGroup,Number(m[1]))>-1){lst(newChanges)[prop]=change[prop];delete change[prop]}}}}return copy}function extendRange(doc,range,head,other){if(doc.cm&&doc.cm.display.shift||doc.extend){var anchor=range.anchor;if(other){var posBefore=cmp(head,anchor)<0;if(posBefore!=cmp(other,anchor)<0){anchor=head;head=other}else posBefore!=cmp(head,other)<0&&(head=other)}return new Range(anchor,head)}return new Range(other||head,head)}function extendSelection(doc,head,other,options){setSelection(doc,new Selection([extendRange(doc,doc.sel.primary(),head,other)],0),options)}function extendSelections(doc,heads,options){for(var out=[],i=0;i<doc.sel.ranges.length;i++)out[i]=extendRange(doc,doc.sel.ranges[i],heads[i],null);var newSel=normalizeSelection(out,doc.sel.primIndex);setSelection(doc,newSel,options)}function replaceOneSelection(doc,i,range,options){var ranges=doc.sel.ranges.slice(0);ranges[i]=range;setSelection(doc,normalizeSelection(ranges,doc.sel.primIndex),options)}function setSimpleSelection(doc,anchor,head,options){setSelection(doc,simpleSelection(anchor,head),options)}function filterSelectionChange(doc,sel,options){var obj={ranges:sel.ranges,update:function(ranges){var this$1=this;this.ranges=[];for(var i=0;i<ranges.length;i++)this$1.ranges[i]=new Range(clipPos(doc,ranges[i].anchor),clipPos(doc,ranges[i].head))},origin:options&&options.origin};signal(doc,"beforeSelectionChange",doc,obj);doc.cm&&signal(doc.cm,"beforeSelectionChange",doc.cm,obj);return obj.ranges!=sel.ranges?normalizeSelection(obj.ranges,obj.ranges.length-1):sel}function setSelectionReplaceHistory(doc,sel,options){var done=doc.history.done,last=lst(done);if(last&&last.ranges){done[done.length-1]=sel;setSelectionNoUndo(doc,sel,options)}else setSelection(doc,sel,options)}function setSelection(doc,sel,options){setSelectionNoUndo(doc,sel,options);addSelectionToHistory(doc,doc.sel,doc.cm?doc.cm.curOp.id:NaN,options)}function setSelectionNoUndo(doc,sel,options){(hasHandler(doc,"beforeSelectionChange")||doc.cm&&hasHandler(doc.cm,"beforeSelectionChange"))&&(sel=filterSelectionChange(doc,sel,options));var bias=options&&options.bias||(cmp(sel.primary().head,doc.sel.primary().head)<0?-1:1);setSelectionInner(doc,skipAtomicInSelection(doc,sel,bias,!0));options&&options.scroll===!1||!doc.cm||ensureCursorVisible(doc.cm)}function setSelectionInner(doc,sel){if(!sel.equals(doc.sel)){doc.sel=sel;if(doc.cm){doc.cm.curOp.updateInput=doc.cm.curOp.selectionChanged=!0;signalCursorActivity(doc.cm)}signalLater(doc,"cursorActivity",doc)}}function reCheckSelection(doc){setSelectionInner(doc,skipAtomicInSelection(doc,doc.sel,null,!1),sel_dontScroll)}function skipAtomicInSelection(doc,sel,bias,mayClear){for(var out,i=0;i<sel.ranges.length;i++){var range=sel.ranges[i],old=sel.ranges.length==doc.sel.ranges.length&&doc.sel.ranges[i],newAnchor=skipAtomic(doc,range.anchor,old&&old.anchor,bias,mayClear),newHead=skipAtomic(doc,range.head,old&&old.head,bias,mayClear);if(out||newAnchor!=range.anchor||newHead!=range.head){out||(out=sel.ranges.slice(0,i));out[i]=new Range(newAnchor,newHead)}}return out?normalizeSelection(out,sel.primIndex):sel}function skipAtomicInner(doc,pos,oldPos,dir,mayClear){var line=getLine(doc,pos.line);if(line.markedSpans)for(var i=0;i<line.markedSpans.length;++i){var sp=line.markedSpans[i],m=sp.marker;if((null==sp.from||(m.inclusiveLeft?sp.from<=pos.ch:sp.from<pos.ch))&&(null==sp.to||(m.inclusiveRight?sp.to>=pos.ch:sp.to>pos.ch))){if(mayClear){signal(m,"beforeCursorEnter");if(m.explicitlyCleared){if(line.markedSpans){--i;continue}break}}if(!m.atomic)continue;if(oldPos){var near=m.find(dir<0?1:-1),diff=void 0;(dir<0?m.inclusiveRight:m.inclusiveLeft)&&(near=movePos(doc,near,-dir,near&&near.line==pos.line?line:null));if(near&&near.line==pos.line&&(diff=cmp(near,oldPos))&&(dir<0?diff<0:diff>0))return skipAtomicInner(doc,near,pos,dir,mayClear)}var far=m.find(dir<0?-1:1);(dir<0?m.inclusiveLeft:m.inclusiveRight)&&(far=movePos(doc,far,dir,far.line==pos.line?line:null));return far?skipAtomicInner(doc,far,pos,dir,mayClear):null}}return pos}function skipAtomic(doc,pos,oldPos,bias,mayClear){var dir=bias||1,found=skipAtomicInner(doc,pos,oldPos,dir,mayClear)||!mayClear&&skipAtomicInner(doc,pos,oldPos,dir,!0)||skipAtomicInner(doc,pos,oldPos,-dir,mayClear)||!mayClear&&skipAtomicInner(doc,pos,oldPos,-dir,!0);if(!found){doc.cantEdit=!0;return Pos(doc.first,0)}return found}function movePos(doc,pos,dir,line){return dir<0&&0==pos.ch?pos.line>doc.first?clipPos(doc,Pos(pos.line-1)):null:dir>0&&pos.ch==(line||getLine(doc,pos.line)).text.length?pos.line<doc.first+doc.size-1?Pos(pos.line+1,0):null:new Pos(pos.line,pos.ch+dir)}function selectAll(cm){cm.setSelection(Pos(cm.firstLine(),0),Pos(cm.lastLine()),sel_dontScroll)}function filterChange(doc,change,update){var obj={canceled:!1,from:change.from,to:change.to,text:change.text,origin:change.origin,cancel:function(){return obj.canceled=!0}};update&&(obj.update=function(from,to,text,origin){from&&(obj.from=clipPos(doc,from));to&&(obj.to=clipPos(doc,to));text&&(obj.text=text);void 0!==origin&&(obj.origin=origin)});signal(doc,"beforeChange",doc,obj);doc.cm&&signal(doc.cm,"beforeChange",doc.cm,obj);return obj.canceled?null:{from:obj.from,to:obj.to,text:obj.text,origin:obj.origin}}function makeChange(doc,change,ignoreReadOnly){if(doc.cm){if(!doc.cm.curOp)return operation(doc.cm,makeChange)(doc,change,ignoreReadOnly);if(doc.cm.state.suppressEdits)return}if(hasHandler(doc,"beforeChange")||doc.cm&&hasHandler(doc.cm,"beforeChange")){change=filterChange(doc,change,!0);if(!change)return}var split=sawReadOnlySpans&&!ignoreReadOnly&&removeReadOnlyRanges(doc,change.from,change.to);if(split)for(var i=split.length-1;i>=0;--i)makeChangeInner(doc,{from:split[i].from,to:split[i].to,text:i?[""]:change.text});else makeChangeInner(doc,change)}function makeChangeInner(doc,change){if(1!=change.text.length||""!=change.text[0]||0!=cmp(change.from,change.to)){var selAfter=computeSelAfterChange(doc,change);addChangeToHistory(doc,change,selAfter,doc.cm?doc.cm.curOp.id:NaN);makeChangeSingleDoc(doc,change,selAfter,stretchSpansOverChange(doc,change));var rebased=[];linkedDocs(doc,function(doc,sharedHist){if(!sharedHist&&indexOf(rebased,doc.history)==-1){rebaseHist(doc.history,change);rebased.push(doc.history)}makeChangeSingleDoc(doc,change,null,stretchSpansOverChange(doc,change))})}}function makeChangeFromHistory(doc,type,allowSelectionOnly){if(!doc.cm||!doc.cm.state.suppressEdits||allowSelectionOnly){for(var event,hist=doc.history,selAfter=doc.sel,source="undo"==type?hist.done:hist.undone,dest="undo"==type?hist.undone:hist.done,i=0;i<source.length;i++){event=source[i];if(allowSelectionOnly?event.ranges&&!event.equals(doc.sel):!event.ranges)break}if(i!=source.length){hist.lastOrigin=hist.lastSelOrigin=null;for(;;){event=source.pop();if(!event.ranges)break;pushSelectionToHistory(event,dest);if(allowSelectionOnly&&!event.equals(doc.sel)){setSelection(doc,event,{clearRedo:!1});return}selAfter=event}var antiChanges=[];pushSelectionToHistory(selAfter,dest);dest.push({changes:antiChanges,generation:hist.generation});hist.generation=event.generation||++hist.maxGeneration;for(var filter=hasHandler(doc,"beforeChange")||doc.cm&&hasHandler(doc.cm,"beforeChange"),loop=function(i){var change=event.changes[i];change.origin=type;if(filter&&!filterChange(doc,change,!1)){source.length=0;return{}}antiChanges.push(historyChangeFromChange(doc,change));var after=i?computeSelAfterChange(doc,change):lst(source);makeChangeSingleDoc(doc,change,after,mergeOldSpans(doc,change));!i&&doc.cm&&doc.cm.scrollIntoView({from:change.from,to:changeEnd(change)});var rebased=[];linkedDocs(doc,function(doc,sharedHist){if(!sharedHist&&indexOf(rebased,doc.history)==-1){rebaseHist(doc.history,change);rebased.push(doc.history)}makeChangeSingleDoc(doc,change,null,mergeOldSpans(doc,change))})},i$1=event.changes.length-1;i$1>=0;--i$1){var returned=loop(i$1);if(returned)return returned.v}}}}function shiftDoc(doc,distance){if(0!=distance){doc.first+=distance;doc.sel=new Selection(map(doc.sel.ranges,function(range){return new Range(Pos(range.anchor.line+distance,range.anchor.ch),Pos(range.head.line+distance,range.head.ch))}),doc.sel.primIndex);if(doc.cm){regChange(doc.cm,doc.first,doc.first-distance,distance);for(var d=doc.cm.display,l=d.viewFrom;l<d.viewTo;l++)regLineChange(doc.cm,l,"gutter")}}}function makeChangeSingleDoc(doc,change,selAfter,spans){if(doc.cm&&!doc.cm.curOp)return operation(doc.cm,makeChangeSingleDoc)(doc,change,selAfter,spans);if(change.to.line<doc.first)shiftDoc(doc,change.text.length-1-(change.to.line-change.from.line));else if(!(change.from.line>doc.lastLine())){if(change.from.line<doc.first){var shift=change.text.length-1-(doc.first-change.from.line);shiftDoc(doc,shift);change={from:Pos(doc.first,0),to:Pos(change.to.line+shift,change.to.ch),text:[lst(change.text)],origin:change.origin}}var last=doc.lastLine();change.to.line>last&&(change={from:change.from,to:Pos(last,getLine(doc,last).text.length),text:[change.text[0]],origin:change.origin});change.removed=getBetween(doc,change.from,change.to);selAfter||(selAfter=computeSelAfterChange(doc,change));doc.cm?makeChangeSingleDocInEditor(doc.cm,change,spans):updateDoc(doc,change,spans);setSelectionNoUndo(doc,selAfter,sel_dontScroll)}}function makeChangeSingleDocInEditor(cm,change,spans){var doc=cm.doc,display=cm.display,from=change.from,to=change.to,recomputeMaxLength=!1,checkWidthStart=from.line;if(!cm.options.lineWrapping){checkWidthStart=lineNo(visualLine(getLine(doc,from.line)));doc.iter(checkWidthStart,to.line+1,function(line){if(line==display.maxLine){recomputeMaxLength=!0;return!0}})}doc.sel.contains(change.from,change.to)>-1&&signalCursorActivity(cm);updateDoc(doc,change,spans,estimateHeight(cm));if(!cm.options.lineWrapping){doc.iter(checkWidthStart,from.line+change.text.length,function(line){var len=lineLength(line);if(len>display.maxLineLength){display.maxLine=line;display.maxLineLength=len;display.maxLineChanged=!0;recomputeMaxLength=!1}});recomputeMaxLength&&(cm.curOp.updateMaxLine=!0)}doc.frontier=Math.min(doc.frontier,from.line);startWorker(cm,400);var lendiff=change.text.length-(to.line-from.line)-1;change.full?regChange(cm):from.line!=to.line||1!=change.text.length||isWholeLineUpdate(cm.doc,change)?regChange(cm,from.line,to.line+1,lendiff):regLineChange(cm,from.line,"text");var changesHandler=hasHandler(cm,"changes"),changeHandler=hasHandler(cm,"change");if(changeHandler||changesHandler){var obj={from:from,to:to,text:change.text,removed:change.removed,origin:change.origin};changeHandler&&signalLater(cm,"change",cm,obj);changesHandler&&(cm.curOp.changeObjs||(cm.curOp.changeObjs=[])).push(obj)}cm.display.selForContextMenu=null}function replaceRange(doc,code,from,to,origin){to||(to=from);if(cmp(to,from)<0){var tmp=to;to=from;from=tmp}"string"==typeof code&&(code=doc.splitLines(code));makeChange(doc,{from:from,to:to,text:code,origin:origin})}function rebaseHistSelSingle(pos,from,to,diff){if(to<pos.line)pos.line+=diff;else if(from<pos.line){pos.line=from;pos.ch=0}}function rebaseHistArray(array,from,to,diff){for(var i=0;i<array.length;++i){var sub=array[i],ok=!0;if(sub.ranges){if(!sub.copied){sub=array[i]=sub.deepCopy();sub.copied=!0}for(var j=0;j<sub.ranges.length;j++){rebaseHistSelSingle(sub.ranges[j].anchor,from,to,diff);rebaseHistSelSingle(sub.ranges[j].head,from,to,diff)}}else{for(var j$1=0;j$1<sub.changes.length;++j$1){var cur=sub.changes[j$1];if(to<cur.from.line){cur.from=Pos(cur.from.line+diff,cur.from.ch);cur.to=Pos(cur.to.line+diff,cur.to.ch)}else if(from<=cur.to.line){ok=!1;break}}if(!ok){array.splice(0,i+1);i=0}}}}function rebaseHist(hist,change){var from=change.from.line,to=change.to.line,diff=change.text.length-(to-from)-1;rebaseHistArray(hist.done,from,to,diff);rebaseHistArray(hist.undone,from,to,diff)}function changeLine(doc,handle,changeType,op){var no=handle,line=handle;"number"==typeof handle?line=getLine(doc,clipLine(doc,handle)):no=lineNo(handle);if(null==no)return null;op(line,no)&&doc.cm&&regLineChange(doc.cm,no,changeType);return line}function LeafChunk(lines){var this$1=this;this.lines=lines;this.parent=null;for(var height=0,i=0;i<lines.length;++i){lines[i].parent=this$1;height+=lines[i].height}this.height=height}function BranchChunk(children){var this$1=this;this.children=children;for(var size=0,height=0,i=0;i<children.length;++i){var ch=children[i];size+=ch.chunkSize();height+=ch.height;ch.parent=this$1}this.size=size;this.height=height;this.parent=null}function LineWidget(doc,node,options){var this$1=this;if(options)for(var opt in options)options.hasOwnProperty(opt)&&(this$1[opt]=options[opt]);this.doc=doc;this.node=node}function adjustScrollWhenAboveVisible(cm,line,diff){heightAtLine(line)<(cm.curOp&&cm.curOp.scrollTop||cm.doc.scrollTop)&&addToScrollPos(cm,null,diff)}function addLineWidget(doc,handle,node,options){var widget=new LineWidget(doc,node,options),cm=doc.cm;cm&&widget.noHScroll&&(cm.display.alignWidgets=!0);changeLine(doc,handle,"widget",function(line){var widgets=line.widgets||(line.widgets=[]);null==widget.insertAt?widgets.push(widget):widgets.splice(Math.min(widgets.length-1,Math.max(0,widget.insertAt)),0,widget);widget.line=line;if(cm&&!lineIsHidden(doc,line)){var aboveVisible=heightAtLine(line)<doc.scrollTop;updateLineHeight(line,line.height+widgetHeight(widget));aboveVisible&&addToScrollPos(cm,null,widget.height);cm.curOp.forceUpdate=!0}return!0});return widget}function TextMarker(doc,type){this.lines=[];this.type=type;this.doc=doc;this.id=++nextMarkerId}function markText(doc,from,to,options,type){if(options&&options.shared)return markTextShared(doc,from,to,options,type);if(doc.cm&&!doc.cm.curOp)return operation(doc.cm,markText)(doc,from,to,options,type);var marker=new TextMarker(doc,type),diff=cmp(from,to);options&&copyObj(options,marker,!1);if(diff>0||0==diff&&marker.clearWhenEmpty!==!1)return marker;if(marker.replacedWith){marker.collapsed=!0;marker.widgetNode=elt("span",[marker.replacedWith],"CodeMirror-widget");options.handleMouseEvents||marker.widgetNode.setAttribute("cm-ignore-events","true");options.insertLeft&&(marker.widgetNode.insertLeft=!0)}if(marker.collapsed){if(conflictingCollapsedRange(doc,from.line,from,to,marker)||from.line!=to.line&&conflictingCollapsedRange(doc,to.line,from,to,marker))throw new Error("Inserting collapsed marker partially overlapping an existing one");seeCollapsedSpans()}marker.addToHistory&&addChangeToHistory(doc,{from:from,to:to,origin:"markText"},doc.sel,NaN);var updateMaxLine,curLine=from.line,cm=doc.cm;doc.iter(curLine,to.line+1,function(line){cm&&marker.collapsed&&!cm.options.lineWrapping&&visualLine(line)==cm.display.maxLine&&(updateMaxLine=!0);marker.collapsed&&curLine!=from.line&&updateLineHeight(line,0);addMarkedSpan(line,new MarkedSpan(marker,curLine==from.line?from.ch:null,curLine==to.line?to.ch:null));++curLine});marker.collapsed&&doc.iter(from.line,to.line+1,function(line){lineIsHidden(doc,line)&&updateLineHeight(line,0)});marker.clearOnEnter&&on(marker,"beforeCursorEnter",function(){return marker.clear()});if(marker.readOnly){seeReadOnlySpans();(doc.history.done.length||doc.history.undone.length)&&doc.clearHistory()}if(marker.collapsed){marker.id=++nextMarkerId;marker.atomic=!0}if(cm){updateMaxLine&&(cm.curOp.updateMaxLine=!0);if(marker.collapsed)regChange(cm,from.line,to.line+1);else if(marker.className||marker.title||marker.startStyle||marker.endStyle||marker.css)for(var i=from.line;i<=to.line;i++)regLineChange(cm,i,"text");marker.atomic&&reCheckSelection(cm.doc);signalLater(cm,"markerAdded",cm,marker)}return marker}function SharedTextMarker(markers,primary){var this$1=this;this.markers=markers;this.primary=primary;for(var i=0;i<markers.length;++i)markers[i].parent=this$1}function markTextShared(doc,from,to,options,type){options=copyObj(options);options.shared=!1;var markers=[markText(doc,from,to,options,type)],primary=markers[0],widget=options.widgetNode;linkedDocs(doc,function(doc){widget&&(options.widgetNode=widget.cloneNode(!0));markers.push(markText(doc,clipPos(doc,from),clipPos(doc,to),options,type));for(var i=0;i<doc.linked.length;++i)if(doc.linked[i].isParent)return;primary=lst(markers)});return new SharedTextMarker(markers,primary)}function findSharedMarkers(doc){return doc.findMarks(Pos(doc.first,0),doc.clipPos(Pos(doc.lastLine())),function(m){return m.parent})}function copySharedMarkers(doc,markers){for(var i=0;i<markers.length;i++){var marker=markers[i],pos=marker.find(),mFrom=doc.clipPos(pos.from),mTo=doc.clipPos(pos.to);if(cmp(mFrom,mTo)){var subMark=markText(doc,mFrom,mTo,marker.primary,marker.primary.type);marker.markers.push(subMark);subMark.parent=marker}}}function detachSharedMarkers(markers){for(var loop=function(i){var marker=markers[i],linked=[marker.primary.doc];linkedDocs(marker.primary.doc,function(d){return linked.push(d)});for(var j=0;j<marker.markers.length;j++){var subMarker=marker.markers[j];if(indexOf(linked,subMarker.doc)==-1){subMarker.parent=null;marker.markers.splice(j--,1)}}},i=0;i<markers.length;i++)loop(i)}function onDrop(e){var cm=this;clearDragCursor(cm);if(!signalDOMEvent(cm,e)&&!eventInWidget(cm.display,e)){e_preventDefault(e);ie&&(lastDrop=+new Date);var pos=posFromMouse(cm,e,!0),files=e.dataTransfer.files;if(pos&&!cm.isReadOnly())if(files&&files.length&&window.FileReader&&window.File)for(var n=files.length,text=Array(n),read=0,loadFile=function(file,i){if(!cm.options.allowDropFileTypes||indexOf(cm.options.allowDropFileTypes,file.type)!=-1){var reader=new FileReader;reader.onload=operation(cm,function(){var content=reader.result;/[\x00-\x08\x0e-\x1f]{2}/.test(content)&&(content="");text[i]=content;if(++read==n){pos=clipPos(cm.doc,pos);var change={from:pos,to:pos,text:cm.doc.splitLines(text.join(cm.doc.lineSeparator())),origin:"paste"};makeChange(cm.doc,change);setSelectionReplaceHistory(cm.doc,simpleSelection(pos,changeEnd(change)))}});reader.readAsText(file)}},i=0;i<n;++i)loadFile(files[i],i);else{if(cm.state.draggingText&&cm.doc.sel.contains(pos)>-1){cm.state.draggingText(e);setTimeout(function(){return cm.display.input.focus()},20);return}try{var text$1=e.dataTransfer.getData("Text");if(text$1){var selected;cm.state.draggingText&&!cm.state.draggingText.copy&&(selected=cm.listSelections());setSelectionNoUndo(cm.doc,simpleSelection(pos,pos));if(selected)for(var i$1=0;i$1<selected.length;++i$1)replaceRange(cm.doc,"",selected[i$1].anchor,selected[i$1].head,"drag");cm.replaceSelection(text$1,"around","paste");cm.display.input.focus()}}catch(e){}}}}function onDragStart(cm,e){if(ie&&(!cm.state.draggingText||+new Date-lastDrop<100))e_stop(e);else if(!signalDOMEvent(cm,e)&&!eventInWidget(cm.display,e)){e.dataTransfer.setData("Text",cm.getSelection());e.dataTransfer.effectAllowed="copyMove";if(e.dataTransfer.setDragImage&&!safari){var img=elt("img",null,null,"position: fixed; left: 0; top: 0;");img.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";if(presto){img.width=img.height=1;cm.display.wrapper.appendChild(img);img._top=img.offsetTop}e.dataTransfer.setDragImage(img,0,0);presto&&img.parentNode.removeChild(img)}}}function onDragOver(cm,e){var pos=posFromMouse(cm,e);if(pos){var frag=document.createDocumentFragment();drawSelectionCursor(cm,pos,frag);if(!cm.display.dragCursor){cm.display.dragCursor=elt("div",null,"CodeMirror-cursors CodeMirror-dragcursors");cm.display.lineSpace.insertBefore(cm.display.dragCursor,cm.display.cursorDiv)}removeChildrenAndAdd(cm.display.dragCursor,frag)}}function clearDragCursor(cm){if(cm.display.dragCursor){cm.display.lineSpace.removeChild(cm.display.dragCursor);cm.display.dragCursor=null}}function forEachCodeMirror(f){if(document.body.getElementsByClassName)for(var byClass=document.body.getElementsByClassName("CodeMirror"),i=0;i<byClass.length;i++){var cm=byClass[i].CodeMirror;cm&&f(cm)}}function ensureGlobalHandlers(){if(!globalsRegistered){registerGlobalHandlers();globalsRegistered=!0}}function registerGlobalHandlers(){var resizeTimer;on(window,"resize",function(){null==resizeTimer&&(resizeTimer=setTimeout(function(){resizeTimer=null;forEachCodeMirror(onResize)},100))});on(window,"blur",function(){return forEachCodeMirror(onBlur)})}function onResize(cm){var d=cm.display;if(d.lastWrapHeight!=d.wrapper.clientHeight||d.lastWrapWidth!=d.wrapper.clientWidth){d.cachedCharWidth=d.cachedTextHeight=d.cachedPaddingH=null;d.scrollbarsClipped=!1;cm.setSize()}}function normalizeKeyName(name){var parts=name.split(/-(?!$)/);name=parts[parts.length-1];for(var alt,ctrl,shift,cmd,i=0;i<parts.length-1;i++){var mod=parts[i];if(/^(cmd|meta|m)$/i.test(mod))cmd=!0;else if(/^a(lt)?$/i.test(mod))alt=!0;else if(/^(c|ctrl|control)$/i.test(mod))ctrl=!0;else{if(!/^s(hift)?$/i.test(mod))throw new Error("Unrecognized modifier name: "+mod);shift=!0}}alt&&(name="Alt-"+name);ctrl&&(name="Ctrl-"+name);cmd&&(name="Cmd-"+name);shift&&(name="Shift-"+name);return name}function normalizeKeyMap(keymap){var copy={};for(var keyname in keymap)if(keymap.hasOwnProperty(keyname)){var value=keymap[keyname];if(/^(name|fallthrough|(de|at)tach)$/.test(keyname))continue;if("..."==value){delete keymap[keyname];continue}for(var keys=map(keyname.split(" "),normalizeKeyName),i=0;i<keys.length;i++){var val=void 0,name=void 0;if(i==keys.length-1){name=keys.join(" ");val=value}else{name=keys.slice(0,i+1).join(" ");val="..."}var prev=copy[name];if(prev){if(prev!=val)throw new Error("Inconsistent bindings for "+name)}else copy[name]=val}delete keymap[keyname]}for(var prop in copy)keymap[prop]=copy[prop];return keymap}function lookupKey(key,map,handle,context){map=getKeyMap(map);var found=map.call?map.call(key,context):map[key];if(found===!1)return"nothing";if("..."===found)return"multi";if(null!=found&&handle(found))return"handled";if(map.fallthrough){if("[object Array]"!=Object.prototype.toString.call(map.fallthrough))return lookupKey(key,map.fallthrough,handle,context);for(var i=0;i<map.fallthrough.length;i++){var result=lookupKey(key,map.fallthrough[i],handle,context);if(result)return result}}}function isModifierKey(value){var name="string"==typeof value?value:keyNames[value.keyCode];return"Ctrl"==name||"Alt"==name||"Shift"==name||"Mod"==name}function keyName(event,noShift){if(presto&&34==event.keyCode&&event["char"])return!1;var base=keyNames[event.keyCode],name=base;if(null==name||event.altGraphKey)return!1;event.altKey&&"Alt"!=base&&(name="Alt-"+name);(flipCtrlCmd?event.metaKey:event.ctrlKey)&&"Ctrl"!=base&&(name="Ctrl-"+name);(flipCtrlCmd?event.ctrlKey:event.metaKey)&&"Cmd"!=base&&(name="Cmd-"+name);!noShift&&event.shiftKey&&"Shift"!=base&&(name="Shift-"+name);return name}function getKeyMap(val){return"string"==typeof val?keyMap[val]:val}function deleteNearSelection(cm,compute){for(var ranges=cm.doc.sel.ranges,kill=[],i=0;i<ranges.length;i++){for(var toKill=compute(ranges[i]);kill.length&&cmp(toKill.from,lst(kill).to)<=0;){var replaced=kill.pop();if(cmp(replaced.from,toKill.from)<0){toKill.from=replaced.from;break}}kill.push(toKill)}runInOp(cm,function(){for(var i=kill.length-1;i>=0;i--)replaceRange(cm.doc,"",kill[i].from,kill[i].to,"+delete");ensureCursorVisible(cm)})}function lineStart(cm,lineN){var line=getLine(cm.doc,lineN),visual=visualLine(line);visual!=line&&(lineN=lineNo(visual));var order=getOrder(visual),ch=order?order[0].level%2?lineRight(visual):lineLeft(visual):0;return Pos(lineN,ch)}function lineEnd(cm,lineN){for(var merged,line=getLine(cm.doc,lineN);merged=collapsedSpanAtEnd(line);){line=merged.find(1,!0).line;lineN=null}var order=getOrder(line),ch=order?order[0].level%2?lineLeft(line):lineRight(line):line.text.length;return Pos(null==lineN?lineNo(line):lineN,ch)}function lineStartSmart(cm,pos){var start=lineStart(cm,pos.line),line=getLine(cm.doc,start.line),order=getOrder(line);if(!order||0==order[0].level){var firstNonWS=Math.max(0,line.text.search(/\S/)),inWS=pos.line==start.line&&pos.ch<=firstNonWS&&pos.ch;return Pos(start.line,inWS?0:firstNonWS)}return start}function doHandleBinding(cm,bound,dropShift){if("string"==typeof bound){bound=commands[bound];if(!bound)return!1}cm.display.input.ensurePolled();var prevShift=cm.display.shift,done=!1;try{cm.isReadOnly()&&(cm.state.suppressEdits=!0);dropShift&&(cm.display.shift=!1);done=bound(cm)!=Pass}finally{cm.display.shift=prevShift;cm.state.suppressEdits=!1}return done}function lookupKeyForEditor(cm,name,handle){for(var i=0;i<cm.state.keyMaps.length;i++){var result=lookupKey(name,cm.state.keyMaps[i],handle,cm);if(result)return result}return cm.options.extraKeys&&lookupKey(name,cm.options.extraKeys,handle,cm)||lookupKey(name,cm.options.keyMap,handle,cm)}function dispatchKey(cm,name,e,handle){var seq=cm.state.keySeq;if(seq){if(isModifierKey(name))return"handled";stopSeq.set(50,function(){if(cm.state.keySeq==seq){cm.state.keySeq=null;cm.display.input.reset()}});name=seq+" "+name}var result=lookupKeyForEditor(cm,name,handle);"multi"==result&&(cm.state.keySeq=name);"handled"==result&&signalLater(cm,"keyHandled",cm,name,e);if("handled"==result||"multi"==result){e_preventDefault(e);restartBlink(cm)}if(seq&&!result&&/\'$/.test(name)){e_preventDefault(e);return!0}return!!result}function handleKeyBinding(cm,e){var name=keyName(e,!0);return!!name&&(e.shiftKey&&!cm.state.keySeq?dispatchKey(cm,"Shift-"+name,e,function(b){return doHandleBinding(cm,b,!0)})||dispatchKey(cm,name,e,function(b){if("string"==typeof b?/^go[A-Z]/.test(b):b.motion)return doHandleBinding(cm,b)}):dispatchKey(cm,name,e,function(b){return doHandleBinding(cm,b)}))}function handleCharBinding(cm,e,ch){return dispatchKey(cm,"'"+ch+"'",e,function(b){return doHandleBinding(cm,b,!0)})}function onKeyDown(e){var cm=this;cm.curOp.focus=activeElt();if(!signalDOMEvent(cm,e)){ie&&ie_version<11&&27==e.keyCode&&(e.returnValue=!1);var code=e.keyCode;cm.display.shift=16==code||e.shiftKey;var handled=handleKeyBinding(cm,e);if(presto){lastStoppedKey=handled?code:null;!handled&&88==code&&!hasCopyEvent&&(mac?e.metaKey:e.ctrlKey)&&cm.replaceSelection("",null,"cut")}18!=code||/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)||showCrossHair(cm)}}function showCrossHair(cm){function up(e){if(18==e.keyCode||!e.altKey){rmClass(lineDiv,"CodeMirror-crosshair");off(document,"keyup",up);off(document,"mouseover",up)}}var lineDiv=cm.display.lineDiv;addClass(lineDiv,"CodeMirror-crosshair");on(document,"keyup",up);on(document,"mouseover",up)}function onKeyUp(e){16==e.keyCode&&(this.doc.sel.shift=!1);signalDOMEvent(this,e)}function onKeyPress(e){var cm=this;if(!(eventInWidget(cm.display,e)||signalDOMEvent(cm,e)||e.ctrlKey&&!e.altKey||mac&&e.metaKey)){var keyCode=e.keyCode,charCode=e.charCode;if(presto&&keyCode==lastStoppedKey){lastStoppedKey=null;e_preventDefault(e)}else if(!presto||e.which&&!(e.which<10)||!handleKeyBinding(cm,e)){var ch=String.fromCharCode(null==charCode?keyCode:charCode);"\b"!=ch&&(handleCharBinding(cm,e,ch)||cm.display.input.onKeyPress(e))}}}function onMouseDown(e){var cm=this,display=cm.display;if(!(signalDOMEvent(cm,e)||display.activeTouch&&display.input.supportsTouch())){display.input.ensurePolled();display.shift=e.shiftKey;if(eventInWidget(display,e)){if(!webkit){display.scroller.draggable=!1;setTimeout(function(){return display.scroller.draggable=!0},100)}}else if(!clickInGutter(cm,e)){var start=posFromMouse(cm,e);window.focus();switch(e_button(e)){case 1:cm.state.selectingText?cm.state.selectingText(e):start?leftButtonDown(cm,e,start):e_target(e)==display.scroller&&e_preventDefault(e);break;case 2:webkit&&(cm.state.lastMiddleDown=+new Date);start&&extendSelection(cm.doc,start);setTimeout(function(){return display.input.focus()},20);e_preventDefault(e);break;case 3:captureRightClick?onContextMenu(cm,e):delayBlurEvent(cm)}}}}function leftButtonDown(cm,e,start){ie?setTimeout(bind(ensureFocus,cm),0):cm.curOp.focus=activeElt();var type,now=+new Date;if(lastDoubleClick&&lastDoubleClick.time>now-400&&0==cmp(lastDoubleClick.pos,start))type="triple";else if(lastClick&&lastClick.time>now-400&&0==cmp(lastClick.pos,start)){type="double";lastDoubleClick={time:now,pos:start}}else{type="single";lastClick={time:now,pos:start}}var contained,sel=cm.doc.sel,modifier=mac?e.metaKey:e.ctrlKey;cm.options.dragDrop&&dragAndDrop&&!cm.isReadOnly()&&"single"==type&&(contained=sel.contains(start))>-1&&(cmp((contained=sel.ranges[contained]).from(),start)<0||start.xRel>0)&&(cmp(contained.to(),start)>0||start.xRel<0)?leftButtonStartDrag(cm,e,start,modifier):leftButtonSelect(cm,e,start,type,modifier);
5
+ }function leftButtonStartDrag(cm,e,start,modifier){var display=cm.display,startTime=+new Date,dragEnd=operation(cm,function(e2){webkit&&(display.scroller.draggable=!1);cm.state.draggingText=!1;off(document,"mouseup",dragEnd);off(display.scroller,"drop",dragEnd);if(Math.abs(e.clientX-e2.clientX)+Math.abs(e.clientY-e2.clientY)<10){e_preventDefault(e2);!modifier&&+new Date-200<startTime&&extendSelection(cm.doc,start);webkit||ie&&9==ie_version?setTimeout(function(){document.body.focus();display.input.focus()},20):display.input.focus()}});webkit&&(display.scroller.draggable=!0);cm.state.draggingText=dragEnd;dragEnd.copy=mac?e.altKey:e.ctrlKey;display.scroller.dragDrop&&display.scroller.dragDrop();on(document,"mouseup",dragEnd);on(display.scroller,"drop",dragEnd)}function leftButtonSelect(cm,e,start,type,addNew){function extendTo(pos){if(0!=cmp(lastPos,pos)){lastPos=pos;if("rect"==type){for(var ranges=[],tabSize=cm.options.tabSize,startCol=countColumn(getLine(doc,start.line).text,start.ch,tabSize),posCol=countColumn(getLine(doc,pos.line).text,pos.ch,tabSize),left=Math.min(startCol,posCol),right=Math.max(startCol,posCol),line=Math.min(start.line,pos.line),end=Math.min(cm.lastLine(),Math.max(start.line,pos.line));line<=end;line++){var text=getLine(doc,line).text,leftPos=findColumn(text,left,tabSize);left==right?ranges.push(new Range(Pos(line,leftPos),Pos(line,leftPos))):text.length>leftPos&&ranges.push(new Range(Pos(line,leftPos),Pos(line,findColumn(text,right,tabSize))))}ranges.length||ranges.push(new Range(start,start));setSelection(doc,normalizeSelection(startSel.ranges.slice(0,ourIndex).concat(ranges),ourIndex),{origin:"*mouse",scroll:!1});cm.scrollIntoView(pos)}else{var oldRange=ourRange,anchor=oldRange.anchor,head=pos;if("single"!=type){var range;range="double"==type?cm.findWordAt(pos):new Range(Pos(pos.line,0),clipPos(doc,Pos(pos.line+1,0)));if(cmp(range.anchor,anchor)>0){head=range.head;anchor=minPos(oldRange.from(),range.anchor)}else{head=range.anchor;anchor=maxPos(oldRange.to(),range.head)}}var ranges$1=startSel.ranges.slice(0);ranges$1[ourIndex]=new Range(clipPos(doc,anchor),head);setSelection(doc,normalizeSelection(ranges$1,ourIndex),sel_mouse)}}}function extend(e){var curCount=++counter,cur=posFromMouse(cm,e,!0,"rect"==type);if(cur)if(0!=cmp(cur,lastPos)){cm.curOp.focus=activeElt();extendTo(cur);var visible=visibleLines(display,doc);(cur.line>=visible.to||cur.line<visible.from)&&setTimeout(operation(cm,function(){counter==curCount&&extend(e)}),150)}else{var outside=e.clientY<editorSize.top?-20:e.clientY>editorSize.bottom?20:0;outside&&setTimeout(operation(cm,function(){if(counter==curCount){display.scroller.scrollTop+=outside;extend(e)}}),50)}}function done(e){cm.state.selectingText=!1;counter=1/0;e_preventDefault(e);display.input.focus();off(document,"mousemove",move);off(document,"mouseup",up);doc.history.lastSelOrigin=null}var display=cm.display,doc=cm.doc;e_preventDefault(e);var ourRange,ourIndex,startSel=doc.sel,ranges=startSel.ranges;if(addNew&&!e.shiftKey){ourIndex=doc.sel.contains(start);ourRange=ourIndex>-1?ranges[ourIndex]:new Range(start,start)}else{ourRange=doc.sel.primary();ourIndex=doc.sel.primIndex}if(chromeOS?e.shiftKey&&e.metaKey:e.altKey){type="rect";addNew||(ourRange=new Range(start,start));start=posFromMouse(cm,e,!0,!0);ourIndex=-1}else if("double"==type){var word=cm.findWordAt(start);ourRange=cm.display.shift||doc.extend?extendRange(doc,ourRange,word.anchor,word.head):word}else if("triple"==type){var line=new Range(Pos(start.line,0),clipPos(doc,Pos(start.line+1,0)));ourRange=cm.display.shift||doc.extend?extendRange(doc,ourRange,line.anchor,line.head):line}else ourRange=extendRange(doc,ourRange,start);if(addNew)if(ourIndex==-1){ourIndex=ranges.length;setSelection(doc,normalizeSelection(ranges.concat([ourRange]),ourIndex),{scroll:!1,origin:"*mouse"})}else if(ranges.length>1&&ranges[ourIndex].empty()&&"single"==type&&!e.shiftKey){setSelection(doc,normalizeSelection(ranges.slice(0,ourIndex).concat(ranges.slice(ourIndex+1)),0),{scroll:!1,origin:"*mouse"});startSel=doc.sel}else replaceOneSelection(doc,ourIndex,ourRange,sel_mouse);else{ourIndex=0;setSelection(doc,new Selection([ourRange],0),sel_mouse);startSel=doc.sel}var lastPos=start,editorSize=display.wrapper.getBoundingClientRect(),counter=0,move=operation(cm,function(e){e_button(e)?extend(e):done(e)}),up=operation(cm,done);cm.state.selectingText=up;on(document,"mousemove",move);on(document,"mouseup",up)}function gutterEvent(cm,e,type,prevent){var mX,mY;try{mX=e.clientX;mY=e.clientY}catch(e){return!1}if(mX>=Math.floor(cm.display.gutters.getBoundingClientRect().right))return!1;prevent&&e_preventDefault(e);var display=cm.display,lineBox=display.lineDiv.getBoundingClientRect();if(mY>lineBox.bottom||!hasHandler(cm,type))return e_defaultPrevented(e);mY-=lineBox.top-display.viewOffset;for(var i=0;i<cm.options.gutters.length;++i){var g=display.gutters.childNodes[i];if(g&&g.getBoundingClientRect().right>=mX){var line=lineAtHeight(cm.doc,mY),gutter=cm.options.gutters[i];signal(cm,type,cm,line,gutter,e);return e_defaultPrevented(e)}}}function clickInGutter(cm,e){return gutterEvent(cm,e,"gutterClick",!0)}function onContextMenu(cm,e){eventInWidget(cm.display,e)||contextMenuInGutter(cm,e)||signalDOMEvent(cm,e,"contextmenu")||cm.display.input.onContextMenu(e)}function contextMenuInGutter(cm,e){return!!hasHandler(cm,"gutterContextMenu")&&gutterEvent(cm,e,"gutterContextMenu",!1)}function themeChanged(cm){cm.display.wrapper.className=cm.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+cm.options.theme.replace(/(^|\s)\s*/g," cm-s-");clearCaches(cm)}function defineOptions(CodeMirror){function option(name,deflt,handle,notOnInit){CodeMirror.defaults[name]=deflt;handle&&(optionHandlers[name]=notOnInit?function(cm,val,old){old!=Init&&handle(cm,val,old)}:handle)}var optionHandlers=CodeMirror.optionHandlers;CodeMirror.defineOption=option;CodeMirror.Init=Init;option("value","",function(cm,val){return cm.setValue(val)},!0);option("mode",null,function(cm,val){cm.doc.modeOption=val;loadMode(cm)},!0);option("indentUnit",2,loadMode,!0);option("indentWithTabs",!1);option("smartIndent",!0);option("tabSize",4,function(cm){resetModeState(cm);clearCaches(cm);regChange(cm)},!0);option("lineSeparator",null,function(cm,val){cm.doc.lineSep=val;if(val){var newBreaks=[],lineNo=cm.doc.first;cm.doc.iter(function(line){for(var pos=0;;){var found=line.text.indexOf(val,pos);if(found==-1)break;pos=found+val.length;newBreaks.push(Pos(lineNo,found))}lineNo++});for(var i=newBreaks.length-1;i>=0;i--)replaceRange(cm.doc,val,newBreaks[i],Pos(newBreaks[i].line,newBreaks[i].ch+val.length))}});option("specialChars",/[\u0000-\u001f\u007f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g,function(cm,val,old){cm.state.specialChars=new RegExp(val.source+(val.test("\t")?"":"|\t"),"g");old!=Init&&cm.refresh()});option("specialCharPlaceholder",defaultSpecialCharPlaceholder,function(cm){return cm.refresh()},!0);option("electricChars",!0);option("inputStyle",mobile?"contenteditable":"textarea",function(){throw new Error("inputStyle can not (yet) be changed in a running editor")},!0);option("spellcheck",!1,function(cm,val){return cm.getInputField().spellcheck=val},!0);option("rtlMoveVisually",!windows);option("wholeLineUpdateBefore",!0);option("theme","default",function(cm){themeChanged(cm);guttersChanged(cm)},!0);option("keyMap","default",function(cm,val,old){var next=getKeyMap(val),prev=old!=Init&&getKeyMap(old);prev&&prev.detach&&prev.detach(cm,next);next.attach&&next.attach(cm,prev||null)});option("extraKeys",null);option("lineWrapping",!1,wrappingChanged,!0);option("gutters",[],function(cm){setGuttersForLineNumbers(cm.options);guttersChanged(cm)},!0);option("fixedGutter",!0,function(cm,val){cm.display.gutters.style.left=val?compensateForHScroll(cm.display)+"px":"0";cm.refresh()},!0);option("coverGutterNextToScrollbar",!1,function(cm){return updateScrollbars(cm)},!0);option("scrollbarStyle","native",function(cm){initScrollbars(cm);updateScrollbars(cm);cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft)},!0);option("lineNumbers",!1,function(cm){setGuttersForLineNumbers(cm.options);guttersChanged(cm)},!0);option("firstLineNumber",1,guttersChanged,!0);option("lineNumberFormatter",function(integer){return integer},guttersChanged,!0);option("showCursorWhenSelecting",!1,updateSelection,!0);option("resetSelectionOnContextMenu",!0);option("lineWiseCopyCut",!0);option("readOnly",!1,function(cm,val){if("nocursor"==val){onBlur(cm);cm.display.input.blur();cm.display.disabled=!0}else cm.display.disabled=!1;cm.display.input.readOnlyChanged(val)});option("disableInput",!1,function(cm,val){val||cm.display.input.reset()},!0);option("dragDrop",!0,dragDropChanged);option("allowDropFileTypes",null);option("cursorBlinkRate",530);option("cursorScrollMargin",0);option("cursorHeight",1,updateSelection,!0);option("singleCursorHeightPerLine",!0,updateSelection,!0);option("workTime",100);option("workDelay",100);option("flattenSpans",!0,resetModeState,!0);option("addModeClass",!1,resetModeState,!0);option("pollInterval",100);option("undoDepth",200,function(cm,val){return cm.doc.history.undoDepth=val});option("historyEventDelay",1250);option("viewportMargin",10,function(cm){return cm.refresh()},!0);option("maxHighlightLength",1e4,resetModeState,!0);option("moveInputWithCursor",!0,function(cm,val){val||cm.display.input.resetPosition()});option("tabindex",null,function(cm,val){return cm.display.input.getField().tabIndex=val||""});option("autofocus",null)}function guttersChanged(cm){updateGutters(cm);regChange(cm);alignHorizontally(cm)}function dragDropChanged(cm,value,old){var wasOn=old&&old!=Init;if(!value!=!wasOn){var funcs=cm.display.dragFunctions,toggle=value?on:off;toggle(cm.display.scroller,"dragstart",funcs.start);toggle(cm.display.scroller,"dragenter",funcs.enter);toggle(cm.display.scroller,"dragover",funcs.over);toggle(cm.display.scroller,"dragleave",funcs.leave);toggle(cm.display.scroller,"drop",funcs.drop)}}function wrappingChanged(cm){if(cm.options.lineWrapping){addClass(cm.display.wrapper,"CodeMirror-wrap");cm.display.sizer.style.minWidth="";cm.display.sizerWidth=null}else{rmClass(cm.display.wrapper,"CodeMirror-wrap");findMaxLine(cm)}estimateLineHeights(cm);regChange(cm);clearCaches(cm);setTimeout(function(){return updateScrollbars(cm)},100)}function CodeMirror(place,options){var this$1=this;if(!(this instanceof CodeMirror))return new CodeMirror(place,options);this.options=options=options?copyObj(options):{};copyObj(defaults,options,!1);setGuttersForLineNumbers(options);var doc=options.value;"string"==typeof doc&&(doc=new Doc(doc,options.mode,null,options.lineSeparator));this.doc=doc;var input=new CodeMirror.inputStyles[options.inputStyle](this),display=this.display=new Display(place,doc,input);display.wrapper.CodeMirror=this;updateGutters(this);themeChanged(this);options.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap");initScrollbars(this);this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,delayingBlurEvent:!1,focused:!1,suppressEdits:!1,pasteIncoming:!1,cutIncoming:!1,selectingText:!1,draggingText:!1,highlight:new Delayed,keySeq:null,specialChars:null};options.autofocus&&!mobile&&display.input.focus();ie&&ie_version<11&&setTimeout(function(){return this$1.display.input.reset(!0)},20);registerEventHandlers(this);ensureGlobalHandlers();startOperation(this);this.curOp.forceUpdate=!0;attachDoc(this,doc);options.autofocus&&!mobile||this.hasFocus()?setTimeout(bind(onFocus,this),20):onBlur(this);for(var opt in optionHandlers)optionHandlers.hasOwnProperty(opt)&&optionHandlers[opt](this$1,options[opt],Init);maybeUpdateLineNumberWidth(this);options.finishInit&&options.finishInit(this);for(var i=0;i<initHooks.length;++i)initHooks[i](this$1);endOperation(this);webkit&&options.lineWrapping&&"optimizelegibility"==getComputedStyle(display.lineDiv).textRendering&&(display.lineDiv.style.textRendering="auto")}function registerEventHandlers(cm){function finishTouch(){if(d.activeTouch){touchFinished=setTimeout(function(){return d.activeTouch=null},1e3);prevTouch=d.activeTouch;prevTouch.end=+new Date}}function isMouseLikeTouchEvent(e){if(1!=e.touches.length)return!1;var touch=e.touches[0];return touch.radiusX<=1&&touch.radiusY<=1}function farAway(touch,other){if(null==other.left)return!0;var dx=other.left-touch.left,dy=other.top-touch.top;return dx*dx+dy*dy>400}var d=cm.display;on(d.scroller,"mousedown",operation(cm,onMouseDown));ie&&ie_version<11?on(d.scroller,"dblclick",operation(cm,function(e){if(!signalDOMEvent(cm,e)){var pos=posFromMouse(cm,e);if(pos&&!clickInGutter(cm,e)&&!eventInWidget(cm.display,e)){e_preventDefault(e);var word=cm.findWordAt(pos);extendSelection(cm.doc,word.anchor,word.head)}}})):on(d.scroller,"dblclick",function(e){return signalDOMEvent(cm,e)||e_preventDefault(e)});captureRightClick||on(d.scroller,"contextmenu",function(e){return onContextMenu(cm,e)});var touchFinished,prevTouch={end:0};on(d.scroller,"touchstart",function(e){if(!signalDOMEvent(cm,e)&&!isMouseLikeTouchEvent(e)){d.input.ensurePolled();clearTimeout(touchFinished);var now=+new Date;d.activeTouch={start:now,moved:!1,prev:now-prevTouch.end<=300?prevTouch:null};if(1==e.touches.length){d.activeTouch.left=e.touches[0].pageX;d.activeTouch.top=e.touches[0].pageY}}});on(d.scroller,"touchmove",function(){d.activeTouch&&(d.activeTouch.moved=!0)});on(d.scroller,"touchend",function(e){var touch=d.activeTouch;if(touch&&!eventInWidget(d,e)&&null!=touch.left&&!touch.moved&&new Date-touch.start<300){var range,pos=cm.coordsChar(d.activeTouch,"page");range=!touch.prev||farAway(touch,touch.prev)?new Range(pos,pos):!touch.prev.prev||farAway(touch,touch.prev.prev)?cm.findWordAt(pos):new Range(Pos(pos.line,0),clipPos(cm.doc,Pos(pos.line+1,0)));cm.setSelection(range.anchor,range.head);cm.focus();e_preventDefault(e)}finishTouch()});on(d.scroller,"touchcancel",finishTouch);on(d.scroller,"scroll",function(){if(d.scroller.clientHeight){setScrollTop(cm,d.scroller.scrollTop);setScrollLeft(cm,d.scroller.scrollLeft,!0);signal(cm,"scroll",cm)}});on(d.scroller,"mousewheel",function(e){return onScrollWheel(cm,e)});on(d.scroller,"DOMMouseScroll",function(e){return onScrollWheel(cm,e)});on(d.wrapper,"scroll",function(){return d.wrapper.scrollTop=d.wrapper.scrollLeft=0});d.dragFunctions={enter:function(e){signalDOMEvent(cm,e)||e_stop(e)},over:function(e){if(!signalDOMEvent(cm,e)){onDragOver(cm,e);e_stop(e)}},start:function(e){return onDragStart(cm,e)},drop:operation(cm,onDrop),leave:function(e){signalDOMEvent(cm,e)||clearDragCursor(cm)}};var inp=d.input.getField();on(inp,"keyup",function(e){return onKeyUp.call(cm,e)});on(inp,"keydown",operation(cm,onKeyDown));on(inp,"keypress",operation(cm,onKeyPress));on(inp,"focus",function(e){return onFocus(cm,e)});on(inp,"blur",function(e){return onBlur(cm,e)})}function indentLine(cm,n,how,aggressive){var state,doc=cm.doc;null==how&&(how="add");"smart"==how&&(doc.mode.indent?state=getStateBefore(cm,n):how="prev");var tabSize=cm.options.tabSize,line=getLine(doc,n),curSpace=countColumn(line.text,null,tabSize);line.stateAfter&&(line.stateAfter=null);var indentation,curSpaceString=line.text.match(/^\s*/)[0];if(aggressive||/\S/.test(line.text)){if("smart"==how){indentation=doc.mode.indent(state,line.text.slice(curSpaceString.length),line.text);if(indentation==Pass||indentation>150){if(!aggressive)return;how="prev"}}}else{indentation=0;how="not"}"prev"==how?indentation=n>doc.first?countColumn(getLine(doc,n-1).text,null,tabSize):0:"add"==how?indentation=curSpace+cm.options.indentUnit:"subtract"==how?indentation=curSpace-cm.options.indentUnit:"number"==typeof how&&(indentation=curSpace+how);indentation=Math.max(0,indentation);var indentString="",pos=0;if(cm.options.indentWithTabs)for(var i=Math.floor(indentation/tabSize);i;--i){pos+=tabSize;indentString+="\t"}pos<indentation&&(indentString+=spaceStr(indentation-pos));if(indentString!=curSpaceString){replaceRange(doc,indentString,Pos(n,0),Pos(n,curSpaceString.length),"+input");line.stateAfter=null;return!0}for(var i$1=0;i$1<doc.sel.ranges.length;i$1++){var range=doc.sel.ranges[i$1];if(range.head.line==n&&range.head.ch<curSpaceString.length){var pos$1=Pos(n,curSpaceString.length);replaceOneSelection(doc,i$1,new Range(pos$1,pos$1));break}}}function setLastCopied(newLastCopied){lastCopied=newLastCopied}function applyTextInput(cm,inserted,deleted,sel,origin){var doc=cm.doc;cm.display.shift=!1;sel||(sel=doc.sel);var paste=cm.state.pasteIncoming||"paste"==origin,textLines=splitLinesAuto(inserted),multiPaste=null;if(paste&&sel.ranges.length>1)if(lastCopied&&lastCopied.text.join("\n")==inserted){if(sel.ranges.length%lastCopied.text.length==0){multiPaste=[];for(var i=0;i<lastCopied.text.length;i++)multiPaste.push(doc.splitLines(lastCopied.text[i]))}}else textLines.length==sel.ranges.length&&(multiPaste=map(textLines,function(l){return[l]}));for(var updateInput,i$1=sel.ranges.length-1;i$1>=0;i$1--){var range=sel.ranges[i$1],from=range.from(),to=range.to();range.empty()&&(deleted&&deleted>0?from=Pos(from.line,from.ch-deleted):cm.state.overwrite&&!paste?to=Pos(to.line,Math.min(getLine(doc,to.line).text.length,to.ch+lst(textLines).length)):lastCopied&&lastCopied.lineWise&&lastCopied.text.join("\n")==inserted&&(from=to=Pos(from.line,0)));updateInput=cm.curOp.updateInput;var changeEvent={from:from,to:to,text:multiPaste?multiPaste[i$1%multiPaste.length]:textLines,origin:origin||(paste?"paste":cm.state.cutIncoming?"cut":"+input")};makeChange(cm.doc,changeEvent);signalLater(cm,"inputRead",cm,changeEvent)}inserted&&!paste&&triggerElectric(cm,inserted);ensureCursorVisible(cm);cm.curOp.updateInput=updateInput;cm.curOp.typing=!0;cm.state.pasteIncoming=cm.state.cutIncoming=!1}function handlePaste(e,cm){var pasted=e.clipboardData&&e.clipboardData.getData("Text");if(pasted){e.preventDefault();cm.isReadOnly()||cm.options.disableInput||runInOp(cm,function(){return applyTextInput(cm,pasted,0,null,"paste")});return!0}}function triggerElectric(cm,inserted){if(cm.options.electricChars&&cm.options.smartIndent)for(var sel=cm.doc.sel,i=sel.ranges.length-1;i>=0;i--){var range=sel.ranges[i];if(!(range.head.ch>100||i&&sel.ranges[i-1].head.line==range.head.line)){var mode=cm.getModeAt(range.head),indented=!1;if(mode.electricChars){for(var j=0;j<mode.electricChars.length;j++)if(inserted.indexOf(mode.electricChars.charAt(j))>-1){indented=indentLine(cm,range.head.line,"smart");break}}else mode.electricInput&&mode.electricInput.test(getLine(cm.doc,range.head.line).text.slice(0,range.head.ch))&&(indented=indentLine(cm,range.head.line,"smart"));indented&&signalLater(cm,"electricInput",cm,range.head.line)}}}function copyableRanges(cm){for(var text=[],ranges=[],i=0;i<cm.doc.sel.ranges.length;i++){var line=cm.doc.sel.ranges[i].head.line,lineRange={anchor:Pos(line,0),head:Pos(line+1,0)};ranges.push(lineRange);text.push(cm.getRange(lineRange.anchor,lineRange.head))}return{text:text,ranges:ranges}}function disableBrowserMagic(field,spellcheck){field.setAttribute("autocorrect","off");field.setAttribute("autocapitalize","off");field.setAttribute("spellcheck",!!spellcheck)}function hiddenTextarea(){var te=elt("textarea",null,null,"position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none"),div=elt("div",[te],null,"overflow: hidden; position: relative; width: 3px; height: 0px;");webkit?te.style.width="1000px":te.setAttribute("wrap","off");ios&&(te.style.border="1px solid black");disableBrowserMagic(te);return div}function addEditorMethods(CodeMirror){var optionHandlers=CodeMirror.optionHandlers,helpers=CodeMirror.helpers={};CodeMirror.prototype={constructor:CodeMirror,focus:function(){window.focus();this.display.input.focus()},setOption:function(option,value){var options=this.options,old=options[option];if(options[option]!=value||"mode"==option){options[option]=value;optionHandlers.hasOwnProperty(option)&&operation(this,optionHandlers[option])(this,value,old);signal(this,"optionChange",this,option)}},getOption:function(option){return this.options[option]},getDoc:function(){return this.doc},addKeyMap:function(map,bottom){this.state.keyMaps[bottom?"push":"unshift"](getKeyMap(map))},removeKeyMap:function(map){for(var maps=this.state.keyMaps,i=0;i<maps.length;++i)if(maps[i]==map||maps[i].name==map){maps.splice(i,1);return!0}},addOverlay:methodOp(function(spec,options){var mode=spec.token?spec:CodeMirror.getMode(this.options,spec);if(mode.startState)throw new Error("Overlays may not be stateful.");insertSorted(this.state.overlays,{mode:mode,modeSpec:spec,opaque:options&&options.opaque,priority:options&&options.priority||0},function(overlay){return overlay.priority});this.state.modeGen++;regChange(this)}),removeOverlay:methodOp(function(spec){for(var this$1=this,overlays=this.state.overlays,i=0;i<overlays.length;++i){var cur=overlays[i].modeSpec;if(cur==spec||"string"==typeof spec&&cur.name==spec){overlays.splice(i,1);this$1.state.modeGen++;regChange(this$1);return}}}),indentLine:methodOp(function(n,dir,aggressive){"string"!=typeof dir&&"number"!=typeof dir&&(dir=null==dir?this.options.smartIndent?"smart":"prev":dir?"add":"subtract");isLine(this.doc,n)&&indentLine(this,n,dir,aggressive)}),indentSelection:methodOp(function(how){for(var this$1=this,ranges=this.doc.sel.ranges,end=-1,i=0;i<ranges.length;i++){var range=ranges[i];if(range.empty()){if(range.head.line>end){indentLine(this$1,range.head.line,how,!0);end=range.head.line;i==this$1.doc.sel.primIndex&&ensureCursorVisible(this$1)}}else{var from=range.from(),to=range.to(),start=Math.max(end,from.line);end=Math.min(this$1.lastLine(),to.line-(to.ch?0:1))+1;for(var j=start;j<end;++j)indentLine(this$1,j,how);var newRanges=this$1.doc.sel.ranges;0==from.ch&&ranges.length==newRanges.length&&newRanges[i].from().ch>0&&replaceOneSelection(this$1.doc,i,new Range(from,newRanges[i].to()),sel_dontScroll)}}}),getTokenAt:function(pos,precise){return takeToken(this,pos,precise)},getLineTokens:function(line,precise){return takeToken(this,Pos(line),precise,!0)},getTokenTypeAt:function(pos){pos=clipPos(this.doc,pos);var type,styles=getLineStyles(this,getLine(this.doc,pos.line)),before=0,after=(styles.length-1)/2,ch=pos.ch;if(0==ch)type=styles[2];else for(;;){var mid=before+after>>1;if((mid?styles[2*mid-1]:0)>=ch)after=mid;else{if(!(styles[2*mid+1]<ch)){type=styles[2*mid+2];break}before=mid+1}}var cut=type?type.indexOf("overlay "):-1;return cut<0?type:0==cut?null:type.slice(0,cut-1)},getModeAt:function(pos){var mode=this.doc.mode;return mode.innerMode?CodeMirror.innerMode(mode,this.getTokenAt(pos).state).mode:mode},getHelper:function(pos,type){return this.getHelpers(pos,type)[0]},getHelpers:function(pos,type){var this$1=this,found=[];if(!helpers.hasOwnProperty(type))return found;var help=helpers[type],mode=this.getModeAt(pos);if("string"==typeof mode[type])help[mode[type]]&&found.push(help[mode[type]]);else if(mode[type])for(var i=0;i<mode[type].length;i++){var val=help[mode[type][i]];val&&found.push(val)}else mode.helperType&&help[mode.helperType]?found.push(help[mode.helperType]):help[mode.name]&&found.push(help[mode.name]);for(var i$1=0;i$1<help._global.length;i$1++){var cur=help._global[i$1];cur.pred(mode,this$1)&&indexOf(found,cur.val)==-1&&found.push(cur.val)}return found},getStateAfter:function(line,precise){var doc=this.doc;line=clipLine(doc,null==line?doc.first+doc.size-1:line);return getStateBefore(this,line+1,precise)},cursorCoords:function(start,mode){var pos,range=this.doc.sel.primary();pos=null==start?range.head:"object"==typeof start?clipPos(this.doc,start):start?range.from():range.to();return cursorCoords(this,pos,mode||"page")},charCoords:function(pos,mode){return charCoords(this,clipPos(this.doc,pos),mode||"page")},coordsChar:function(coords,mode){coords=fromCoordSystem(this,coords,mode||"page");return coordsChar(this,coords.left,coords.top)},lineAtHeight:function(height,mode){height=fromCoordSystem(this,{top:height,left:0},mode||"page").top;return lineAtHeight(this.doc,height+this.display.viewOffset)},heightAtLine:function(line,mode,includeWidgets){var lineObj,end=!1;if("number"==typeof line){var last=this.doc.first+this.doc.size-1;if(line<this.doc.first)line=this.doc.first;else if(line>last){line=last;end=!0}lineObj=getLine(this.doc,line)}else lineObj=line;return intoCoordSystem(this,lineObj,{top:0,left:0},mode||"page",includeWidgets).top+(end?this.doc.height-heightAtLine(lineObj):0)},defaultTextHeight:function(){return textHeight(this.display)},defaultCharWidth:function(){return charWidth(this.display)},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(pos,node,scroll,vert,horiz){var display=this.display;pos=cursorCoords(this,clipPos(this.doc,pos));var top=pos.bottom,left=pos.left;node.style.position="absolute";node.setAttribute("cm-ignore-events","true");this.display.input.setUneditable(node);display.sizer.appendChild(node);if("over"==vert)top=pos.top;else if("above"==vert||"near"==vert){var vspace=Math.max(display.wrapper.clientHeight,this.doc.height),hspace=Math.max(display.sizer.clientWidth,display.lineSpace.clientWidth);("above"==vert||pos.bottom+node.offsetHeight>vspace)&&pos.top>node.offsetHeight?top=pos.top-node.offsetHeight:pos.bottom+node.offsetHeight<=vspace&&(top=pos.bottom);left+node.offsetWidth>hspace&&(left=hspace-node.offsetWidth)}node.style.top=top+"px";node.style.left=node.style.right="";if("right"==horiz){left=display.sizer.clientWidth-node.offsetWidth;node.style.right="0px"}else{"left"==horiz?left=0:"middle"==horiz&&(left=(display.sizer.clientWidth-node.offsetWidth)/2);node.style.left=left+"px"}scroll&&scrollIntoView(this,left,top,left+node.offsetWidth,top+node.offsetHeight)},triggerOnKeyDown:methodOp(onKeyDown),triggerOnKeyPress:methodOp(onKeyPress),triggerOnKeyUp:onKeyUp,execCommand:function(cmd){if(commands.hasOwnProperty(cmd))return commands[cmd].call(null,this)},triggerElectric:methodOp(function(text){triggerElectric(this,text)}),findPosH:function(from,amount,unit,visually){var this$1=this,dir=1;if(amount<0){dir=-1;amount=-amount}for(var cur=clipPos(this.doc,from),i=0;i<amount;++i){cur=findPosH(this$1.doc,cur,dir,unit,visually);if(cur.hitSide)break}return cur},moveH:methodOp(function(dir,unit){var this$1=this;this.extendSelectionsBy(function(range){return this$1.display.shift||this$1.doc.extend||range.empty()?findPosH(this$1.doc,range.head,dir,unit,this$1.options.rtlMoveVisually):dir<0?range.from():range.to()},sel_move)}),deleteH:methodOp(function(dir,unit){var sel=this.doc.sel,doc=this.doc;sel.somethingSelected()?doc.replaceSelection("",null,"+delete"):deleteNearSelection(this,function(range){var other=findPosH(doc,range.head,dir,unit,!1);return dir<0?{from:other,to:range.head}:{from:range.head,to:other}})}),findPosV:function(from,amount,unit,goalColumn){var this$1=this,dir=1,x=goalColumn;if(amount<0){dir=-1;amount=-amount}for(var cur=clipPos(this.doc,from),i=0;i<amount;++i){var coords=cursorCoords(this$1,cur,"div");null==x?x=coords.left:coords.left=x;cur=findPosV(this$1,coords,dir,unit);if(cur.hitSide)break}return cur},moveV:methodOp(function(dir,unit){var this$1=this,doc=this.doc,goals=[],collapse=!this.display.shift&&!doc.extend&&doc.sel.somethingSelected();doc.extendSelectionsBy(function(range){if(collapse)return dir<0?range.from():range.to();var headPos=cursorCoords(this$1,range.head,"div");null!=range.goalColumn&&(headPos.left=range.goalColumn);goals.push(headPos.left);var pos=findPosV(this$1,headPos,dir,unit);"page"==unit&&range==doc.sel.primary()&&addToScrollPos(this$1,null,charCoords(this$1,pos,"div").top-headPos.top);return pos},sel_move);if(goals.length)for(var i=0;i<doc.sel.ranges.length;i++)doc.sel.ranges[i].goalColumn=goals[i]}),findWordAt:function(pos){var doc=this.doc,line=getLine(doc,pos.line).text,start=pos.ch,end=pos.ch;if(line){var helper=this.getHelper(pos,"wordChars");(pos.xRel<0||end==line.length)&&start?--start:++end;for(var startChar=line.charAt(start),check=isWordChar(startChar,helper)?function(ch){return isWordChar(ch,helper)}:/\s/.test(startChar)?function(ch){return/\s/.test(ch)}:function(ch){return!/\s/.test(ch)&&!isWordChar(ch)};start>0&&check(line.charAt(start-1));)--start;for(;end<line.length&&check(line.charAt(end));)++end}return new Range(Pos(pos.line,start),Pos(pos.line,end))},toggleOverwrite:function(value){if(null==value||value!=this.state.overwrite){(this.state.overwrite=!this.state.overwrite)?addClass(this.display.cursorDiv,"CodeMirror-overwrite"):rmClass(this.display.cursorDiv,"CodeMirror-overwrite");signal(this,"overwriteToggle",this,this.state.overwrite)}},hasFocus:function(){return this.display.input.getField()==activeElt()},isReadOnly:function(){return!(!this.options.readOnly&&!this.doc.cantEdit)},scrollTo:methodOp(function(x,y){null==x&&null==y||resolveScrollToPos(this);null!=x&&(this.curOp.scrollLeft=x);null!=y&&(this.curOp.scrollTop=y)}),getScrollInfo:function(){var scroller=this.display.scroller;return{left:scroller.scrollLeft,top:scroller.scrollTop,height:scroller.scrollHeight-scrollGap(this)-this.display.barHeight,width:scroller.scrollWidth-scrollGap(this)-this.display.barWidth,clientHeight:displayHeight(this),clientWidth:displayWidth(this)}},scrollIntoView:methodOp(function(range,margin){if(null==range){range={from:this.doc.sel.primary().head,to:null};null==margin&&(margin=this.options.cursorScrollMargin)}else"number"==typeof range?range={from:Pos(range,0),to:null}:null==range.from&&(range={from:range,to:null});range.to||(range.to=range.from);range.margin=margin||0;if(null!=range.from.line){resolveScrollToPos(this);this.curOp.scrollToPos=range}else{var sPos=calculateScrollPos(this,Math.min(range.from.left,range.to.left),Math.min(range.from.top,range.to.top)-range.margin,Math.max(range.from.right,range.to.right),Math.max(range.from.bottom,range.to.bottom)+range.margin);this.scrollTo(sPos.scrollLeft,sPos.scrollTop)}}),setSize:methodOp(function(width,height){var this$1=this,interpret=function(val){return"number"==typeof val||/^\d+$/.test(String(val))?val+"px":val};null!=width&&(this.display.wrapper.style.width=interpret(width));null!=height&&(this.display.wrapper.style.height=interpret(height));this.options.lineWrapping&&clearLineMeasurementCache(this);var lineNo=this.display.viewFrom;this.doc.iter(lineNo,this.display.viewTo,function(line){if(line.widgets)for(var i=0;i<line.widgets.length;i++)if(line.widgets[i].noHScroll){regLineChange(this$1,lineNo,"widget");break}++lineNo});this.curOp.forceUpdate=!0;signal(this,"refresh",this)}),operation:function(f){return runInOp(this,f)},refresh:methodOp(function(){var oldHeight=this.display.cachedTextHeight;regChange(this);this.curOp.forceUpdate=!0;clearCaches(this);this.scrollTo(this.doc.scrollLeft,this.doc.scrollTop);updateGutterSpace(this);(null==oldHeight||Math.abs(oldHeight-textHeight(this.display))>.5)&&estimateLineHeights(this);signal(this,"refresh",this)}),swapDoc:methodOp(function(doc){var old=this.doc;old.cm=null;attachDoc(this,doc);clearCaches(this);this.display.input.reset();this.scrollTo(doc.scrollLeft,doc.scrollTop);this.curOp.forceScroll=!0;signalLater(this,"swapDoc",this,old);return old}),getInputField:function(){return this.display.input.getField()},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}};eventMixin(CodeMirror);CodeMirror.registerHelper=function(type,name,value){helpers.hasOwnProperty(type)||(helpers[type]=CodeMirror[type]={_global:[]});helpers[type][name]=value};CodeMirror.registerGlobalHelper=function(type,name,predicate,value){CodeMirror.registerHelper(type,name,value);helpers[type]._global.push({pred:predicate,val:value})}}function findPosH(doc,pos,dir,unit,visually){function findNextLine(){var l=line+dir;if(l<doc.first||l>=doc.first+doc.size)return!1;line=l;return lineObj=getLine(doc,l)}function moveOnce(boundToLine){var next=(visually?moveVisually:moveLogically)(lineObj,ch,dir,!0);
6
+ if(null==next){if(boundToLine||!findNextLine())return!1;ch=visually?(dir<0?lineRight:lineLeft)(lineObj):dir<0?lineObj.text.length:0}else ch=next;return!0}var line=pos.line,ch=pos.ch,origDir=dir,lineObj=getLine(doc,line);if("char"==unit)moveOnce();else if("column"==unit)moveOnce(!0);else if("word"==unit||"group"==unit)for(var sawType=null,group="group"==unit,helper=doc.cm&&doc.cm.getHelper(pos,"wordChars"),first=!0;!(dir<0)||moveOnce(!first);first=!1){var cur=lineObj.text.charAt(ch)||"\n",type=isWordChar(cur,helper)?"w":group&&"\n"==cur?"n":!group||/\s/.test(cur)?null:"p";!group||first||type||(type="s");if(sawType&&sawType!=type){if(dir<0){dir=1;moveOnce()}break}type&&(sawType=type);if(dir>0&&!moveOnce(!first))break}var result=skipAtomic(doc,Pos(line,ch),pos,origDir,!0);cmp(pos,result)||(result.hitSide=!0);return result}function findPosV(cm,pos,dir,unit){var y,doc=cm.doc,x=pos.left;if("page"==unit){var pageSize=Math.min(cm.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight),moveAmount=Math.max(pageSize-.5*textHeight(cm.display),3);y=(dir>0?pos.bottom:pos.top)+dir*moveAmount}else"line"==unit&&(y=dir>0?pos.bottom+3:pos.top-3);for(var target;;){target=coordsChar(cm,x,y);if(!target.outside)break;if(dir<0?y<=0:y>=doc.height){target.hitSide=!0;break}y+=5*dir}return target}function posToDOM(cm,pos){var view=findViewForLine(cm,pos.line);if(!view||view.hidden)return null;var line=getLine(cm.doc,pos.line),info=mapFromLineView(view,line,pos.line),order=getOrder(line),side="left";if(order){var partPos=getBidiPartAt(order,pos.ch);side=partPos%2?"right":"left"}var result=nodeAndOffsetInLineMap(info.map,pos.ch,side);result.offset="right"==result.collapse?result.end:result.start;return result}function badPos(pos,bad){bad&&(pos.bad=!0);return pos}function domTextBetween(cm,from,to,fromLine,toLine){function recognizeMarker(id){return function(marker){return marker.id==id}}function walk(node){if(1==node.nodeType){var cmText=node.getAttribute("cm-text");if(null!=cmText){text+=""==cmText?node.textContent.replace(/\u200b/g,""):cmText;return}var range,markerID=node.getAttribute("cm-marker");if(markerID){var found=cm.findMarks(Pos(fromLine,0),Pos(toLine+1,0),recognizeMarker(+markerID));found.length&&(range=found[0].find())&&(text+=getBetween(cm.doc,range.from,range.to).join(lineSep));return}if("false"==node.getAttribute("contenteditable"))return;for(var i=0;i<node.childNodes.length;i++)walk(node.childNodes[i]);/^(pre|div|p)$/i.test(node.nodeName)&&(closing=!0)}else if(3==node.nodeType){var val=node.nodeValue;if(!val)return;if(closing){text+=lineSep;closing=!1}text+=val}}for(var text="",closing=!1,lineSep=cm.doc.lineSeparator();;){walk(from);if(from==to)break;from=from.nextSibling}return text}function domToPos(cm,node,offset){var lineNode;if(node==cm.display.lineDiv){lineNode=cm.display.lineDiv.childNodes[offset];if(!lineNode)return badPos(cm.clipPos(Pos(cm.display.viewTo-1)),!0);node=null;offset=0}else for(lineNode=node;;lineNode=lineNode.parentNode){if(!lineNode||lineNode==cm.display.lineDiv)return null;if(lineNode.parentNode&&lineNode.parentNode==cm.display.lineDiv)break}for(var i=0;i<cm.display.view.length;i++){var lineView=cm.display.view[i];if(lineView.node==lineNode)return locateNodeInLineView(lineView,node,offset)}}function locateNodeInLineView(lineView,node,offset){function find(textNode,topNode,offset){for(var i=-1;i<(maps?maps.length:0);i++)for(var map=i<0?measure.map:maps[i],j=0;j<map.length;j+=3){var curNode=map[j+2];if(curNode==textNode||curNode==topNode){var line=lineNo(i<0?lineView.line:lineView.rest[i]),ch=map[j]+offset;(offset<0||curNode!=textNode)&&(ch=map[j+(offset?1:0)]);return Pos(line,ch)}}}var wrapper=lineView.text.firstChild,bad=!1;if(!node||!contains(wrapper,node))return badPos(Pos(lineNo(lineView.line),0),!0);if(node==wrapper){bad=!0;node=wrapper.childNodes[offset];offset=0;if(!node){var line=lineView.rest?lst(lineView.rest):lineView.line;return badPos(Pos(lineNo(line),line.text.length),bad)}}var textNode=3==node.nodeType?node:null,topNode=node;if(!textNode&&1==node.childNodes.length&&3==node.firstChild.nodeType){textNode=node.firstChild;offset&&(offset=textNode.nodeValue.length)}for(;topNode.parentNode!=wrapper;)topNode=topNode.parentNode;var measure=lineView.measure,maps=measure.maps,found=find(textNode,topNode,offset);if(found)return badPos(found,bad);for(var after=topNode.nextSibling,dist=textNode?textNode.nodeValue.length-offset:0;after;after=after.nextSibling){found=find(after,after.firstChild,0);if(found)return badPos(Pos(found.line,found.ch-dist),bad);dist+=after.textContent.length}for(var before=topNode.previousSibling,dist$1=offset;before;before=before.previousSibling){found=find(before,before.firstChild,-1);if(found)return badPos(Pos(found.line,found.ch+dist$1),bad);dist$1+=before.textContent.length}}function fromTextArea(textarea,options){function save(){textarea.value=cm.getValue()}options=options?copyObj(options):{};options.value=textarea.value;!options.tabindex&&textarea.tabIndex&&(options.tabindex=textarea.tabIndex);!options.placeholder&&textarea.placeholder&&(options.placeholder=textarea.placeholder);if(null==options.autofocus){var hasFocus=activeElt();options.autofocus=hasFocus==textarea||null!=textarea.getAttribute("autofocus")&&hasFocus==document.body}var realSubmit;if(textarea.form){on(textarea.form,"submit",save);if(!options.leaveSubmitMethodAlone){var form=textarea.form;realSubmit=form.submit;try{var wrappedSubmit=form.submit=function(){save();form.submit=realSubmit;form.submit();form.submit=wrappedSubmit}}catch(e){}}}options.finishInit=function(cm){cm.save=save;cm.getTextArea=function(){return textarea};cm.toTextArea=function(){cm.toTextArea=isNaN;save();textarea.parentNode.removeChild(cm.getWrapperElement());textarea.style.display="";if(textarea.form){off(textarea.form,"submit",save);"function"==typeof textarea.form.submit&&(textarea.form.submit=realSubmit)}}};textarea.style.display="none";var cm=CodeMirror(function(node){return textarea.parentNode.insertBefore(node,textarea.nextSibling)},options);return cm}function addLegacyProps(CodeMirror){CodeMirror.off=off;CodeMirror.on=on;CodeMirror.wheelEventPixels=wheelEventPixels;CodeMirror.Doc=Doc;CodeMirror.splitLines=splitLinesAuto;CodeMirror.countColumn=countColumn;CodeMirror.findColumn=findColumn;CodeMirror.isWordChar=isWordCharBasic;CodeMirror.Pass=Pass;CodeMirror.signal=signal;CodeMirror.Line=Line;CodeMirror.changeEnd=changeEnd;CodeMirror.scrollbarModel=scrollbarModel;CodeMirror.Pos=Pos;CodeMirror.cmpPos=cmp;CodeMirror.modes=modes;CodeMirror.mimeModes=mimeModes;CodeMirror.resolveMode=resolveMode;CodeMirror.getMode=getMode;CodeMirror.modeExtensions=modeExtensions;CodeMirror.extendMode=extendMode;CodeMirror.copyState=copyState;CodeMirror.startState=startState;CodeMirror.innerMode=innerMode;CodeMirror.commands=commands;CodeMirror.keyMap=keyMap;CodeMirror.keyName=keyName;CodeMirror.isModifierKey=isModifierKey;CodeMirror.lookupKey=lookupKey;CodeMirror.normalizeKeyMap=normalizeKeyMap;CodeMirror.StringStream=StringStream;CodeMirror.SharedTextMarker=SharedTextMarker;CodeMirror.TextMarker=TextMarker;CodeMirror.LineWidget=LineWidget;CodeMirror.e_preventDefault=e_preventDefault;CodeMirror.e_stopPropagation=e_stopPropagation;CodeMirror.e_stop=e_stop;CodeMirror.addClass=addClass;CodeMirror.contains=contains;CodeMirror.rmClass=rmClass;CodeMirror.keyNames=keyNames}var userAgent=navigator.userAgent,platform=navigator.platform,gecko=/gecko\/\d/i.test(userAgent),ie_upto10=/MSIE \d/.test(userAgent),ie_11up=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent),ie=ie_upto10||ie_11up,ie_version=ie&&(ie_upto10?document.documentMode||6:ie_11up[1]),webkit=/WebKit\//.test(userAgent),qtwebkit=webkit&&/Qt\/\d+\.\d+/.test(userAgent),chrome=/Chrome\//.test(userAgent),presto=/Opera\//.test(userAgent),safari=/Apple Computer/.test(navigator.vendor),mac_geMountainLion=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent),phantom=/PhantomJS/.test(userAgent),ios=/AppleWebKit/.test(userAgent)&&/Mobile\/\w+/.test(userAgent),mobile=ios||/Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent),mac=ios||/Mac/.test(platform),chromeOS=/\bCrOS\b/.test(userAgent),windows=/win/i.test(platform),presto_version=presto&&userAgent.match(/Version\/(\d*\.\d*)/);presto_version&&(presto_version=Number(presto_version[1]));if(presto_version&&presto_version>=15){presto=!1;webkit=!0}var range,flipCtrlCmd=mac&&(qtwebkit||presto&&(null==presto_version||presto_version<12.11)),captureRightClick=gecko||ie&&ie_version>=9,rmClass=function(node,cls){var current=node.className,match=classTest(cls).exec(current);if(match){var after=current.slice(match.index+match[0].length);node.className=current.slice(0,match.index)+(after?match[1]+after:"")}};range=document.createRange?function(node,start,end,endNode){var r=document.createRange();r.setEnd(endNode||node,end);r.setStart(node,start);return r}:function(node,start,end){var r=document.body.createTextRange();try{r.moveToElementText(node.parentNode)}catch(e){return r}r.collapse(!0);r.moveEnd("character",end);r.moveStart("character",start);return r};var selectInput=function(node){node.select()};ios?selectInput=function(node){node.selectionStart=0;node.selectionEnd=node.value.length}:ie&&(selectInput=function(node){try{node.select()}catch(_e){}});Delayed.prototype.set=function(ms,f){clearTimeout(this.id);this.id=setTimeout(f,ms)};var zwspSupported,badBidiRects,scrollerGap=30,Pass={toString:function(){return"CodeMirror.Pass"}},sel_dontScroll={scroll:!1},sel_mouse={origin:"*mouse"},sel_move={origin:"+move"},spaceStrs=[""],nonASCIISingleCaseWordChar=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,extendingChars=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/,sawReadOnlySpans=!1,sawCollapsedSpans=!1,bidiOther=null,bidiOrdering=function(){function charType(code){return code<=247?lowTypes.charAt(code):1424<=code&&code<=1524?"R":1536<=code&&code<=1785?arabicTypes.charAt(code-1536):1774<=code&&code<=2220?"r":8192<=code&&code<=8203?"w":8204==code?"b":"L"}function BidiSpan(level,from,to){this.level=level;this.from=from;this.to=to}var lowTypes="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",arabicTypes="nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111",bidiRE=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,isNeutral=/[stwN]/,isStrong=/[LRr]/,countsAsLeft=/[Lb1n]/,countsAsNum=/[1n]/,outerType="L";return function(str){if(!bidiRE.test(str))return!1;for(var len=str.length,types=[],i=0;i<len;++i)types.push(charType(str.charCodeAt(i)));for(var i$1=0,prev=outerType;i$1<len;++i$1){var type=types[i$1];"m"==type?types[i$1]=prev:prev=type}for(var i$2=0,cur=outerType;i$2<len;++i$2){var type$1=types[i$2];if("1"==type$1&&"r"==cur)types[i$2]="n";else if(isStrong.test(type$1)){cur=type$1;"r"==type$1&&(types[i$2]="R")}}for(var i$3=1,prev$1=types[0];i$3<len-1;++i$3){var type$2=types[i$3];"+"==type$2&&"1"==prev$1&&"1"==types[i$3+1]?types[i$3]="1":","!=type$2||prev$1!=types[i$3+1]||"1"!=prev$1&&"n"!=prev$1||(types[i$3]=prev$1);prev$1=type$2}for(var i$4=0;i$4<len;++i$4){var type$3=types[i$4];if(","==type$3)types[i$4]="N";else if("%"==type$3){var end=void 0;for(end=i$4+1;end<len&&"%"==types[end];++end);for(var replace=i$4&&"!"==types[i$4-1]||end<len&&"1"==types[end]?"1":"N",j=i$4;j<end;++j)types[j]=replace;i$4=end-1}}for(var i$5=0,cur$1=outerType;i$5<len;++i$5){var type$4=types[i$5];"L"==cur$1&&"1"==type$4?types[i$5]="L":isStrong.test(type$4)&&(cur$1=type$4)}for(var i$6=0;i$6<len;++i$6)if(isNeutral.test(types[i$6])){var end$1=void 0;for(end$1=i$6+1;end$1<len&&isNeutral.test(types[end$1]);++end$1);for(var before="L"==(i$6?types[i$6-1]:outerType),after="L"==(end$1<len?types[end$1]:outerType),replace$1=before||after?"L":"R",j$1=i$6;j$1<end$1;++j$1)types[j$1]=replace$1;i$6=end$1-1}for(var m,order=[],i$7=0;i$7<len;)if(countsAsLeft.test(types[i$7])){var start=i$7;for(++i$7;i$7<len&&countsAsLeft.test(types[i$7]);++i$7);order.push(new BidiSpan(0,start,i$7))}else{var pos=i$7,at=order.length;for(++i$7;i$7<len&&"L"!=types[i$7];++i$7);for(var j$2=pos;j$2<i$7;)if(countsAsNum.test(types[j$2])){pos<j$2&&order.splice(at,0,new BidiSpan(1,pos,j$2));var nstart=j$2;for(++j$2;j$2<i$7&&countsAsNum.test(types[j$2]);++j$2);order.splice(at,0,new BidiSpan(2,nstart,j$2));pos=j$2}else++j$2;pos<i$7&&order.splice(at,0,new BidiSpan(1,pos,i$7))}if(1==order[0].level&&(m=str.match(/^\s+/))){order[0].from=m[0].length;order.unshift(new BidiSpan(0,0,m[0].length))}if(1==lst(order).level&&(m=str.match(/\s+$/))){lst(order).to-=m[0].length;order.push(new BidiSpan(0,len-m[0].length,len))}2==order[0].level&&order.unshift(new BidiSpan(1,order[0].to,order[0].to));order[0].level!=lst(order).level&&order.push(new BidiSpan(order[0].level,len,len));return order}}(),noHandlers=[],on=function(emitter,type,f){if(emitter.addEventListener)emitter.addEventListener(type,f,!1);else if(emitter.attachEvent)emitter.attachEvent("on"+type,f);else{var map=emitter._handlers||(emitter._handlers={});map[type]=(map[type]||noHandlers).concat(f)}},dragAndDrop=function(){if(ie&&ie_version<9)return!1;var div=elt("div");return"draggable"in div||"dragDrop"in div}(),splitLinesAuto=3!="\n\nb".split(/\n/).length?function(string){for(var pos=0,result=[],l=string.length;pos<=l;){var nl=string.indexOf("\n",pos);nl==-1&&(nl=string.length);var line=string.slice(pos,"\r"==string.charAt(nl-1)?nl-1:nl),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/)},hasSelection=window.getSelection?function(te){try{return te.selectionStart!=te.selectionEnd}catch(e){return!1}}:function(te){var range;try{range=te.ownerDocument.selection.createRange()}catch(e){}return!(!range||range.parentElement()!=te)&&0!=range.compareEndPoints("StartToEnd",range)},hasCopyEvent=function(){var e=elt("div");if("oncopy"in e)return!0;e.setAttribute("oncopy","return;");return"function"==typeof e.oncopy}(),badZoomedRects=null,modes={},mimeModes={},modeExtensions={},StringStream=function(string,tabSize){this.pos=this.start=0;this.string=string;this.tabSize=tabSize||8;this.lastColumnPos=this.lastColumnValue=0;this.lineStart=0};StringStream.prototype={eol:function(){return this.pos>=this.string.length},sol:function(){return this.pos==this.lineStart},peek:function(){return this.string.charAt(this.pos)||void 0},next:function(){if(this.pos<this.string.length)return this.string.charAt(this.pos++)},eat:function(match){var ok,ch=this.string.charAt(this.pos);ok="string"==typeof match?ch==match:ch&&(match.test?match.test(ch):match(ch));if(ok){++this.pos;return ch}},eatWhile:function(match){for(var start=this.pos;this.eat(match););return this.pos>start},eatSpace:function(){for(var this$1=this,start=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this$1.pos;return this.pos>start},skipToEnd:function(){this.pos=this.string.length},skipTo:function(ch){var found=this.string.indexOf(ch,this.pos);if(found>-1){this.pos=found;return!0}},backUp:function(n){this.pos-=n},column:function(){if(this.lastColumnPos<this.start){this.lastColumnValue=countColumn(this.string,this.start,this.tabSize,this.lastColumnPos,this.lastColumnValue);this.lastColumnPos=this.start}return this.lastColumnValue-(this.lineStart?countColumn(this.string,this.lineStart,this.tabSize):0)},indentation:function(){return countColumn(this.string,null,this.tabSize)-(this.lineStart?countColumn(this.string,this.lineStart,this.tabSize):0)},match:function(pattern,consume,caseInsensitive){if("string"!=typeof pattern){var match=this.string.slice(this.pos).match(pattern);if(match&&match.index>0)return null;match&&consume!==!1&&(this.pos+=match[0].length);return match}var cased=function(str){return caseInsensitive?str.toLowerCase():str},substr=this.string.substr(this.pos,pattern.length);if(cased(substr)==cased(pattern)){consume!==!1&&(this.pos+=pattern.length);return!0}},current:function(){return this.string.slice(this.start,this.pos)},hideFirstChars:function(n,inner){this.lineStart+=n;try{return inner()}finally{this.lineStart-=n}}};eventMixin(Line);Line.prototype.lineNo=function(){return lineNo(this)};var measureText,styleToClassCache={},styleToClassCacheWithMode={},operationGroup=null,orphanDelayedCallbacks=null,nullRect={left:0,right:0,top:0,bottom:0},wheelSamples=0,wheelPixelsPerUnit=null;ie?wheelPixelsPerUnit=-.53:gecko?wheelPixelsPerUnit=15:chrome?wheelPixelsPerUnit=-.7:safari&&(wheelPixelsPerUnit=-1/3);var NativeScrollbars=function(place,scroll,cm){this.cm=cm;var vert=this.vert=elt("div",[elt("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),horiz=this.horiz=elt("div",[elt("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");place(vert);place(horiz);on(vert,"scroll",function(){vert.clientHeight&&scroll(vert.scrollTop,"vertical")});on(horiz,"scroll",function(){horiz.clientWidth&&scroll(horiz.scrollLeft,"horizontal")});this.checkedZeroWidth=!1;ie&&ie_version<8&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px")};NativeScrollbars.prototype.update=function(measure){var needsH=measure.scrollWidth>measure.clientWidth+1,needsV=measure.scrollHeight>measure.clientHeight+1,sWidth=measure.nativeBarWidth;if(needsV){this.vert.style.display="block";this.vert.style.bottom=needsH?sWidth+"px":"0";var totalHeight=measure.viewHeight-(needsH?sWidth:0);this.vert.firstChild.style.height=Math.max(0,measure.scrollHeight-measure.clientHeight+totalHeight)+"px"}else{this.vert.style.display="";this.vert.firstChild.style.height="0"}if(needsH){this.horiz.style.display="block";this.horiz.style.right=needsV?sWidth+"px":"0";this.horiz.style.left=measure.barLeft+"px";var totalWidth=measure.viewWidth-measure.barLeft-(needsV?sWidth:0);this.horiz.firstChild.style.width=measure.scrollWidth-measure.clientWidth+totalWidth+"px"}else{this.horiz.style.display="";this.horiz.firstChild.style.width="0"}if(!this.checkedZeroWidth&&measure.clientHeight>0){0==sWidth&&this.zeroWidthHack();this.checkedZeroWidth=!0}return{right:needsV?sWidth:0,bottom:needsH?sWidth:0}};NativeScrollbars.prototype.setScrollLeft=function(pos){this.horiz.scrollLeft!=pos&&(this.horiz.scrollLeft=pos);this.disableHoriz&&this.enableZeroWidthBar(this.horiz,this.disableHoriz)};NativeScrollbars.prototype.setScrollTop=function(pos){this.vert.scrollTop!=pos&&(this.vert.scrollTop=pos);this.disableVert&&this.enableZeroWidthBar(this.vert,this.disableVert)};NativeScrollbars.prototype.zeroWidthHack=function(){var w=mac&&!mac_geMountainLion?"12px":"18px";this.horiz.style.height=this.vert.style.width=w;this.horiz.style.pointerEvents=this.vert.style.pointerEvents="none";this.disableHoriz=new Delayed;this.disableVert=new Delayed};NativeScrollbars.prototype.enableZeroWidthBar=function(bar,delay){function maybeDisable(){var box=bar.getBoundingClientRect(),elt=document.elementFromPoint(box.left+1,box.bottom-1);elt!=bar?bar.style.pointerEvents="none":delay.set(1e3,maybeDisable)}bar.style.pointerEvents="auto";delay.set(1e3,maybeDisable)};NativeScrollbars.prototype.clear=function(){var parent=this.horiz.parentNode;parent.removeChild(this.horiz);parent.removeChild(this.vert)};var NullScrollbars=function(){};NullScrollbars.prototype.update=function(){return{bottom:0,right:0}};NullScrollbars.prototype.setScrollLeft=function(){};NullScrollbars.prototype.setScrollTop=function(){};NullScrollbars.prototype.clear=function(){};var scrollbarModel={"native":NativeScrollbars,"null":NullScrollbars},nextOpId=0,DisplayUpdate=function(cm,viewport,force){var display=cm.display;this.viewport=viewport;this.visible=visibleLines(display,cm.doc,viewport);this.editorIsHidden=!display.wrapper.offsetWidth;this.wrapperHeight=display.wrapper.clientHeight;this.wrapperWidth=display.wrapper.clientWidth;this.oldDisplayWidth=displayWidth(cm);this.force=force;this.dims=getDimensions(cm);this.events=[]};DisplayUpdate.prototype.signal=function(emitter,type){hasHandler(emitter,type)&&this.events.push(arguments)};DisplayUpdate.prototype.finish=function(){for(var this$1=this,i=0;i<this.events.length;i++)signal.apply(null,this$1.events[i])};Selection.prototype={primary:function(){return this.ranges[this.primIndex]},equals:function(other){var this$1=this;if(other==this)return!0;if(other.primIndex!=this.primIndex||other.ranges.length!=this.ranges.length)return!1;for(var i=0;i<this.ranges.length;i++){var here=this$1.ranges[i],there=other.ranges[i];if(0!=cmp(here.anchor,there.anchor)||0!=cmp(here.head,there.head))return!1}return!0},deepCopy:function(){for(var this$1=this,out=[],i=0;i<this.ranges.length;i++)out[i]=new Range(copyPos(this$1.ranges[i].anchor),copyPos(this$1.ranges[i].head));return new Selection(out,this.primIndex)},somethingSelected:function(){for(var this$1=this,i=0;i<this.ranges.length;i++)if(!this$1.ranges[i].empty())return!0;return!1},contains:function(pos,end){var this$1=this;end||(end=pos);for(var i=0;i<this.ranges.length;i++){var range=this$1.ranges[i];if(cmp(end,range.from())>=0&&cmp(pos,range.to())<=0)return i}return-1}};Range.prototype={from:function(){return minPos(this.anchor,this.head)},to:function(){return maxPos(this.anchor,this.head)},empty:function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch}};LeafChunk.prototype={chunkSize:function(){return this.lines.length},removeInner:function(at,n){for(var this$1=this,i=at,e=at+n;i<e;++i){var line=this$1.lines[i];this$1.height-=line.height;cleanUpLine(line);signalLater(line,"delete")}this.lines.splice(at,n)},collapse:function(lines){lines.push.apply(lines,this.lines)},insertInner:function(at,lines,height){var this$1=this;this.height+=height;this.lines=this.lines.slice(0,at).concat(lines).concat(this.lines.slice(at));for(var i=0;i<lines.length;++i)lines[i].parent=this$1},iterN:function(at,n,op){for(var this$1=this,e=at+n;at<e;++at)if(op(this$1.lines[at]))return!0}};BranchChunk.prototype={chunkSize:function(){return this.size},removeInner:function(at,n){var this$1=this;this.size-=n;for(var i=0;i<this.children.length;++i){var child=this$1.children[i],sz=child.chunkSize();if(at<sz){var rm=Math.min(n,sz-at),oldHeight=child.height;child.removeInner(at,rm);this$1.height-=oldHeight-child.height;if(sz==rm){this$1.children.splice(i--,1);child.parent=null}if(0==(n-=rm))break;at=0}else at-=sz}if(this.size-n<25&&(this.children.length>1||!(this.children[0]instanceof LeafChunk))){var lines=[];this.collapse(lines);this.children=[new LeafChunk(lines)];this.children[0].parent=this}},collapse:function(lines){for(var this$1=this,i=0;i<this.children.length;++i)this$1.children[i].collapse(lines)},insertInner:function(at,lines,height){var this$1=this;this.size+=lines.length;this.height+=height;for(var i=0;i<this.children.length;++i){var child=this$1.children[i],sz=child.chunkSize();if(at<=sz){child.insertInner(at,lines,height);if(child.lines&&child.lines.length>50){for(var remaining=child.lines.length%25+25,pos=remaining;pos<child.lines.length;){var leaf=new LeafChunk(child.lines.slice(pos,pos+=25));child.height-=leaf.height;this$1.children.splice(++i,0,leaf);leaf.parent=this$1}child.lines=child.lines.slice(0,remaining);this$1.maybeSpill()}break}at-=sz}},maybeSpill:function(){if(!(this.children.length<=10)){var me=this;do{var spilled=me.children.splice(me.children.length-5,5),sibling=new BranchChunk(spilled);if(me.parent){me.size-=sibling.size;me.height-=sibling.height;var myIndex=indexOf(me.parent.children,me);me.parent.children.splice(myIndex+1,0,sibling)}else{var copy=new BranchChunk(me.children);copy.parent=me;me.children=[copy,sibling];me=copy}sibling.parent=me.parent}while(me.children.length>10);me.parent.maybeSpill()}},iterN:function(at,n,op){for(var this$1=this,i=0;i<this.children.length;++i){var child=this$1.children[i],sz=child.chunkSize();if(at<sz){var used=Math.min(n,sz-at);if(child.iterN(at,used,op))return!0;if(0==(n-=used))break;at=0}else at-=sz}}};eventMixin(LineWidget);LineWidget.prototype.clear=function(){var this$1=this,cm=this.doc.cm,ws=this.line.widgets,line=this.line,no=lineNo(line);if(null!=no&&ws){for(var i=0;i<ws.length;++i)ws[i]==this$1&&ws.splice(i--,1);ws.length||(line.widgets=null);var height=widgetHeight(this);updateLineHeight(line,Math.max(0,line.height-height));cm&&runInOp(cm,function(){adjustScrollWhenAboveVisible(cm,line,-height);regLineChange(cm,no,"widget")})}};LineWidget.prototype.changed=function(){var oldH=this.height,cm=this.doc.cm,line=this.line;this.height=null;var diff=widgetHeight(this)-oldH;if(diff){updateLineHeight(line,line.height+diff);cm&&runInOp(cm,function(){cm.curOp.forceUpdate=!0;adjustScrollWhenAboveVisible(cm,line,diff)})}};var nextMarkerId=0;eventMixin(TextMarker);TextMarker.prototype.clear=function(){var this$1=this;if(!this.explicitlyCleared){var cm=this.doc.cm,withOp=cm&&!cm.curOp;withOp&&startOperation(cm);if(hasHandler(this,"clear")){var found=this.find();found&&signalLater(this,"clear",found.from,found.to)}for(var min=null,max=null,i=0;i<this.lines.length;++i){var line=this$1.lines[i],span=getMarkedSpanFor(line.markedSpans,this$1);if(cm&&!this$1.collapsed)regLineChange(cm,lineNo(line),"text");else if(cm){null!=span.to&&(max=lineNo(line));null!=span.from&&(min=lineNo(line))}line.markedSpans=removeMarkedSpan(line.markedSpans,span);null==span.from&&this$1.collapsed&&!lineIsHidden(this$1.doc,line)&&cm&&updateLineHeight(line,textHeight(cm.display))}if(cm&&this.collapsed&&!cm.options.lineWrapping)for(var i$1=0;i$1<this.lines.length;++i$1){var visual=visualLine(this$1.lines[i$1]),len=lineLength(visual);if(len>cm.display.maxLineLength){cm.display.maxLine=visual;cm.display.maxLineLength=len;cm.display.maxLineChanged=!0}}null!=min&&cm&&this.collapsed&&regChange(cm,min,max+1);this.lines.length=0;this.explicitlyCleared=!0;if(this.atomic&&this.doc.cantEdit){this.doc.cantEdit=!1;cm&&reCheckSelection(cm.doc)}cm&&signalLater(cm,"markerCleared",cm,this);withOp&&endOperation(cm);this.parent&&this.parent.clear()}};TextMarker.prototype.find=function(side,lineObj){var this$1=this;null==side&&"bookmark"==this.type&&(side=1);for(var from,to,i=0;i<this.lines.length;++i){var line=this$1.lines[i],span=getMarkedSpanFor(line.markedSpans,this$1);if(null!=span.from){from=Pos(lineObj?line:lineNo(line),span.from);if(side==-1)return from}if(null!=span.to){to=Pos(lineObj?line:lineNo(line),span.to);if(1==side)return to}}return from&&{from:from,to:to}};TextMarker.prototype.changed=function(){var pos=this.find(-1,!0),widget=this,cm=this.doc.cm;pos&&cm&&runInOp(cm,function(){var line=pos.line,lineN=lineNo(pos.line),view=findViewForLine(cm,lineN);if(view){clearLineMeasurementCacheFor(view);cm.curOp.selectionChanged=cm.curOp.forceUpdate=!0}cm.curOp.updateMaxLine=!0;if(!lineIsHidden(widget.doc,line)&&null!=widget.height){var oldHeight=widget.height;widget.height=null;var dHeight=widgetHeight(widget)-oldHeight;dHeight&&updateLineHeight(line,line.height+dHeight)}})};TextMarker.prototype.attachLine=function(line){if(!this.lines.length&&this.doc.cm){var op=this.doc.cm.curOp;op.maybeHiddenMarkers&&indexOf(op.maybeHiddenMarkers,this)!=-1||(op.maybeUnhiddenMarkers||(op.maybeUnhiddenMarkers=[])).push(this)}this.lines.push(line)};TextMarker.prototype.detachLine=function(line){this.lines.splice(indexOf(this.lines,line),1);if(!this.lines.length&&this.doc.cm){var op=this.doc.cm.curOp;(op.maybeHiddenMarkers||(op.maybeHiddenMarkers=[])).push(this)}};eventMixin(SharedTextMarker);SharedTextMarker.prototype.clear=function(){var this$1=this;if(!this.explicitlyCleared){this.explicitlyCleared=!0;for(var i=0;i<this.markers.length;++i)this$1.markers[i].clear();signalLater(this,"clear")}};SharedTextMarker.prototype.find=function(side,lineObj){return this.primary.find(side,lineObj)};var nextDocId=0,Doc=function(text,mode,firstLine,lineSep){if(!(this instanceof Doc))return new Doc(text,mode,firstLine,lineSep);null==firstLine&&(firstLine=0);BranchChunk.call(this,[new LeafChunk([new Line("",null)])]);this.first=firstLine;this.scrollTop=this.scrollLeft=0;this.cantEdit=!1;this.cleanGeneration=1;this.frontier=firstLine;var start=Pos(firstLine,0);this.sel=simpleSelection(start);this.history=new History(null);this.id=++nextDocId;this.modeOption=mode;this.lineSep=lineSep;this.extend=!1;"string"==typeof text&&(text=this.splitLines(text));updateDoc(this,{from:start,to:start,text:text});setSelection(this,simpleSelection(start),sel_dontScroll)};Doc.prototype=createObj(BranchChunk.prototype,{constructor:Doc,iter:function(from,to,op){op?this.iterN(from-this.first,to-from,op):this.iterN(this.first,this.first+this.size,from)},insert:function(at,lines){for(var height=0,i=0;i<lines.length;++i)height+=lines[i].height;this.insertInner(at-this.first,lines,height)},remove:function(at,n){this.removeInner(at-this.first,n)},getValue:function(lineSep){var lines=getLines(this,this.first,this.first+this.size);return lineSep===!1?lines:lines.join(lineSep||this.lineSeparator())},setValue:docMethodOp(function(code){var top=Pos(this.first,0),last=this.first+this.size-1;makeChange(this,{from:top,to:Pos(last,getLine(this,last).text.length),text:this.splitLines(code),origin:"setValue",full:!0},!0);setSelection(this,simpleSelection(top))}),replaceRange:function(code,from,to,origin){from=clipPos(this,from);to=to?clipPos(this,to):from;replaceRange(this,code,from,to,origin)},getRange:function(from,to,lineSep){var lines=getBetween(this,clipPos(this,from),clipPos(this,to));return lineSep===!1?lines:lines.join(lineSep||this.lineSeparator())},getLine:function(line){var l=this.getLineHandle(line);return l&&l.text},getLineHandle:function(line){if(isLine(this,line))return getLine(this,line)},getLineNumber:function(line){return lineNo(line)},getLineHandleVisualStart:function(line){"number"==typeof line&&(line=getLine(this,line));return visualLine(line);
7
+ },lineCount:function(){return this.size},firstLine:function(){return this.first},lastLine:function(){return this.first+this.size-1},clipPos:function(pos){return clipPos(this,pos)},getCursor:function(start){var pos,range=this.sel.primary();pos=null==start||"head"==start?range.head:"anchor"==start?range.anchor:"end"==start||"to"==start||start===!1?range.to():range.from();return pos},listSelections:function(){return this.sel.ranges},somethingSelected:function(){return this.sel.somethingSelected()},setCursor:docMethodOp(function(line,ch,options){setSimpleSelection(this,clipPos(this,"number"==typeof line?Pos(line,ch||0):line),null,options)}),setSelection:docMethodOp(function(anchor,head,options){setSimpleSelection(this,clipPos(this,anchor),clipPos(this,head||anchor),options)}),extendSelection:docMethodOp(function(head,other,options){extendSelection(this,clipPos(this,head),other&&clipPos(this,other),options)}),extendSelections:docMethodOp(function(heads,options){extendSelections(this,clipPosArray(this,heads),options)}),extendSelectionsBy:docMethodOp(function(f,options){var heads=map(this.sel.ranges,f);extendSelections(this,clipPosArray(this,heads),options)}),setSelections:docMethodOp(function(ranges,primary,options){var this$1=this;if(ranges.length){for(var out=[],i=0;i<ranges.length;i++)out[i]=new Range(clipPos(this$1,ranges[i].anchor),clipPos(this$1,ranges[i].head));null==primary&&(primary=Math.min(ranges.length-1,this.sel.primIndex));setSelection(this,normalizeSelection(out,primary),options)}}),addSelection:docMethodOp(function(anchor,head,options){var ranges=this.sel.ranges.slice(0);ranges.push(new Range(clipPos(this,anchor),clipPos(this,head||anchor)));setSelection(this,normalizeSelection(ranges,ranges.length-1),options)}),getSelection:function(lineSep){for(var lines,this$1=this,ranges=this.sel.ranges,i=0;i<ranges.length;i++){var sel=getBetween(this$1,ranges[i].from(),ranges[i].to());lines=lines?lines.concat(sel):sel}return lineSep===!1?lines:lines.join(lineSep||this.lineSeparator())},getSelections:function(lineSep){for(var this$1=this,parts=[],ranges=this.sel.ranges,i=0;i<ranges.length;i++){var sel=getBetween(this$1,ranges[i].from(),ranges[i].to());lineSep!==!1&&(sel=sel.join(lineSep||this$1.lineSeparator()));parts[i]=sel}return parts},replaceSelection:function(code,collapse,origin){for(var dup=[],i=0;i<this.sel.ranges.length;i++)dup[i]=code;this.replaceSelections(dup,collapse,origin||"+input")},replaceSelections:docMethodOp(function(code,collapse,origin){for(var this$1=this,changes=[],sel=this.sel,i=0;i<sel.ranges.length;i++){var range=sel.ranges[i];changes[i]={from:range.from(),to:range.to(),text:this$1.splitLines(code[i]),origin:origin}}for(var newSel=collapse&&"end"!=collapse&&computeReplacedSel(this,changes,collapse),i$1=changes.length-1;i$1>=0;i$1--)makeChange(this$1,changes[i$1]);newSel?setSelectionReplaceHistory(this,newSel):this.cm&&ensureCursorVisible(this.cm)}),undo:docMethodOp(function(){makeChangeFromHistory(this,"undo")}),redo:docMethodOp(function(){makeChangeFromHistory(this,"redo")}),undoSelection:docMethodOp(function(){makeChangeFromHistory(this,"undo",!0)}),redoSelection:docMethodOp(function(){makeChangeFromHistory(this,"redo",!0)}),setExtending:function(val){this.extend=val},getExtending:function(){return this.extend},historySize:function(){for(var hist=this.history,done=0,undone=0,i=0;i<hist.done.length;i++)hist.done[i].ranges||++done;for(var i$1=0;i$1<hist.undone.length;i$1++)hist.undone[i$1].ranges||++undone;return{undo:done,redo:undone}},clearHistory:function(){this.history=new History(this.history.maxGeneration)},markClean:function(){this.cleanGeneration=this.changeGeneration(!0)},changeGeneration:function(forceSplit){forceSplit&&(this.history.lastOp=this.history.lastSelOp=this.history.lastOrigin=null);return this.history.generation},isClean:function(gen){return this.history.generation==(gen||this.cleanGeneration)},getHistory:function(){return{done:copyHistoryArray(this.history.done),undone:copyHistoryArray(this.history.undone)}},setHistory:function(histData){var hist=this.history=new History(this.history.maxGeneration);hist.done=copyHistoryArray(histData.done.slice(0),null,!0);hist.undone=copyHistoryArray(histData.undone.slice(0),null,!0)},setGutterMarker:docMethodOp(function(line,gutterID,value){return changeLine(this,line,"gutter",function(line){var markers=line.gutterMarkers||(line.gutterMarkers={});markers[gutterID]=value;!value&&isEmpty(markers)&&(line.gutterMarkers=null);return!0})}),clearGutter:docMethodOp(function(gutterID){var this$1=this,i=this.first;this.iter(function(line){line.gutterMarkers&&line.gutterMarkers[gutterID]&&changeLine(this$1,line,"gutter",function(){line.gutterMarkers[gutterID]=null;isEmpty(line.gutterMarkers)&&(line.gutterMarkers=null);return!0});++i})}),lineInfo:function(line){var n;if("number"==typeof line){if(!isLine(this,line))return null;n=line;line=getLine(this,line);if(!line)return null}else{n=lineNo(line);if(null==n)return null}return{line:n,handle:line,text:line.text,gutterMarkers:line.gutterMarkers,textClass:line.textClass,bgClass:line.bgClass,wrapClass:line.wrapClass,widgets:line.widgets}},addLineClass:docMethodOp(function(handle,where,cls){return changeLine(this,handle,"gutter"==where?"gutter":"class",function(line){var prop="text"==where?"textClass":"background"==where?"bgClass":"gutter"==where?"gutterClass":"wrapClass";if(line[prop]){if(classTest(cls).test(line[prop]))return!1;line[prop]+=" "+cls}else line[prop]=cls;return!0})}),removeLineClass:docMethodOp(function(handle,where,cls){return changeLine(this,handle,"gutter"==where?"gutter":"class",function(line){var prop="text"==where?"textClass":"background"==where?"bgClass":"gutter"==where?"gutterClass":"wrapClass",cur=line[prop];if(!cur)return!1;if(null==cls)line[prop]=null;else{var found=cur.match(classTest(cls));if(!found)return!1;var end=found.index+found[0].length;line[prop]=cur.slice(0,found.index)+(found.index&&end!=cur.length?" ":"")+cur.slice(end)||null}return!0})}),addLineWidget:docMethodOp(function(handle,node,options){return addLineWidget(this,handle,node,options)}),removeLineWidget:function(widget){widget.clear()},markText:function(from,to,options){return markText(this,clipPos(this,from),clipPos(this,to),options,options&&options.type||"range")},setBookmark:function(pos,options){var realOpts={replacedWith:options&&(null==options.nodeType?options.widget:options),insertLeft:options&&options.insertLeft,clearWhenEmpty:!1,shared:options&&options.shared,handleMouseEvents:options&&options.handleMouseEvents};pos=clipPos(this,pos);return markText(this,pos,pos,realOpts,"bookmark")},findMarksAt:function(pos){pos=clipPos(this,pos);var markers=[],spans=getLine(this,pos.line).markedSpans;if(spans)for(var i=0;i<spans.length;++i){var span=spans[i];(null==span.from||span.from<=pos.ch)&&(null==span.to||span.to>=pos.ch)&&markers.push(span.marker.parent||span.marker)}return markers},findMarks:function(from,to,filter){from=clipPos(this,from);to=clipPos(this,to);var found=[],lineNo=from.line;this.iter(from.line,to.line+1,function(line){var spans=line.markedSpans;if(spans)for(var i=0;i<spans.length;i++){var span=spans[i];null!=span.to&&lineNo==from.line&&from.ch>=span.to||null==span.from&&lineNo!=from.line||null!=span.from&&lineNo==to.line&&span.from>=to.ch||filter&&!filter(span.marker)||found.push(span.marker.parent||span.marker)}++lineNo});return found},getAllMarks:function(){var markers=[];this.iter(function(line){var sps=line.markedSpans;if(sps)for(var i=0;i<sps.length;++i)null!=sps[i].from&&markers.push(sps[i].marker)});return markers},posFromIndex:function(off){var ch,lineNo=this.first,sepSize=this.lineSeparator().length;this.iter(function(line){var sz=line.text.length+sepSize;if(sz>off){ch=off;return!0}off-=sz;++lineNo});return clipPos(this,Pos(lineNo,ch))},indexFromPos:function(coords){coords=clipPos(this,coords);var index=coords.ch;if(coords.line<this.first||coords.ch<0)return 0;var sepSize=this.lineSeparator().length;this.iter(this.first,coords.line,function(line){index+=line.text.length+sepSize});return index},copy:function(copyHistory){var doc=new Doc(getLines(this,this.first,this.first+this.size),this.modeOption,this.first,this.lineSep);doc.scrollTop=this.scrollTop;doc.scrollLeft=this.scrollLeft;doc.sel=this.sel;doc.extend=!1;if(copyHistory){doc.history.undoDepth=this.history.undoDepth;doc.setHistory(this.getHistory())}return doc},linkedDoc:function(options){options||(options={});var from=this.first,to=this.first+this.size;null!=options.from&&options.from>from&&(from=options.from);null!=options.to&&options.to<to&&(to=options.to);var copy=new Doc(getLines(this,from,to),options.mode||this.modeOption,from,this.lineSep);options.sharedHist&&(copy.history=this.history);(this.linked||(this.linked=[])).push({doc:copy,sharedHist:options.sharedHist});copy.linked=[{doc:this,isParent:!0,sharedHist:options.sharedHist}];copySharedMarkers(copy,findSharedMarkers(this));return copy},unlinkDoc:function(other){var this$1=this;other instanceof CodeMirror&&(other=other.doc);if(this.linked)for(var i=0;i<this.linked.length;++i){var link=this$1.linked[i];if(link.doc==other){this$1.linked.splice(i,1);other.unlinkDoc(this$1);detachSharedMarkers(findSharedMarkers(this$1));break}}if(other.history==this.history){var splitIds=[other.id];linkedDocs(other,function(doc){return splitIds.push(doc.id)},!0);other.history=new History(null);other.history.done=copyHistoryArray(this.history.done,splitIds);other.history.undone=copyHistoryArray(this.history.undone,splitIds)}},iterLinkedDocs:function(f){linkedDocs(this,f)},getMode:function(){return this.mode},getEditor:function(){return this.cm},splitLines:function(str){return this.lineSep?str.split(this.lineSep):splitLinesAuto(str)},lineSeparator:function(){return this.lineSep||"\n"}});Doc.prototype.eachLine=Doc.prototype.iter;for(var lastDrop=0,globalsRegistered=!1,keyNames={3:"Enter",8:"Backspace",9:"Tab",13:"Enter",16:"Shift",17:"Ctrl",18:"Alt",19:"Pause",20:"CapsLock",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"Left",38:"Up",39:"Right",40:"Down",44:"PrintScrn",45:"Insert",46:"Delete",59:";",61:"=",91:"Mod",92:"Mod",93:"Mod",106:"*",107:"=",109:"-",110:".",111:"/",127:"Delete",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'",63232:"Up",63233:"Down",63234:"Left",63235:"Right",63272:"Delete",63273:"Home",63275:"End",63276:"PageUp",63277:"PageDown",63302:"Insert"},i=0;i<10;i++)keyNames[i+48]=keyNames[i+96]=String(i);for(var i$1=65;i$1<=90;i$1++)keyNames[i$1]=String.fromCharCode(i$1);for(var i$2=1;i$2<=12;i$2++)keyNames[i$2+111]=keyNames[i$2+63235]="F"+i$2;var keyMap={};keyMap.basic={Left:"goCharLeft",Right:"goCharRight",Up:"goLineUp",Down:"goLineDown",End:"goLineEnd",Home:"goLineStartSmart",PageUp:"goPageUp",PageDown:"goPageDown",Delete:"delCharAfter",Backspace:"delCharBefore","Shift-Backspace":"delCharBefore",Tab:"defaultTab","Shift-Tab":"indentAuto",Enter:"newlineAndIndent",Insert:"toggleOverwrite",Esc:"singleSelection"};keyMap.pcDefault={"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Up":"goLineUp","Ctrl-Down":"goLineDown","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev","Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection",fallthrough:"basic"};keyMap.emacsy={"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Alt-F":"goWordRight","Alt-B":"goWordLeft","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-D":"delWordAfter","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars","Ctrl-O":"openLine"};keyMap.macDefault={"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Home":"goDocStart","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineLeft","Cmd-Right":"goLineRight","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace","Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delWrappedLineLeft","Cmd-Delete":"delWrappedLineRight","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection","Ctrl-Up":"goDocStart","Ctrl-Down":"goDocEnd",fallthrough:["basic","emacsy"]};keyMap["default"]=mac?keyMap.macDefault:keyMap.pcDefault;var lastClick,lastDoubleClick,commands={selectAll:selectAll,singleSelection:function(cm){return cm.setSelection(cm.getCursor("anchor"),cm.getCursor("head"),sel_dontScroll)},killLine:function(cm){return deleteNearSelection(cm,function(range){if(range.empty()){var len=getLine(cm.doc,range.head.line).text.length;return range.head.ch==len&&range.head.line<cm.lastLine()?{from:range.head,to:Pos(range.head.line+1,0)}:{from:range.head,to:Pos(range.head.line,len)}}return{from:range.from(),to:range.to()}})},deleteLine:function(cm){return deleteNearSelection(cm,function(range){return{from:Pos(range.from().line,0),to:clipPos(cm.doc,Pos(range.to().line+1,0))}})},delLineLeft:function(cm){return deleteNearSelection(cm,function(range){return{from:Pos(range.from().line,0),to:range.from()}})},delWrappedLineLeft:function(cm){return deleteNearSelection(cm,function(range){var top=cm.charCoords(range.head,"div").top+5,leftPos=cm.coordsChar({left:0,top:top},"div");return{from:leftPos,to:range.from()}})},delWrappedLineRight:function(cm){return deleteNearSelection(cm,function(range){var top=cm.charCoords(range.head,"div").top+5,rightPos=cm.coordsChar({left:cm.display.lineDiv.offsetWidth+100,top:top},"div");return{from:range.from(),to:rightPos}})},undo:function(cm){return cm.undo()},redo:function(cm){return cm.redo()},undoSelection:function(cm){return cm.undoSelection()},redoSelection:function(cm){return cm.redoSelection()},goDocStart:function(cm){return cm.extendSelection(Pos(cm.firstLine(),0))},goDocEnd:function(cm){return cm.extendSelection(Pos(cm.lastLine()))},goLineStart:function(cm){return cm.extendSelectionsBy(function(range){return lineStart(cm,range.head.line)},{origin:"+move",bias:1})},goLineStartSmart:function(cm){return cm.extendSelectionsBy(function(range){return lineStartSmart(cm,range.head)},{origin:"+move",bias:1})},goLineEnd:function(cm){return cm.extendSelectionsBy(function(range){return lineEnd(cm,range.head.line)},{origin:"+move",bias:-1})},goLineRight:function(cm){return cm.extendSelectionsBy(function(range){var top=cm.charCoords(range.head,"div").top+5;return cm.coordsChar({left:cm.display.lineDiv.offsetWidth+100,top:top},"div")},sel_move)},goLineLeft:function(cm){return cm.extendSelectionsBy(function(range){var top=cm.charCoords(range.head,"div").top+5;return cm.coordsChar({left:0,top:top},"div")},sel_move)},goLineLeftSmart:function(cm){return cm.extendSelectionsBy(function(range){var top=cm.charCoords(range.head,"div").top+5,pos=cm.coordsChar({left:0,top:top},"div");return pos.ch<cm.getLine(pos.line).search(/\S/)?lineStartSmart(cm,range.head):pos},sel_move)},goLineUp:function(cm){return cm.moveV(-1,"line")},goLineDown:function(cm){return cm.moveV(1,"line")},goPageUp:function(cm){return cm.moveV(-1,"page")},goPageDown:function(cm){return cm.moveV(1,"page")},goCharLeft:function(cm){return cm.moveH(-1,"char")},goCharRight:function(cm){return cm.moveH(1,"char")},goColumnLeft:function(cm){return cm.moveH(-1,"column")},goColumnRight:function(cm){return cm.moveH(1,"column")},goWordLeft:function(cm){return cm.moveH(-1,"word")},goGroupRight:function(cm){return cm.moveH(1,"group")},goGroupLeft:function(cm){return cm.moveH(-1,"group")},goWordRight:function(cm){return cm.moveH(1,"word")},delCharBefore:function(cm){return cm.deleteH(-1,"char")},delCharAfter:function(cm){return cm.deleteH(1,"char")},delWordBefore:function(cm){return cm.deleteH(-1,"word")},delWordAfter:function(cm){return cm.deleteH(1,"word")},delGroupBefore:function(cm){return cm.deleteH(-1,"group")},delGroupAfter:function(cm){return cm.deleteH(1,"group")},indentAuto:function(cm){return cm.indentSelection("smart")},indentMore:function(cm){return cm.indentSelection("add")},indentLess:function(cm){return cm.indentSelection("subtract")},insertTab:function(cm){return cm.replaceSelection("\t")},insertSoftTab:function(cm){for(var spaces=[],ranges=cm.listSelections(),tabSize=cm.options.tabSize,i=0;i<ranges.length;i++){var pos=ranges[i].from(),col=countColumn(cm.getLine(pos.line),pos.ch,tabSize);spaces.push(spaceStr(tabSize-col%tabSize))}cm.replaceSelections(spaces)},defaultTab:function(cm){cm.somethingSelected()?cm.indentSelection("add"):cm.execCommand("insertTab")},transposeChars:function(cm){return runInOp(cm,function(){for(var ranges=cm.listSelections(),newSel=[],i=0;i<ranges.length;i++)if(ranges[i].empty()){var cur=ranges[i].head,line=getLine(cm.doc,cur.line).text;if(line){cur.ch==line.length&&(cur=new Pos(cur.line,cur.ch-1));if(cur.ch>0){cur=new Pos(cur.line,cur.ch+1);cm.replaceRange(line.charAt(cur.ch-1)+line.charAt(cur.ch-2),Pos(cur.line,cur.ch-2),cur,"+transpose")}else if(cur.line>cm.doc.first){var prev=getLine(cm.doc,cur.line-1).text;if(prev){cur=new Pos(cur.line,1);cm.replaceRange(line.charAt(0)+cm.doc.lineSeparator()+prev.charAt(prev.length-1),Pos(cur.line-1,prev.length-1),cur,"+transpose")}}}newSel.push(new Range(cur,cur))}cm.setSelections(newSel)})},newlineAndIndent:function(cm){return runInOp(cm,function(){for(var sels=cm.listSelections(),i=sels.length-1;i>=0;i--)cm.replaceRange(cm.doc.lineSeparator(),sels[i].anchor,sels[i].head,"+input");sels=cm.listSelections();for(var i$1=0;i$1<sels.length;i$1++)cm.indentLine(sels[i$1].from().line,null,!0);ensureCursorVisible(cm)})},openLine:function(cm){return cm.replaceSelection("\n","start")},toggleOverwrite:function(cm){return cm.toggleOverwrite()}},stopSeq=new Delayed,lastStoppedKey=null,Init={toString:function(){return"CodeMirror.Init"}},defaults={},optionHandlers={};CodeMirror.defaults=defaults;CodeMirror.optionHandlers=optionHandlers;var initHooks=[];CodeMirror.defineInitHook=function(f){return initHooks.push(f)};var lastCopied=null,ContentEditableInput=function(cm){this.cm=cm;this.lastAnchorNode=this.lastAnchorOffset=this.lastFocusNode=this.lastFocusOffset=null;this.polling=new Delayed;this.composing=null;this.gracePeriod=!1;this.readDOMTimeout=null};ContentEditableInput.prototype.init=function(display){function onCopyCut(e){if(!signalDOMEvent(cm,e)){if(cm.somethingSelected()){setLastCopied({lineWise:!1,text:cm.getSelections()});"cut"==e.type&&cm.replaceSelection("",null,"cut")}else{if(!cm.options.lineWiseCopyCut)return;var ranges=copyableRanges(cm);setLastCopied({lineWise:!0,text:ranges.text});"cut"==e.type&&cm.operation(function(){cm.setSelections(ranges.ranges,0,sel_dontScroll);cm.replaceSelection("",null,"cut")})}if(e.clipboardData){e.clipboardData.clearData();var content=lastCopied.text.join("\n");e.clipboardData.setData("Text",content);if(e.clipboardData.getData("Text")==content){e.preventDefault();return}}var kludge=hiddenTextarea(),te=kludge.firstChild;cm.display.lineSpace.insertBefore(kludge,cm.display.lineSpace.firstChild);te.value=lastCopied.text.join("\n");var hadFocus=document.activeElement;selectInput(te);setTimeout(function(){cm.display.lineSpace.removeChild(kludge);hadFocus.focus();hadFocus==div&&input.showPrimarySelection()},50)}}var this$1=this,input=this,cm=input.cm,div=input.div=display.lineDiv;disableBrowserMagic(div,cm.options.spellcheck);on(div,"paste",function(e){signalDOMEvent(cm,e)||handlePaste(e,cm)||ie_version<=11&&setTimeout(operation(cm,function(){input.pollContent()||regChange(cm)}),20)});on(div,"compositionstart",function(e){this$1.composing={data:e.data,done:!1}});on(div,"compositionupdate",function(e){this$1.composing||(this$1.composing={data:e.data,done:!1})});on(div,"compositionend",function(e){if(this$1.composing){e.data!=this$1.composing.data&&this$1.readFromDOMSoon();this$1.composing.done=!0}});on(div,"touchstart",function(){return input.forceCompositionEnd()});on(div,"input",function(){this$1.composing||this$1.readFromDOMSoon()});on(div,"copy",onCopyCut);on(div,"cut",onCopyCut)};ContentEditableInput.prototype.prepareSelection=function(){var result=prepareSelection(this.cm,!1);result.focus=this.cm.state.focused;return result};ContentEditableInput.prototype.showSelection=function(info,takeFocus){if(info&&this.cm.display.view.length){(info.focus||takeFocus)&&this.showPrimarySelection();this.showMultipleSelections(info)}};ContentEditableInput.prototype.showPrimarySelection=function(){var sel=window.getSelection(),prim=this.cm.doc.sel.primary(),curAnchor=domToPos(this.cm,sel.anchorNode,sel.anchorOffset),curFocus=domToPos(this.cm,sel.focusNode,sel.focusOffset);if(!curAnchor||curAnchor.bad||!curFocus||curFocus.bad||0!=cmp(minPos(curAnchor,curFocus),prim.from())||0!=cmp(maxPos(curAnchor,curFocus),prim.to())){var start=posToDOM(this.cm,prim.from()),end=posToDOM(this.cm,prim.to());if(start||end){var view=this.cm.display.view,old=sel.rangeCount&&sel.getRangeAt(0);if(start){if(!end){var measure=view[view.length-1].measure,map=measure.maps?measure.maps[measure.maps.length-1]:measure.map;end={node:map[map.length-1],offset:map[map.length-2]-map[map.length-3]}}}else start={node:view[0].measure.map[2],offset:0};var rng;try{rng=range(start.node,start.offset,end.offset,end.node)}catch(e){}if(rng){if(!gecko&&this.cm.state.focused){sel.collapse(start.node,start.offset);if(!rng.collapsed){sel.removeAllRanges();sel.addRange(rng)}}else{sel.removeAllRanges();sel.addRange(rng)}old&&null==sel.anchorNode?sel.addRange(old):gecko&&this.startGracePeriod()}this.rememberSelection()}}};ContentEditableInput.prototype.startGracePeriod=function(){var this$1=this;clearTimeout(this.gracePeriod);this.gracePeriod=setTimeout(function(){this$1.gracePeriod=!1;this$1.selectionChanged()&&this$1.cm.operation(function(){return this$1.cm.curOp.selectionChanged=!0})},20)};ContentEditableInput.prototype.showMultipleSelections=function(info){removeChildrenAndAdd(this.cm.display.cursorDiv,info.cursors);removeChildrenAndAdd(this.cm.display.selectionDiv,info.selection)};ContentEditableInput.prototype.rememberSelection=function(){var sel=window.getSelection();this.lastAnchorNode=sel.anchorNode;this.lastAnchorOffset=sel.anchorOffset;this.lastFocusNode=sel.focusNode;this.lastFocusOffset=sel.focusOffset};ContentEditableInput.prototype.selectionInEditor=function(){var sel=window.getSelection();if(!sel.rangeCount)return!1;var node=sel.getRangeAt(0).commonAncestorContainer;return contains(this.div,node)};ContentEditableInput.prototype.focus=function(){if("nocursor"!=this.cm.options.readOnly){this.selectionInEditor()||this.showSelection(this.prepareSelection(),!0);this.div.focus()}};ContentEditableInput.prototype.blur=function(){this.div.blur()};ContentEditableInput.prototype.getField=function(){return this.div};ContentEditableInput.prototype.supportsTouch=function(){return!0};ContentEditableInput.prototype.receivedFocus=function(){function poll(){if(input.cm.state.focused){input.pollSelection();input.polling.set(input.cm.options.pollInterval,poll)}}var input=this;this.selectionInEditor()?this.pollSelection():runInOp(this.cm,function(){return input.cm.curOp.selectionChanged=!0});this.polling.set(this.cm.options.pollInterval,poll)};ContentEditableInput.prototype.selectionChanged=function(){var sel=window.getSelection();return sel.anchorNode!=this.lastAnchorNode||sel.anchorOffset!=this.lastAnchorOffset||sel.focusNode!=this.lastFocusNode||sel.focusOffset!=this.lastFocusOffset};ContentEditableInput.prototype.pollSelection=function(){if(!this.composing&&null==this.readDOMTimeout&&!this.gracePeriod&&this.selectionChanged()){var sel=window.getSelection(),cm=this.cm;this.rememberSelection();var anchor=domToPos(cm,sel.anchorNode,sel.anchorOffset),head=domToPos(cm,sel.focusNode,sel.focusOffset);anchor&&head&&runInOp(cm,function(){setSelection(cm.doc,simpleSelection(anchor,head),sel_dontScroll);(anchor.bad||head.bad)&&(cm.curOp.selectionChanged=!0)})}};ContentEditableInput.prototype.pollContent=function(){if(null!=this.readDOMTimeout){clearTimeout(this.readDOMTimeout);this.readDOMTimeout=null}var cm=this.cm,display=cm.display,sel=cm.doc.sel.primary(),from=sel.from(),to=sel.to();0==from.ch&&from.line>cm.firstLine()&&(from=Pos(from.line-1,getLine(cm.doc,from.line-1).length));to.ch==getLine(cm.doc,to.line).text.length&&to.line<cm.lastLine()&&(to=Pos(to.line+1,0));if(from.line<display.viewFrom||to.line>display.viewTo-1)return!1;var fromIndex,fromLine,fromNode;if(from.line==display.viewFrom||0==(fromIndex=findViewIndex(cm,from.line))){fromLine=lineNo(display.view[0].line);fromNode=display.view[0].node}else{fromLine=lineNo(display.view[fromIndex].line);fromNode=display.view[fromIndex-1].node.nextSibling}var toLine,toNode,toIndex=findViewIndex(cm,to.line);if(toIndex==display.view.length-1){toLine=display.viewTo-1;toNode=display.lineDiv.lastChild}else{toLine=lineNo(display.view[toIndex+1].line)-1;toNode=display.view[toIndex+1].node.previousSibling}if(!fromNode)return!1;for(var newText=cm.doc.splitLines(domTextBetween(cm,fromNode,toNode,fromLine,toLine)),oldText=getBetween(cm.doc,Pos(fromLine,0),Pos(toLine,getLine(cm.doc,toLine).text.length));newText.length>1&&oldText.length>1;)if(lst(newText)==lst(oldText)){newText.pop();oldText.pop();toLine--}else{if(newText[0]!=oldText[0])break;newText.shift();oldText.shift();fromLine++}for(var cutFront=0,cutEnd=0,newTop=newText[0],oldTop=oldText[0],maxCutFront=Math.min(newTop.length,oldTop.length);cutFront<maxCutFront&&newTop.charCodeAt(cutFront)==oldTop.charCodeAt(cutFront);)++cutFront;for(var newBot=lst(newText),oldBot=lst(oldText),maxCutEnd=Math.min(newBot.length-(1==newText.length?cutFront:0),oldBot.length-(1==oldText.length?cutFront:0));cutEnd<maxCutEnd&&newBot.charCodeAt(newBot.length-cutEnd-1)==oldBot.charCodeAt(oldBot.length-cutEnd-1);)++cutEnd;newText[newText.length-1]=newBot.slice(0,newBot.length-cutEnd).replace(/^\u200b+/,"");newText[0]=newText[0].slice(cutFront).replace(/\u200b+$/,"");var chFrom=Pos(fromLine,cutFront),chTo=Pos(toLine,oldText.length?lst(oldText).length-cutEnd:0);if(newText.length>1||newText[0]||cmp(chFrom,chTo)){replaceRange(cm.doc,newText,chFrom,chTo,"+input");return!0}};ContentEditableInput.prototype.ensurePolled=function(){this.forceCompositionEnd()};ContentEditableInput.prototype.reset=function(){this.forceCompositionEnd()};ContentEditableInput.prototype.forceCompositionEnd=function(){if(this.composing){clearTimeout(this.readDOMTimeout);this.composing=null;this.pollContent()||regChange(this.cm);this.div.blur();this.div.focus()}};ContentEditableInput.prototype.readFromDOMSoon=function(){var this$1=this;null==this.readDOMTimeout&&(this.readDOMTimeout=setTimeout(function(){this$1.readDOMTimeout=null;if(this$1.composing){if(!this$1.composing.done)return;this$1.composing=null}!this$1.cm.isReadOnly()&&this$1.pollContent()||runInOp(this$1.cm,function(){return regChange(this$1.cm)})},80))};ContentEditableInput.prototype.setUneditable=function(node){node.contentEditable="false"};ContentEditableInput.prototype.onKeyPress=function(e){e.preventDefault();this.cm.isReadOnly()||operation(this.cm,applyTextInput)(this.cm,String.fromCharCode(null==e.charCode?e.keyCode:e.charCode),0)};ContentEditableInput.prototype.readOnlyChanged=function(val){this.div.contentEditable=String("nocursor"!=val)};ContentEditableInput.prototype.onContextMenu=function(){};ContentEditableInput.prototype.resetPosition=function(){};ContentEditableInput.prototype.needsContentAttribute=!0;var TextareaInput=function(cm){this.cm=cm;this.prevInput="";this.pollingFast=!1;this.polling=new Delayed;this.inaccurateSelection=!1;this.hasSelection=!1;this.composing=null};TextareaInput.prototype.init=function(display){function prepareCopyCut(e){if(!signalDOMEvent(cm,e)){if(cm.somethingSelected()){setLastCopied({lineWise:!1,text:cm.getSelections()});if(input.inaccurateSelection){input.prevInput="";input.inaccurateSelection=!1;te.value=lastCopied.text.join("\n");selectInput(te)}}else{if(!cm.options.lineWiseCopyCut)return;var ranges=copyableRanges(cm);setLastCopied({lineWise:!0,text:ranges.text});if("cut"==e.type)cm.setSelections(ranges.ranges,null,sel_dontScroll);else{input.prevInput="";te.value=ranges.text.join("\n");selectInput(te)}}"cut"==e.type&&(cm.state.cutIncoming=!0)}}var this$1=this,input=this,cm=this.cm,div=this.wrapper=hiddenTextarea(),te=this.textarea=div.firstChild;display.wrapper.insertBefore(div,display.wrapper.firstChild);ios&&(te.style.width="0px");on(te,"input",function(){ie&&ie_version>=9&&this$1.hasSelection&&(this$1.hasSelection=null);input.poll()});on(te,"paste",function(e){if(!signalDOMEvent(cm,e)&&!handlePaste(e,cm)){cm.state.pasteIncoming=!0;input.fastPoll()}});on(te,"cut",prepareCopyCut);on(te,"copy",prepareCopyCut);on(display.scroller,"paste",function(e){if(!eventInWidget(display,e)&&!signalDOMEvent(cm,e)){cm.state.pasteIncoming=!0;input.focus()}});on(display.lineSpace,"selectstart",function(e){eventInWidget(display,e)||e_preventDefault(e)});on(te,"compositionstart",function(){var start=cm.getCursor("from");input.composing&&input.composing.range.clear();input.composing={start:start,range:cm.markText(start,cm.getCursor("to"),{className:"CodeMirror-composing"})}});on(te,"compositionend",function(){if(input.composing){input.poll();input.composing.range.clear();input.composing=null}})};TextareaInput.prototype.prepareSelection=function(){var cm=this.cm,display=cm.display,doc=cm.doc,result=prepareSelection(cm);if(cm.options.moveInputWithCursor){var headPos=cursorCoords(cm,doc.sel.primary().head,"div"),wrapOff=display.wrapper.getBoundingClientRect(),lineOff=display.lineDiv.getBoundingClientRect();result.teTop=Math.max(0,Math.min(display.wrapper.clientHeight-10,headPos.top+lineOff.top-wrapOff.top));result.teLeft=Math.max(0,Math.min(display.wrapper.clientWidth-10,headPos.left+lineOff.left-wrapOff.left))}return result};TextareaInput.prototype.showSelection=function(drawn){var cm=this.cm,display=cm.display;removeChildrenAndAdd(display.cursorDiv,drawn.cursors);removeChildrenAndAdd(display.selectionDiv,drawn.selection);if(null!=drawn.teTop){this.wrapper.style.top=drawn.teTop+"px";this.wrapper.style.left=drawn.teLeft+"px"}};TextareaInput.prototype.reset=function(typing){if(!this.contextMenuPending){var minimal,selected,cm=this.cm,doc=cm.doc;if(cm.somethingSelected()){this.prevInput="";var range=doc.sel.primary();minimal=hasCopyEvent&&(range.to().line-range.from().line>100||(selected=cm.getSelection()).length>1e3);var content=minimal?"-":selected||cm.getSelection();this.textarea.value=content;cm.state.focused&&selectInput(this.textarea);ie&&ie_version>=9&&(this.hasSelection=content)}else if(!typing){this.prevInput=this.textarea.value="";ie&&ie_version>=9&&(this.hasSelection=null)}this.inaccurateSelection=minimal}};TextareaInput.prototype.getField=function(){return this.textarea};TextareaInput.prototype.supportsTouch=function(){return!1};TextareaInput.prototype.focus=function(){if("nocursor"!=this.cm.options.readOnly&&(!mobile||activeElt()!=this.textarea))try{this.textarea.focus()}catch(e){}};TextareaInput.prototype.blur=function(){this.textarea.blur()};TextareaInput.prototype.resetPosition=function(){this.wrapper.style.top=this.wrapper.style.left=0};TextareaInput.prototype.receivedFocus=function(){this.slowPoll()};TextareaInput.prototype.slowPoll=function(){var this$1=this;this.pollingFast||this.polling.set(this.cm.options.pollInterval,function(){this$1.poll();this$1.cm.state.focused&&this$1.slowPoll()})};TextareaInput.prototype.fastPoll=function(){
8
+ function p(){var changed=input.poll();if(changed||missed){input.pollingFast=!1;input.slowPoll()}else{missed=!0;input.polling.set(60,p)}}var missed=!1,input=this;input.pollingFast=!0;input.polling.set(20,p)};TextareaInput.prototype.poll=function(){var this$1=this,cm=this.cm,input=this.textarea,prevInput=this.prevInput;if(this.contextMenuPending||!cm.state.focused||hasSelection(input)&&!prevInput&&!this.composing||cm.isReadOnly()||cm.options.disableInput||cm.state.keySeq)return!1;var text=input.value;if(text==prevInput&&!cm.somethingSelected())return!1;if(ie&&ie_version>=9&&this.hasSelection===text||mac&&/[\uf700-\uf7ff]/.test(text)){cm.display.input.reset();return!1}if(cm.doc.sel==cm.display.selForContextMenu){var first=text.charCodeAt(0);8203!=first||prevInput||(prevInput="​");if(8666==first){this.reset();return this.cm.execCommand("undo")}}for(var same=0,l=Math.min(prevInput.length,text.length);same<l&&prevInput.charCodeAt(same)==text.charCodeAt(same);)++same;runInOp(cm,function(){applyTextInput(cm,text.slice(same),prevInput.length-same,null,this$1.composing?"*compose":null);text.length>1e3||text.indexOf("\n")>-1?input.value=this$1.prevInput="":this$1.prevInput=text;if(this$1.composing){this$1.composing.range.clear();this$1.composing.range=cm.markText(this$1.composing.start,cm.getCursor("to"),{className:"CodeMirror-composing"})}});return!0};TextareaInput.prototype.ensurePolled=function(){this.pollingFast&&this.poll()&&(this.pollingFast=!1)};TextareaInput.prototype.onKeyPress=function(){ie&&ie_version>=9&&(this.hasSelection=null);this.fastPoll()};TextareaInput.prototype.onContextMenu=function(e){function prepareSelectAllHack(){if(null!=te.selectionStart){var selected=cm.somethingSelected(),extval="​"+(selected?te.value:"");te.value="⇚";te.value=extval;input.prevInput=selected?"":"​";te.selectionStart=1;te.selectionEnd=extval.length;display.selForContextMenu=cm.doc.sel}}function rehide(){input.contextMenuPending=!1;input.wrapper.style.cssText=oldWrapperCSS;te.style.cssText=oldCSS;ie&&ie_version<9&&display.scrollbars.setScrollTop(display.scroller.scrollTop=scrollPos);if(null!=te.selectionStart){(!ie||ie&&ie_version<9)&&prepareSelectAllHack();var i=0,poll=function(){display.selForContextMenu==cm.doc.sel&&0==te.selectionStart&&te.selectionEnd>0&&"​"==input.prevInput?operation(cm,selectAll)(cm):i++<10?display.detectingSelectAll=setTimeout(poll,500):display.input.reset()};display.detectingSelectAll=setTimeout(poll,200)}}var input=this,cm=input.cm,display=cm.display,te=input.textarea,pos=posFromMouse(cm,e),scrollPos=display.scroller.scrollTop;if(pos&&!presto){var reset=cm.options.resetSelectionOnContextMenu;reset&&cm.doc.sel.contains(pos)==-1&&operation(cm,setSelection)(cm.doc,simpleSelection(pos),sel_dontScroll);var oldCSS=te.style.cssText,oldWrapperCSS=input.wrapper.style.cssText;input.wrapper.style.cssText="position: absolute";var wrapperBox=input.wrapper.getBoundingClientRect();te.style.cssText="position: absolute; width: 30px; height: 30px;\n top: "+(e.clientY-wrapperBox.top-5)+"px; left: "+(e.clientX-wrapperBox.left-5)+"px;\n z-index: 1000; background: "+(ie?"rgba(255, 255, 255, .05)":"transparent")+";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";var oldScrollY;webkit&&(oldScrollY=window.scrollY);display.input.focus();webkit&&window.scrollTo(null,oldScrollY);display.input.reset();cm.somethingSelected()||(te.value=input.prevInput=" ");input.contextMenuPending=!0;display.selForContextMenu=cm.doc.sel;clearTimeout(display.detectingSelectAll);ie&&ie_version>=9&&prepareSelectAllHack();if(captureRightClick){e_stop(e);var mouseup=function(){off(window,"mouseup",mouseup);setTimeout(rehide,20)};on(window,"mouseup",mouseup)}else setTimeout(rehide,50)}};TextareaInput.prototype.readOnlyChanged=function(val){val||this.reset()};TextareaInput.prototype.setUneditable=function(){};TextareaInput.prototype.needsContentAttribute=!1;defineOptions(CodeMirror);addEditorMethods(CodeMirror);var dontDelegate="iter insert remove copy getEditor constructor".split(" ");for(var prop in Doc.prototype)Doc.prototype.hasOwnProperty(prop)&&indexOf(dontDelegate,prop)<0&&(CodeMirror.prototype[prop]=function(method){return function(){return method.apply(this.doc,arguments)}}(Doc.prototype[prop]));eventMixin(Doc);CodeMirror.inputStyles={textarea:TextareaInput,contenteditable:ContentEditableInput};CodeMirror.defineMode=function(name){CodeMirror.defaults.mode||"null"==name||(CodeMirror.defaults.mode=name);defineMode.apply(this,arguments)};CodeMirror.defineMIME=defineMIME;CodeMirror.defineMode("null",function(){return{token:function(stream){return stream.skipToEnd()}}});CodeMirror.defineMIME("text/plain","null");CodeMirror.defineExtension=function(name,func){CodeMirror.prototype[name]=func};CodeMirror.defineDocExtension=function(name,func){Doc.prototype[name]=func};CodeMirror.fromTextArea=fromTextArea;addLegacyProps(CodeMirror);CodeMirror.version="5.22.2";return CodeMirror});
js/esites_editor/dist/js/vendor/codemirror/mode/css/css.js CHANGED
@@ -1 +1 @@
1
- !function(mod){"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],mod):mod(CodeMirror)}(function(CodeMirror){"use strict";function keySet(array){for(var keys={},i=0;i<array.length;++i)keys[array[i]]=!0;return keys}function tokenCComment(stream,state){for(var ch,maybeEnd=!1;null!=(ch=stream.next());){if(maybeEnd&&"/"==ch){state.tokenize=null;break}maybeEnd="*"==ch}return["comment","comment"]}CodeMirror.defineMode("css",function(config,parserConfig){function ret(style,tp){type=tp;return style}function tokenBase(stream,state){var ch=stream.next();if(tokenHooks[ch]){var result=tokenHooks[ch](stream,state);if(result!==!1)return result}if("@"==ch){stream.eatWhile(/[\w\\\-]/);return ret("def",stream.current())}if("="==ch||("~"==ch||"|"==ch)&&stream.eat("="))return ret(null,"compare");if('"'==ch||"'"==ch){state.tokenize=tokenString(ch);return state.tokenize(stream,state)}if("#"==ch){stream.eatWhile(/[\w\\\-]/);return ret("atom","hash")}if("!"==ch){stream.match(/^\s*\w*/);return ret("keyword","important")}if(/\d/.test(ch)||"."==ch&&stream.eat(/\d/)){stream.eatWhile(/[\w.%]/);return ret("number","unit")}if("-"!==ch){if(/[,+>*\/]/.test(ch))return ret(null,"select-op");if("."==ch&&stream.match(/^-?[_a-z][_a-z0-9-]*/i))return ret("qualifier","qualifier");if(/[:;{}\[\]\(\)]/.test(ch))return ret(null,ch);if("u"==ch&&stream.match(/rl(-prefix)?\(/)||"d"==ch&&stream.match("omain(")||"r"==ch&&stream.match("egexp(")){stream.backUp(1);state.tokenize=tokenParenthesized;return ret("property","word")}if(/[\w\\\-]/.test(ch)){stream.eatWhile(/[\w\\\-]/);return ret("property","word")}return ret(null,null)}if(/[\d.]/.test(stream.peek())){stream.eatWhile(/[\w.%]/);return ret("number","unit")}if(stream.match(/^-[\w\\\-]+/)){stream.eatWhile(/[\w\\\-]/);return stream.match(/^\s*:/,!1)?ret("variable-2","variable-definition"):ret("variable-2","variable")}return stream.match(/^\w+-/)?ret("meta","meta"):void 0}function tokenString(quote){return function(stream,state){for(var ch,escaped=!1;null!=(ch=stream.next());){if(ch==quote&&!escaped){")"==quote&&stream.backUp(1);break}escaped=!escaped&&"\\"==ch}(ch==quote||!escaped&&")"!=quote)&&(state.tokenize=null);return ret("string","string")}}function tokenParenthesized(stream,state){stream.next();stream.match(/\s*[\"\')]/,!1)?state.tokenize=null:state.tokenize=tokenString(")");return ret(null,"(")}function Context(type,indent,prev){this.type=type;this.indent=indent;this.prev=prev}function pushContext(state,stream,type,indent){state.context=new Context(type,stream.indentation()+(indent===!1?0:indentUnit),state.context);return type}function popContext(state){state.context.prev&&(state.context=state.context.prev);return state.context.type}function pass(type,stream,state){return states[state.context.type](type,stream,state)}function popAndPass(type,stream,state,n){for(var i=n||1;i>0;i--)state.context=state.context.prev;return pass(type,stream,state)}function wordAsValue(stream){var word=stream.current().toLowerCase();override=valueKeywords.hasOwnProperty(word)?"atom":colorKeywords.hasOwnProperty(word)?"keyword":"variable"}var inline=parserConfig.inline;parserConfig.propertyKeywords||(parserConfig=CodeMirror.resolveMode("text/css"));var type,override,indentUnit=config.indentUnit,tokenHooks=parserConfig.tokenHooks,documentTypes=parserConfig.documentTypes||{},mediaTypes=parserConfig.mediaTypes||{},mediaFeatures=parserConfig.mediaFeatures||{},mediaValueKeywords=parserConfig.mediaValueKeywords||{},propertyKeywords=parserConfig.propertyKeywords||{},nonStandardPropertyKeywords=parserConfig.nonStandardPropertyKeywords||{},fontProperties=parserConfig.fontProperties||{},counterDescriptors=parserConfig.counterDescriptors||{},colorKeywords=parserConfig.colorKeywords||{},valueKeywords=parserConfig.valueKeywords||{},allowNested=parserConfig.allowNested,supportsAtComponent=parserConfig.supportsAtComponent===!0,states={};states.top=function(type,stream,state){if("{"==type)return pushContext(state,stream,"block");if("}"==type&&state.context.prev)return popContext(state);if(supportsAtComponent&&/@component/.test(type))return pushContext(state,stream,"atComponentBlock");if(/^@(-moz-)?document$/.test(type))return pushContext(state,stream,"documentTypes");if(/^@(media|supports|(-moz-)?document|import)$/.test(type))return pushContext(state,stream,"atBlock");if(/^@(font-face|counter-style)/.test(type)){state.stateArg=type;return"restricted_atBlock_before"}if(/^@(-(moz|ms|o|webkit)-)?keyframes$/.test(type))return"keyframes";if(type&&"@"==type.charAt(0))return pushContext(state,stream,"at");if("hash"==type)override="builtin";else if("word"==type)override="tag";else{if("variable-definition"==type)return"maybeprop";if("interpolation"==type)return pushContext(state,stream,"interpolation");if(":"==type)return"pseudo";if(allowNested&&"("==type)return pushContext(state,stream,"parens")}return state.context.type};states.block=function(type,stream,state){if("word"==type){var word=stream.current().toLowerCase();if(propertyKeywords.hasOwnProperty(word)){override="property";return"maybeprop"}if(nonStandardPropertyKeywords.hasOwnProperty(word)){override="string-2";return"maybeprop"}if(allowNested){override=stream.match(/^\s*:(?:\s|$)/,!1)?"property":"tag";return"block"}override+=" error";return"maybeprop"}if("meta"==type)return"block";if(allowNested||"hash"!=type&&"qualifier"!=type)return states.top(type,stream,state);override="error";return"block"};states.maybeprop=function(type,stream,state){return":"==type?pushContext(state,stream,"prop"):pass(type,stream,state)};states.prop=function(type,stream,state){if(";"==type)return popContext(state);if("{"==type&&allowNested)return pushContext(state,stream,"propBlock");if("}"==type||"{"==type)return popAndPass(type,stream,state);if("("==type)return pushContext(state,stream,"parens");if("hash"!=type||/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(stream.current())){if("word"==type)wordAsValue(stream);else if("interpolation"==type)return pushContext(state,stream,"interpolation")}else override+=" error";return"prop"};states.propBlock=function(type,_stream,state){if("}"==type)return popContext(state);if("word"==type){override="property";return"maybeprop"}return state.context.type};states.parens=function(type,stream,state){if("{"==type||"}"==type)return popAndPass(type,stream,state);if(")"==type)return popContext(state);if("("==type)return pushContext(state,stream,"parens");if("interpolation"==type)return pushContext(state,stream,"interpolation");"word"==type&&wordAsValue(stream);return"parens"};states.pseudo=function(type,stream,state){if("word"==type){override="variable-3";return state.context.type}return pass(type,stream,state)};states.documentTypes=function(type,stream,state){if("word"==type&&documentTypes.hasOwnProperty(stream.current())){override="tag";return state.context.type}return states.atBlock(type,stream,state)};states.atBlock=function(type,stream,state){if("("==type)return pushContext(state,stream,"atBlock_parens");if("}"==type||";"==type)return popAndPass(type,stream,state);if("{"==type)return popContext(state)&&pushContext(state,stream,allowNested?"block":"top");if("interpolation"==type)return pushContext(state,stream,"interpolation");if("word"==type){var word=stream.current().toLowerCase();override="only"==word||"not"==word||"and"==word||"or"==word?"keyword":mediaTypes.hasOwnProperty(word)?"attribute":mediaFeatures.hasOwnProperty(word)?"property":mediaValueKeywords.hasOwnProperty(word)?"keyword":propertyKeywords.hasOwnProperty(word)?"property":nonStandardPropertyKeywords.hasOwnProperty(word)?"string-2":valueKeywords.hasOwnProperty(word)?"atom":colorKeywords.hasOwnProperty(word)?"keyword":"error"}return state.context.type};states.atComponentBlock=function(type,stream,state){if("}"==type)return popAndPass(type,stream,state);if("{"==type)return popContext(state)&&pushContext(state,stream,allowNested?"block":"top",!1);"word"==type&&(override="error");return state.context.type};states.atBlock_parens=function(type,stream,state){return")"==type?popContext(state):"{"==type||"}"==type?popAndPass(type,stream,state,2):states.atBlock(type,stream,state)};states.restricted_atBlock_before=function(type,stream,state){if("{"==type)return pushContext(state,stream,"restricted_atBlock");if("word"==type&&"@counter-style"==state.stateArg){override="variable";return"restricted_atBlock_before"}return pass(type,stream,state)};states.restricted_atBlock=function(type,stream,state){if("}"==type){state.stateArg=null;return popContext(state)}if("word"==type){override="@font-face"==state.stateArg&&!fontProperties.hasOwnProperty(stream.current().toLowerCase())||"@counter-style"==state.stateArg&&!counterDescriptors.hasOwnProperty(stream.current().toLowerCase())?"error":"property";return"maybeprop"}return"restricted_atBlock"};states.keyframes=function(type,stream,state){if("word"==type){override="variable";return"keyframes"}return"{"==type?pushContext(state,stream,"top"):pass(type,stream,state)};states.at=function(type,stream,state){if(";"==type)return popContext(state);if("{"==type||"}"==type)return popAndPass(type,stream,state);"word"==type?override="tag":"hash"==type&&(override="builtin");return"at"};states.interpolation=function(type,stream,state){if("}"==type)return popContext(state);if("{"==type||";"==type)return popAndPass(type,stream,state);"word"==type?override="variable":"variable"!=type&&"("!=type&&")"!=type&&(override="error");return"interpolation"};return{startState:function(base){return{tokenize:null,state:inline?"block":"top",stateArg:null,context:new Context(inline?"block":"top",base||0,null)}},token:function(stream,state){if(!state.tokenize&&stream.eatSpace())return null;var style=(state.tokenize||tokenBase)(stream,state);if(style&&"object"==typeof style){type=style[1];style=style[0]}override=style;state.state=states[state.state](type,stream,state);return override},indent:function(state,textAfter){var cx=state.context,ch=textAfter&&textAfter.charAt(0),indent=cx.indent;"prop"!=cx.type||"}"!=ch&&")"!=ch||(cx=cx.prev);if(cx.prev)if("}"!=ch||"block"!=cx.type&&"top"!=cx.type&&"interpolation"!=cx.type&&"restricted_atBlock"!=cx.type){if(")"==ch&&("parens"==cx.type||"atBlock_parens"==cx.type)||"{"==ch&&("at"==cx.type||"atBlock"==cx.type)){indent=Math.max(0,cx.indent-indentUnit);cx=cx.prev}}else{cx=cx.prev;indent=cx.indent}return indent},electricChars:"}",blockCommentStart:"/*",blockCommentEnd:"*/",fold:"brace"}});var documentTypes_=["domain","regexp","url","url-prefix"],documentTypes=keySet(documentTypes_),mediaTypes_=["all","aural","braille","handheld","print","projection","screen","tty","tv","embossed"],mediaTypes=keySet(mediaTypes_),mediaFeatures_=["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"],mediaFeatures=keySet(mediaFeatures_),mediaValueKeywords_=["landscape","portrait","none","coarse","fine","on-demand","hover","interlace","progressive"],mediaValueKeywords=keySet(mediaValueKeywords_),propertyKeywords_=["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-position","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphens","icon","image-orientation","image-rendering","image-resolution","inline-box-align","justify-content","left","letter-spacing","line-break","line-height","line-stacking","line-stacking-ruby","line-stacking-shift","line-stacking-strategy","list-style","list-style-image","list-style-position","list-style-type","margin","margin-bottom","margin-left","margin-right","margin-top","marker-offset","marks","marquee-direction","marquee-loop","marquee-play-count","marquee-speed","marquee-style","max-height","max-width","min-height","min-width","move-to","nav-down","nav-index","nav-left","nav-right","nav-up","object-fit","object-position","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-style","overflow-wrap","overflow-x","overflow-y","padding","padding-bottom","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","page-policy","pause","pause-after","pause-before","perspective","perspective-origin","pitch","pitch-range","play-during","position","presentation-level","punctuation-trim","quotes","region-break-after","region-break-before","region-break-inside","region-fragment","rendering-intent","resize","rest","rest-after","rest-before","richness","right","rotation","rotation-point","ruby-align","ruby-overhang","ruby-position","ruby-span","shape-image-threshold","shape-inside","shape-margin","shape-outside","size","speak","speak-as","speak-header","speak-numeral","speak-punctuation","speech-rate","stress","string-set","tab-size","table-layout","target","target-name","target-new","target-position","text-align","text-align-last","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-style","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-height","text-indent","text-justify","text-outline","text-overflow","text-shadow","text-size-adjust","text-space-collapse","text-transform","text-underline-position","text-wrap","top","transform","transform-origin","transform-style","transition","transition-delay","transition-duration","transition-property","transition-timing-function","unicode-bidi","vertical-align","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","volume","white-space","widows","width","word-break","word-spacing","word-wrap","z-index","clip-path","clip-rule","mask","enable-background","filter","flood-color","flood-opacity","lighting-color","stop-color","stop-opacity","pointer-events","color-interpolation","color-interpolation-filters","color-rendering","fill","fill-opacity","fill-rule","image-rendering","marker","marker-end","marker-mid","marker-start","shape-rendering","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","text-rendering","baseline-shift","dominant-baseline","glyph-orientation-horizontal","glyph-orientation-vertical","text-anchor","writing-mode"],propertyKeywords=keySet(propertyKeywords_),nonStandardPropertyKeywords_=["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"],nonStandardPropertyKeywords=keySet(nonStandardPropertyKeywords_),fontProperties_=["font-family","src","unicode-range","font-variant","font-feature-settings","font-stretch","font-weight","font-style"],fontProperties=keySet(fontProperties_),counterDescriptors_=["additive-symbols","fallback","negative","pad","prefix","range","speak-as","suffix","symbols","system"],counterDescriptors=keySet(counterDescriptors_),colorKeywords_=["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"],colorKeywords=keySet(colorKeywords_),valueKeywords_=["above","absolute","activeborder","additive","activecaption","afar","after-white-space","ahead","alias","all","all-scroll","alphabetic","alternate","always","amharic","amharic-abegede","antialiased","appworkspace","arabic-indic","armenian","asterisks","attr","auto","avoid","avoid-column","avoid-page","avoid-region","background","backwards","baseline","below","bidi-override","binary","bengali","blink","block","block-axis","bold","bolder","border","border-box","both","bottom","break","break-all","break-word","bullets","button","button-bevel","buttonface","buttonhighlight","buttonshadow","buttontext","calc","cambodian","capitalize","caps-lock-indicator","caption","captiontext","caret","cell","center","checkbox","circle","cjk-decimal","cjk-earthly-branch","cjk-heavenly-stem","cjk-ideographic","clear","clip","close-quote","col-resize","collapse","color","color-burn","color-dodge","column","column-reverse","compact","condensed","contain","content","content-box","context-menu","continuous","copy","counter","counters","cover","crop","cross","crosshair","currentcolor","cursive","cyclic","darken","dashed","decimal","decimal-leading-zero","default","default-button","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","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-table","inset","inside","intrinsic","invert","italic","japanese-formal","japanese-informal","justify","kannada","katakana","katakana-iroha","keep-all","khmer","korean-hangul-formal","korean-hanja-formal","korean-hanja-informal","landscape","lao","large","larger","left","level","lighter","lighten","line-through","linear","linear-gradient","lines","list-item","listbox","listitem","local","logical","loud","lower","lower-alpha","lower-armenian","lower-greek","lower-hexadecimal","lower-latin","lower-norwegian","lower-roman","lowercase","ltr","luminosity","malayalam","match","matrix","matrix3d","media-controls-background","media-current-time-display","media-fullscreen-button","media-mute-button","media-play-button","media-return-to-realtime-button","media-rewind-button","media-seek-back-button","media-seek-forward-button","media-slider","media-sliderthumb","media-time-remaining-display","media-volume-slider","media-volume-slider-container","media-volume-sliderthumb","medium","menu","menulist","menulist-button","menulist-text","menulist-textfield","menutext","message-box","middle","min-intrinsic","mix","mongolian","monospace","move","multiple","multiply","myanmar","n-resize","narrower","ne-resize","nesw-resize","no-close-quote","no-drop","no-open-quote","no-repeat","none","normal","not-allowed","nowrap","ns-resize","numbers","numeric","nw-resize","nwse-resize","oblique","octal","open-quote","optimizeLegibility","optimizeSpeed","oriya","oromo","outset","outside","outside-shape","overlay","overline","padding","padding-box","painted","page","paused","persian","perspective","plus-darker","plus-lighter","pointer","polygon","portrait","pre","pre-line","pre-wrap","preserve-3d","progress","push-button","radial-gradient","radio","read-only","read-write","read-write-plaintext-only","rectangle","region","relative","repeat","repeating-linear-gradient","repeating-radial-gradient","repeat-x","repeat-y","reset","reverse","rgb","rgba","ridge","right","rotate","rotate3d","rotateX","rotateY","rotateZ","round","row","row-resize","row-reverse","rtl","run-in","running","s-resize","sans-serif","saturation","scale","scale3d","scaleX","scaleY","scaleZ","screen","scroll","scrollbar","se-resize","searchfield","searchfield-cancel-button","searchfield-decoration","searchfield-results-button","searchfield-results-decoration","semi-condensed","semi-expanded","separate","serif","show","sidama","simp-chinese-formal","simp-chinese-informal","single","skew","skewX","skewY","skip-white-space","slide","slider-horizontal","slider-vertical","sliderthumb-horizontal","sliderthumb-vertical","slow","small","small-caps","small-caption","smaller","soft-light","solid","somali","source-atop","source-in","source-out","source-over","space","space-around","space-between","spell-out","square","square-button","start","static","status-bar","stretch","stroke","sub","subpixel-antialiased","super","sw-resize","symbolic","symbols","table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","tamil","telugu","text","text-bottom","text-top","textarea","textfield","thai","thick","thin","threeddarkshadow","threedface","threedhighlight","threedlightshadow","threedshadow","tibetan","tigre","tigrinya-er","tigrinya-er-abegede","tigrinya-et","tigrinya-et-abegede","to","top","trad-chinese-formal","trad-chinese-informal","translate","translate3d","translateX","translateY","translateZ","transparent","ultra-condensed","ultra-expanded","underline","up","upper-alpha","upper-armenian","upper-greek","upper-hexadecimal","upper-latin","upper-norwegian","upper-roman","uppercase","urdu","url","var","vertical","vertical-text","visible","visibleFill","visiblePainted","visibleStroke","visual","w-resize","wait","wave","wider","window","windowframe","windowtext","words","wrap","wrap-reverse","x-large","x-small","xor","xx-large","xx-small"],valueKeywords=keySet(valueKeywords_),allWords=documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(mediaValueKeywords_).concat(propertyKeywords_).concat(nonStandardPropertyKeywords_).concat(colorKeywords_).concat(valueKeywords_);CodeMirror.registerHelper("hintWords","css",allWords);CodeMirror.defineMIME("text/css",{documentTypes:documentTypes,mediaTypes:mediaTypes,mediaFeatures:mediaFeatures,mediaValueKeywords:mediaValueKeywords,propertyKeywords:propertyKeywords,nonStandardPropertyKeywords:nonStandardPropertyKeywords,fontProperties:fontProperties,counterDescriptors:counterDescriptors,colorKeywords:colorKeywords,valueKeywords:valueKeywords,tokenHooks:{"/":function(stream,state){if(!stream.eat("*"))return!1;state.tokenize=tokenCComment;return tokenCComment(stream,state)}},name:"css"});CodeMirror.defineMIME("text/x-scss",{mediaTypes:mediaTypes,mediaFeatures:mediaFeatures,mediaValueKeywords:mediaValueKeywords,propertyKeywords:propertyKeywords,nonStandardPropertyKeywords:nonStandardPropertyKeywords,colorKeywords:colorKeywords,valueKeywords:valueKeywords,fontProperties:fontProperties,allowNested:!0,tokenHooks:{"/":function(stream,state){if(stream.eat("/")){stream.skipToEnd();return["comment","comment"]}if(stream.eat("*")){state.tokenize=tokenCComment;return tokenCComment(stream,state)}return["operator","operator"]},":":function(stream){return stream.match(/\s*\{/)?[null,"{"]:!1},$:function(stream){stream.match(/^[\w-]+/);return stream.match(/^\s*:/,!1)?["variable-2","variable-definition"]:["variable-2","variable"]},"#":function(stream){return stream.eat("{")?[null,"interpolation"]:!1}},name:"css",helperType:"scss"});CodeMirror.defineMIME("text/x-less",{mediaTypes:mediaTypes,mediaFeatures:mediaFeatures,mediaValueKeywords:mediaValueKeywords,propertyKeywords:propertyKeywords,nonStandardPropertyKeywords:nonStandardPropertyKeywords,colorKeywords:colorKeywords,valueKeywords:valueKeywords,fontProperties:fontProperties,allowNested:!0,tokenHooks:{"/":function(stream,state){if(stream.eat("/")){stream.skipToEnd();return["comment","comment"]}if(stream.eat("*")){state.tokenize=tokenCComment;return tokenCComment(stream,state)}return["operator","operator"]},"@":function(stream){if(stream.eat("{"))return[null,"interpolation"];if(stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/,!1))return!1;stream.eatWhile(/[\w\\\-]/);return stream.match(/^\s*:/,!1)?["variable-2","variable-definition"]:["variable-2","variable"]},"&":function(){return["atom","atom"]}},name:"css",helperType:"less"});CodeMirror.defineMIME("text/x-gss",{documentTypes:documentTypes,mediaTypes:mediaTypes,mediaFeatures:mediaFeatures,propertyKeywords:propertyKeywords,nonStandardPropertyKeywords:nonStandardPropertyKeywords,fontProperties:fontProperties,counterDescriptors:counterDescriptors,colorKeywords:colorKeywords,valueKeywords:valueKeywords,supportsAtComponent:!0,tokenHooks:{"/":function(stream,state){if(!stream.eat("*"))return!1;state.tokenize=tokenCComment;return tokenCComment(stream,state)}},name:"css",helperType:"gss"})});
1
+ !function(mod){"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],mod):mod(CodeMirror)}(function(CodeMirror){"use strict";function keySet(array){for(var keys={},i=0;i<array.length;++i)keys[array[i].toLowerCase()]=!0;return keys}function tokenCComment(stream,state){for(var ch,maybeEnd=!1;null!=(ch=stream.next());){if(maybeEnd&&"/"==ch){state.tokenize=null;break}maybeEnd="*"==ch}return["comment","comment"]}CodeMirror.defineMode("css",function(config,parserConfig){function ret(style,tp){type=tp;return style}function tokenBase(stream,state){var ch=stream.next();if(tokenHooks[ch]){var result=tokenHooks[ch](stream,state);if(result!==!1)return result}if("@"==ch){stream.eatWhile(/[\w\\\-]/);return ret("def",stream.current())}if("="==ch||("~"==ch||"|"==ch)&&stream.eat("="))return ret(null,"compare");if('"'==ch||"'"==ch){state.tokenize=tokenString(ch);return state.tokenize(stream,state)}if("#"==ch){stream.eatWhile(/[\w\\\-]/);return ret("atom","hash")}if("!"==ch){stream.match(/^\s*\w*/);return ret("keyword","important")}if(/\d/.test(ch)||"."==ch&&stream.eat(/\d/)){stream.eatWhile(/[\w.%]/);return ret("number","unit")}if("-"!==ch){if(/[,+>*\/]/.test(ch))return ret(null,"select-op");if("."==ch&&stream.match(/^-?[_a-z][_a-z0-9-]*/i))return ret("qualifier","qualifier");if(/[:;{}\[\]\(\)]/.test(ch))return ret(null,ch);if("u"==ch&&stream.match(/rl(-prefix)?\(/)||"d"==ch&&stream.match("omain(")||"r"==ch&&stream.match("egexp(")){stream.backUp(1);state.tokenize=tokenParenthesized;return ret("property","word")}if(/[\w\\\-]/.test(ch)){stream.eatWhile(/[\w\\\-]/);return ret("property","word")}return ret(null,null)}if(/[\d.]/.test(stream.peek())){stream.eatWhile(/[\w.%]/);return ret("number","unit")}if(stream.match(/^-[\w\\\-]+/)){stream.eatWhile(/[\w\\\-]/);return stream.match(/^\s*:/,!1)?ret("variable-2","variable-definition"):ret("variable-2","variable")}return stream.match(/^\w+-/)?ret("meta","meta"):void 0}function tokenString(quote){return function(stream,state){for(var ch,escaped=!1;null!=(ch=stream.next());){if(ch==quote&&!escaped){")"==quote&&stream.backUp(1);break}escaped=!escaped&&"\\"==ch}(ch==quote||!escaped&&")"!=quote)&&(state.tokenize=null);return ret("string","string")}}function tokenParenthesized(stream,state){stream.next();stream.match(/\s*[\"\')]/,!1)?state.tokenize=null:state.tokenize=tokenString(")");return ret(null,"(")}function Context(type,indent,prev){this.type=type;this.indent=indent;this.prev=prev}function pushContext(state,stream,type,indent){state.context=new Context(type,stream.indentation()+(indent===!1?0:indentUnit),state.context);return type}function popContext(state){state.context.prev&&(state.context=state.context.prev);return state.context.type}function pass(type,stream,state){return states[state.context.type](type,stream,state)}function popAndPass(type,stream,state,n){for(var i=n||1;i>0;i--)state.context=state.context.prev;return pass(type,stream,state)}function wordAsValue(stream){var word=stream.current().toLowerCase();override=valueKeywords.hasOwnProperty(word)?"atom":colorKeywords.hasOwnProperty(word)?"keyword":"variable"}var inline=parserConfig.inline;parserConfig.propertyKeywords||(parserConfig=CodeMirror.resolveMode("text/css"));var type,override,indentUnit=config.indentUnit,tokenHooks=parserConfig.tokenHooks,documentTypes=parserConfig.documentTypes||{},mediaTypes=parserConfig.mediaTypes||{},mediaFeatures=parserConfig.mediaFeatures||{},mediaValueKeywords=parserConfig.mediaValueKeywords||{},propertyKeywords=parserConfig.propertyKeywords||{},nonStandardPropertyKeywords=parserConfig.nonStandardPropertyKeywords||{},fontProperties=parserConfig.fontProperties||{},counterDescriptors=parserConfig.counterDescriptors||{},colorKeywords=parserConfig.colorKeywords||{},valueKeywords=parserConfig.valueKeywords||{},allowNested=parserConfig.allowNested,supportsAtComponent=parserConfig.supportsAtComponent===!0,states={};states.top=function(type,stream,state){if("{"==type)return pushContext(state,stream,"block");if("}"==type&&state.context.prev)return popContext(state);if(supportsAtComponent&&/@component/.test(type))return pushContext(state,stream,"atComponentBlock");if(/^@(-moz-)?document$/.test(type))return pushContext(state,stream,"documentTypes");if(/^@(media|supports|(-moz-)?document|import)$/.test(type))return pushContext(state,stream,"atBlock");if(/^@(font-face|counter-style)/.test(type)){state.stateArg=type;return"restricted_atBlock_before"}if(/^@(-(moz|ms|o|webkit)-)?keyframes$/.test(type))return"keyframes";if(type&&"@"==type.charAt(0))return pushContext(state,stream,"at");if("hash"==type)override="builtin";else if("word"==type)override="tag";else{if("variable-definition"==type)return"maybeprop";if("interpolation"==type)return pushContext(state,stream,"interpolation");if(":"==type)return"pseudo";if(allowNested&&"("==type)return pushContext(state,stream,"parens")}return state.context.type};states.block=function(type,stream,state){if("word"==type){var word=stream.current().toLowerCase();if(propertyKeywords.hasOwnProperty(word)){override="property";return"maybeprop"}if(nonStandardPropertyKeywords.hasOwnProperty(word)){override="string-2";return"maybeprop"}if(allowNested){override=stream.match(/^\s*:(?:\s|$)/,!1)?"property":"tag";return"block"}override+=" error";return"maybeprop"}if("meta"==type)return"block";if(allowNested||"hash"!=type&&"qualifier"!=type)return states.top(type,stream,state);override="error";return"block"};states.maybeprop=function(type,stream,state){return":"==type?pushContext(state,stream,"prop"):pass(type,stream,state)};states.prop=function(type,stream,state){if(";"==type)return popContext(state);if("{"==type&&allowNested)return pushContext(state,stream,"propBlock");if("}"==type||"{"==type)return popAndPass(type,stream,state);if("("==type)return pushContext(state,stream,"parens");if("hash"!=type||/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(stream.current())){if("word"==type)wordAsValue(stream);else if("interpolation"==type)return pushContext(state,stream,"interpolation")}else override+=" error";return"prop"};states.propBlock=function(type,_stream,state){if("}"==type)return popContext(state);if("word"==type){override="property";return"maybeprop"}return state.context.type};states.parens=function(type,stream,state){if("{"==type||"}"==type)return popAndPass(type,stream,state);if(")"==type)return popContext(state);if("("==type)return pushContext(state,stream,"parens");if("interpolation"==type)return pushContext(state,stream,"interpolation");"word"==type&&wordAsValue(stream);return"parens"};states.pseudo=function(type,stream,state){if("word"==type){override="variable-3";return state.context.type}return pass(type,stream,state)};states.documentTypes=function(type,stream,state){if("word"==type&&documentTypes.hasOwnProperty(stream.current())){override="tag";return state.context.type}return states.atBlock(type,stream,state)};states.atBlock=function(type,stream,state){if("("==type)return pushContext(state,stream,"atBlock_parens");if("}"==type||";"==type)return popAndPass(type,stream,state);if("{"==type)return popContext(state)&&pushContext(state,stream,allowNested?"block":"top");if("interpolation"==type)return pushContext(state,stream,"interpolation");if("word"==type){var word=stream.current().toLowerCase();override="only"==word||"not"==word||"and"==word||"or"==word?"keyword":mediaTypes.hasOwnProperty(word)?"attribute":mediaFeatures.hasOwnProperty(word)?"property":mediaValueKeywords.hasOwnProperty(word)?"keyword":propertyKeywords.hasOwnProperty(word)?"property":nonStandardPropertyKeywords.hasOwnProperty(word)?"string-2":valueKeywords.hasOwnProperty(word)?"atom":colorKeywords.hasOwnProperty(word)?"keyword":"error"}return state.context.type};states.atComponentBlock=function(type,stream,state){if("}"==type)return popAndPass(type,stream,state);if("{"==type)return popContext(state)&&pushContext(state,stream,allowNested?"block":"top",!1);"word"==type&&(override="error");return state.context.type};states.atBlock_parens=function(type,stream,state){return")"==type?popContext(state):"{"==type||"}"==type?popAndPass(type,stream,state,2):states.atBlock(type,stream,state)};states.restricted_atBlock_before=function(type,stream,state){if("{"==type)return pushContext(state,stream,"restricted_atBlock");if("word"==type&&"@counter-style"==state.stateArg){override="variable";return"restricted_atBlock_before"}return pass(type,stream,state)};states.restricted_atBlock=function(type,stream,state){if("}"==type){state.stateArg=null;return popContext(state)}if("word"==type){override="@font-face"==state.stateArg&&!fontProperties.hasOwnProperty(stream.current().toLowerCase())||"@counter-style"==state.stateArg&&!counterDescriptors.hasOwnProperty(stream.current().toLowerCase())?"error":"property";return"maybeprop"}return"restricted_atBlock"};states.keyframes=function(type,stream,state){if("word"==type){override="variable";return"keyframes"}return"{"==type?pushContext(state,stream,"top"):pass(type,stream,state)};states.at=function(type,stream,state){if(";"==type)return popContext(state);if("{"==type||"}"==type)return popAndPass(type,stream,state);"word"==type?override="tag":"hash"==type&&(override="builtin");return"at"};states.interpolation=function(type,stream,state){if("}"==type)return popContext(state);if("{"==type||";"==type)return popAndPass(type,stream,state);"word"==type?override="variable":"variable"!=type&&"("!=type&&")"!=type&&(override="error");return"interpolation"};return{startState:function(base){return{tokenize:null,state:inline?"block":"top",stateArg:null,context:new Context(inline?"block":"top",base||0,null)}},token:function(stream,state){if(!state.tokenize&&stream.eatSpace())return null;var style=(state.tokenize||tokenBase)(stream,state);if(style&&"object"==typeof style){type=style[1];style=style[0]}override=style;state.state=states[state.state](type,stream,state);return override},indent:function(state,textAfter){var cx=state.context,ch=textAfter&&textAfter.charAt(0),indent=cx.indent;"prop"!=cx.type||"}"!=ch&&")"!=ch||(cx=cx.prev);if(cx.prev)if("}"!=ch||"block"!=cx.type&&"top"!=cx.type&&"interpolation"!=cx.type&&"restricted_atBlock"!=cx.type){if(")"==ch&&("parens"==cx.type||"atBlock_parens"==cx.type)||"{"==ch&&("at"==cx.type||"atBlock"==cx.type)){indent=Math.max(0,cx.indent-indentUnit);cx=cx.prev}}else{cx=cx.prev;indent=cx.indent}return indent},electricChars:"}",blockCommentStart:"/*",blockCommentEnd:"*/",fold:"brace"}});var documentTypes_=["domain","regexp","url","url-prefix"],documentTypes=keySet(documentTypes_),mediaTypes_=["all","aural","braille","handheld","print","projection","screen","tty","tv","embossed"],mediaTypes=keySet(mediaTypes_),mediaFeatures_=["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"],mediaFeatures=keySet(mediaFeatures_),mediaValueKeywords_=["landscape","portrait","none","coarse","fine","on-demand","hover","interlace","progressive"],mediaValueKeywords=keySet(mediaValueKeywords_),propertyKeywords_=["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"],propertyKeywords=keySet(propertyKeywords_),nonStandardPropertyKeywords_=["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"],nonStandardPropertyKeywords=keySet(nonStandardPropertyKeywords_),fontProperties_=["font-family","src","unicode-range","font-variant","font-feature-settings","font-stretch","font-weight","font-style"],fontProperties=keySet(fontProperties_),counterDescriptors_=["additive-symbols","fallback","negative","pad","prefix","range","speak-as","suffix","symbols","system"],counterDescriptors=keySet(counterDescriptors_),colorKeywords_=["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"],colorKeywords=keySet(colorKeywords_),valueKeywords_=["above","absolute","activeborder","additive","activecaption","afar","after-white-space","ahead","alias","all","all-scroll","alphabetic","alternate","always","amharic","amharic-abegede","antialiased","appworkspace","arabic-indic","armenian","asterisks","attr","auto","avoid","avoid-column","avoid-page","avoid-region","background","backwards","baseline","below","bidi-override","binary","bengali","blink","block","block-axis","bold","bolder","border","border-box","both","bottom","break","break-all","break-word","bullets","button","button-bevel","buttonface","buttonhighlight","buttonshadow","buttontext","calc","cambodian","capitalize","caps-lock-indicator","caption","captiontext","caret","cell","center","checkbox","circle","cjk-decimal","cjk-earthly-branch","cjk-heavenly-stem","cjk-ideographic","clear","clip","close-quote","col-resize","collapse","color","color-burn","color-dodge","column","column-reverse","compact","condensed","contain","content","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","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"],valueKeywords=keySet(valueKeywords_),allWords=documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(mediaValueKeywords_).concat(propertyKeywords_).concat(nonStandardPropertyKeywords_).concat(colorKeywords_).concat(valueKeywords_);CodeMirror.registerHelper("hintWords","css",allWords);CodeMirror.defineMIME("text/css",{documentTypes:documentTypes,mediaTypes:mediaTypes,mediaFeatures:mediaFeatures,mediaValueKeywords:mediaValueKeywords,propertyKeywords:propertyKeywords,nonStandardPropertyKeywords:nonStandardPropertyKeywords,fontProperties:fontProperties,counterDescriptors:counterDescriptors,colorKeywords:colorKeywords,valueKeywords:valueKeywords,tokenHooks:{"/":function(stream,state){if(!stream.eat("*"))return!1;state.tokenize=tokenCComment;return tokenCComment(stream,state)}},name:"css"});CodeMirror.defineMIME("text/x-scss",{mediaTypes:mediaTypes,mediaFeatures:mediaFeatures,mediaValueKeywords:mediaValueKeywords,propertyKeywords:propertyKeywords,nonStandardPropertyKeywords:nonStandardPropertyKeywords,colorKeywords:colorKeywords,valueKeywords:valueKeywords,fontProperties:fontProperties,allowNested:!0,tokenHooks:{"/":function(stream,state){if(stream.eat("/")){stream.skipToEnd();return["comment","comment"]}if(stream.eat("*")){state.tokenize=tokenCComment;return tokenCComment(stream,state)}return["operator","operator"]},":":function(stream){return!!stream.match(/\s*\{/)&&[null,"{"]},$:function(stream){stream.match(/^[\w-]+/);return stream.match(/^\s*:/,!1)?["variable-2","variable-definition"]:["variable-2","variable"]},"#":function(stream){return!!stream.eat("{")&&[null,"interpolation"]}},name:"css",helperType:"scss"});CodeMirror.defineMIME("text/x-less",{mediaTypes:mediaTypes,mediaFeatures:mediaFeatures,mediaValueKeywords:mediaValueKeywords,propertyKeywords:propertyKeywords,nonStandardPropertyKeywords:nonStandardPropertyKeywords,colorKeywords:colorKeywords,valueKeywords:valueKeywords,fontProperties:fontProperties,allowNested:!0,tokenHooks:{"/":function(stream,state){if(stream.eat("/")){stream.skipToEnd();return["comment","comment"]}if(stream.eat("*")){state.tokenize=tokenCComment;return tokenCComment(stream,state)}return["operator","operator"]},"@":function(stream){if(stream.eat("{"))return[null,"interpolation"];if(stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/,!1))return!1;stream.eatWhile(/[\w\\\-]/);return stream.match(/^\s*:/,!1)?["variable-2","variable-definition"]:["variable-2","variable"]},"&":function(){return["atom","atom"]}},name:"css",helperType:"less"});CodeMirror.defineMIME("text/x-gss",{documentTypes:documentTypes,mediaTypes:mediaTypes,mediaFeatures:mediaFeatures,propertyKeywords:propertyKeywords,nonStandardPropertyKeywords:nonStandardPropertyKeywords,fontProperties:fontProperties,counterDescriptors:counterDescriptors,colorKeywords:colorKeywords,valueKeywords:valueKeywords,supportsAtComponent:!0,tokenHooks:{"/":function(stream,state){if(!stream.eat("*"))return!1;state.tokenize=tokenCComment;return tokenCComment(stream,state)}},name:"css",helperType:"gss"})});
js/esites_editor/dist/js/vendor/codemirror/mode/htmlmixed/htmlmixed.js CHANGED
@@ -1 +1 @@
1
- !function(mod){"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror"),require("../xml/xml"),require("../javascript/javascript"),require("../css/css")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","../xml/xml","../javascript/javascript","../css/css"],mod):mod(CodeMirror)}(function(CodeMirror){"use strict";function maybeBackup(stream,pat,style){var cur=stream.current(),close=cur.search(pat);if(close>-1)stream.backUp(cur.length-close);else if(cur.match(/<\/?$/)){stream.backUp(cur.length);stream.match(pat,!1)||stream.match(cur)}return style}function getAttrRegexp(attr){var regexp=attrRegexpCache[attr];return regexp?regexp:attrRegexpCache[attr]=new RegExp("\\s+"+attr+"\\s*=\\s*('|\")?([^'\"]+)('|\")?\\s*")}function getAttrValue(text,attr){var match=text.match(getAttrRegexp(attr));return match?match[2]:""}function getTagRegexp(tagName,anchored){return new RegExp((anchored?"^":"")+"</s*"+tagName+"s*>","i")}function addTags(from,to){for(var tag in from)for(var dest=to[tag]||(to[tag]=[]),source=from[tag],i=source.length-1;i>=0;i--)dest.unshift(source[i])}function findMatchingMode(tagInfo,tagText){for(var i=0;i<tagInfo.length;i++){var spec=tagInfo[i];if(!spec[0]||spec[1].test(getAttrValue(tagText,spec[0])))return spec[2]}}var defaultTags={script:[["lang",/(javascript|babel)/i,"javascript"],["type",/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^$/i,"javascript"],["type",/./,"text/plain"],[null,null,"javascript"]],style:[["lang",/^css$/i,"css"],["type",/^(text\/)?(x-)?(stylesheet|css)$/i,"css"],["type",/./,"text/plain"],[null,null,"css"]]},attrRegexpCache={};CodeMirror.defineMode("htmlmixed",function(config,parserConfig){function html(stream,state){var tagName,style=htmlMode.token(stream,state.htmlState),tag=/\btag\b/.test(style);if(tag&&!/[<>\s\/]/.test(stream.current())&&(tagName=state.htmlState.tagName&&state.htmlState.tagName.toLowerCase())&&tags.hasOwnProperty(tagName))state.inTag=tagName+" ";else if(state.inTag&&tag&&/>$/.test(stream.current())){var inTag=/^([\S]+) (.*)/.exec(state.inTag);state.inTag=null;var modeSpec=">"==stream.current()&&findMatchingMode(tags[inTag[1]],inTag[2]),mode=CodeMirror.getMode(config,modeSpec),endTagA=getTagRegexp(inTag[1],!0),endTag=getTagRegexp(inTag[1],!1);state.token=function(stream,state){if(stream.match(endTagA,!1)){state.token=html;state.localState=state.localMode=null;return null}return maybeBackup(stream,endTag,state.localMode.token(stream,state.localState))};state.localMode=mode;state.localState=CodeMirror.startState(mode,htmlMode.indent(state.htmlState,""))}else if(state.inTag){state.inTag+=stream.current();stream.eol()&&(state.inTag+=" ")}return style}var htmlMode=CodeMirror.getMode(config,{name:"xml",htmlMode:!0,multilineTagIndentFactor:parserConfig.multilineTagIndentFactor,multilineTagIndentPastTag:parserConfig.multilineTagIndentPastTag}),tags={},configTags=parserConfig&&parserConfig.tags,configScript=parserConfig&&parserConfig.scriptTypes;addTags(defaultTags,tags);configTags&&addTags(configTags,tags);if(configScript)for(var i=configScript.length-1;i>=0;i--)tags.script.unshift(["type",configScript[i].matches,configScript[i].mode]);return{startState:function(){var state=htmlMode.startState();return{token:html,inTag:null,localMode:null,localState:null,htmlState:state}},copyState:function(state){var local;state.localState&&(local=CodeMirror.copyState(state.localMode,state.localState));return{token:state.token,inTag:state.inTag,localMode:state.localMode,localState:local,htmlState:CodeMirror.copyState(htmlMode,state.htmlState)}},token:function(stream,state){return state.token(stream,state)},indent:function(state,textAfter){return!state.localMode||/^\s*<\//.test(textAfter)?htmlMode.indent(state.htmlState,textAfter):state.localMode.indent?state.localMode.indent(state.localState,textAfter):CodeMirror.Pass},innerMode:function(state){return{state:state.localState||state.htmlState,mode:state.localMode||htmlMode}}}},"xml","javascript","css");CodeMirror.defineMIME("text/html","htmlmixed")});
1
+ !function(mod){"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror"),require("../xml/xml"),require("../javascript/javascript"),require("../css/css")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","../xml/xml","../javascript/javascript","../css/css"],mod):mod(CodeMirror)}(function(CodeMirror){"use strict";function maybeBackup(stream,pat,style){var cur=stream.current(),close=cur.search(pat);if(close>-1)stream.backUp(cur.length-close);else if(cur.match(/<\/?$/)){stream.backUp(cur.length);stream.match(pat,!1)||stream.match(cur)}return style}function getAttrRegexp(attr){var regexp=attrRegexpCache[attr];return regexp?regexp:attrRegexpCache[attr]=new RegExp("\\s+"+attr+"\\s*=\\s*('|\")?([^'\"]+)('|\")?\\s*")}function getAttrValue(text,attr){var match=text.match(getAttrRegexp(attr));return match?/^\s*(.*?)\s*$/.exec(match[2])[1]:""}function getTagRegexp(tagName,anchored){return new RegExp((anchored?"^":"")+"</s*"+tagName+"s*>","i")}function addTags(from,to){for(var tag in from)for(var dest=to[tag]||(to[tag]=[]),source=from[tag],i=source.length-1;i>=0;i--)dest.unshift(source[i])}function findMatchingMode(tagInfo,tagText){for(var i=0;i<tagInfo.length;i++){var spec=tagInfo[i];if(!spec[0]||spec[1].test(getAttrValue(tagText,spec[0])))return spec[2]}}var defaultTags={script:[["lang",/(javascript|babel)/i,"javascript"],["type",/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^$/i,"javascript"],["type",/./,"text/plain"],[null,null,"javascript"]],style:[["lang",/^css$/i,"css"],["type",/^(text\/)?(x-)?(stylesheet|css)$/i,"css"],["type",/./,"text/plain"],[null,null,"css"]]},attrRegexpCache={};CodeMirror.defineMode("htmlmixed",function(config,parserConfig){function html(stream,state){var tagName,style=htmlMode.token(stream,state.htmlState),tag=/\btag\b/.test(style);if(tag&&!/[<>\s\/]/.test(stream.current())&&(tagName=state.htmlState.tagName&&state.htmlState.tagName.toLowerCase())&&tags.hasOwnProperty(tagName))state.inTag=tagName+" ";else if(state.inTag&&tag&&/>$/.test(stream.current())){var inTag=/^([\S]+) (.*)/.exec(state.inTag);state.inTag=null;var modeSpec=">"==stream.current()&&findMatchingMode(tags[inTag[1]],inTag[2]),mode=CodeMirror.getMode(config,modeSpec),endTagA=getTagRegexp(inTag[1],!0),endTag=getTagRegexp(inTag[1],!1);state.token=function(stream,state){if(stream.match(endTagA,!1)){state.token=html;state.localState=state.localMode=null;return null}return maybeBackup(stream,endTag,state.localMode.token(stream,state.localState))};state.localMode=mode;state.localState=CodeMirror.startState(mode,htmlMode.indent(state.htmlState,""))}else if(state.inTag){state.inTag+=stream.current();stream.eol()&&(state.inTag+=" ")}return style}var htmlMode=CodeMirror.getMode(config,{name:"xml",htmlMode:!0,multilineTagIndentFactor:parserConfig.multilineTagIndentFactor,multilineTagIndentPastTag:parserConfig.multilineTagIndentPastTag}),tags={},configTags=parserConfig&&parserConfig.tags,configScript=parserConfig&&parserConfig.scriptTypes;addTags(defaultTags,tags);configTags&&addTags(configTags,tags);if(configScript)for(var i=configScript.length-1;i>=0;i--)tags.script.unshift(["type",configScript[i].matches,configScript[i].mode]);return{startState:function(){var state=CodeMirror.startState(htmlMode);return{token:html,inTag:null,localMode:null,localState:null,htmlState:state}},copyState:function(state){var local;state.localState&&(local=CodeMirror.copyState(state.localMode,state.localState));return{token:state.token,inTag:state.inTag,localMode:state.localMode,localState:local,htmlState:CodeMirror.copyState(htmlMode,state.htmlState)}},token:function(stream,state){return state.token(stream,state)},indent:function(state,textAfter){return!state.localMode||/^\s*<\//.test(textAfter)?htmlMode.indent(state.htmlState,textAfter):state.localMode.indent?state.localMode.indent(state.localState,textAfter):CodeMirror.Pass},innerMode:function(state){return{state:state.localState||state.htmlState,mode:state.localMode||htmlMode}}}},"xml","javascript","css");CodeMirror.defineMIME("text/html","htmlmixed")});
js/esites_editor/dist/js/vendor/codemirror/mode/javascript/javascript.js CHANGED
@@ -1 +1 @@
1
- !function(mod){"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],mod):mod(CodeMirror)}(function(CodeMirror){"use strict";function expressionAllowed(stream,state,backUp){return/^(?:operator|sof|keyword c|case|new|[\[{}\(,;:]|=>)$/.test(state.lastType)||"quasi"==state.lastType&&/\{\s*$/.test(stream.string.slice(0,stream.pos-(backUp||0)))}CodeMirror.defineMode("javascript",function(config,parserConfig){function readRegexp(stream){for(var next,escaped=!1,inSet=!1;null!=(next=stream.next());){if(!escaped){if("/"==next&&!inSet)return;"["==next?inSet=!0:inSet&&"]"==next&&(inSet=!1)}escaped=!escaped&&"\\"==next}}function ret(tp,style,cont){type=tp;content=cont;return style}function tokenBase(stream,state){var ch=stream.next();if('"'==ch||"'"==ch){state.tokenize=tokenString(ch);return state.tokenize(stream,state)}if("."==ch&&stream.match(/^\d+(?:[eE][+\-]?\d+)?/))return ret("number","number");if("."==ch&&stream.match(".."))return ret("spread","meta");if(/[\[\]{}\(\),;\:\.]/.test(ch))return ret(ch);if("="==ch&&stream.eat(">"))return ret("=>","operator");if("0"==ch&&stream.eat(/x/i)){stream.eatWhile(/[\da-f]/i);return ret("number","number")}if("0"==ch&&stream.eat(/o/i)){stream.eatWhile(/[0-7]/i);return ret("number","number")}if("0"==ch&&stream.eat(/b/i)){stream.eatWhile(/[01]/i);return ret("number","number")}if(/\d/.test(ch)){stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);return ret("number","number")}if("/"==ch){if(stream.eat("*")){state.tokenize=tokenComment;return tokenComment(stream,state)}if(stream.eat("/")){stream.skipToEnd();return ret("comment","comment")}if(expressionAllowed(stream,state,1)){readRegexp(stream);stream.match(/^\b(([gimyu])(?![gimyu]*\2))+\b/);return ret("regexp","string-2")}stream.eatWhile(isOperatorChar);return ret("operator","operator",stream.current())}if("`"==ch){state.tokenize=tokenQuasi;return tokenQuasi(stream,state)}if("#"==ch){stream.skipToEnd();return ret("error","error")}if(isOperatorChar.test(ch)){stream.eatWhile(isOperatorChar);return ret("operator","operator",stream.current())}if(wordRE.test(ch)){stream.eatWhile(wordRE);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 tokenString(quote){return function(stream,state){var next,escaped=!1;if(jsonldMode&&"@"==stream.peek()&&stream.match(isJsonldKeyword)){state.tokenize=tokenBase;return ret("jsonld-keyword","meta")}for(;null!=(next=stream.next())&&(next!=quote||escaped);)escaped=!escaped&&"\\"==next;escaped||(state.tokenize=tokenBase);return ret("string","string")}}function tokenComment(stream,state){for(var ch,maybeEnd=!1;ch=stream.next();){if("/"==ch&&maybeEnd){state.tokenize=tokenBase;break}maybeEnd="*"==ch}return ret("comment","comment")}function tokenQuasi(stream,state){for(var next,escaped=!1;null!=(next=stream.next());){if(!escaped&&("`"==next||"$"==next&&stream.eat("{"))){state.tokenize=tokenBase;break}escaped=!escaped&&"\\"==next}return ret("quasi","string-2",stream.current())}function findFatArrow(stream,state){state.fatArrowAt&&(state.fatArrowAt=null);var arrow=stream.string.indexOf("=>",stream.start);if(!(0>arrow)){for(var depth=0,sawSomething=!1,pos=arrow-1;pos>=0;--pos){var ch=stream.string.charAt(pos),bracket=brackets.indexOf(ch);if(bracket>=0&&3>bracket){if(!depth){++pos;break}if(0==--depth)break}else if(bracket>=3&&6>bracket)++depth;else if(wordRE.test(ch))sawSomething=!0;else{if(/["'\/]/.test(ch))return;if(sawSomething&&!depth){++pos;break}}}sawSomething&&!depth&&(state.fatArrowAt=pos)}}function JSLexical(indented,column,type,align,prev,info){this.indented=indented;this.column=column;this.type=type;this.prev=prev;this.info=info;null!=align&&(this.align=align)}function inScope(state,varname){for(var v=state.localVars;v;v=v.next)if(v.name==varname)return!0;for(var cx=state.context;cx;cx=cx.prev)for(var v=cx.vars;v;v=v.next)if(v.name==varname)return!0}function parseJS(state,style,type,content,stream){var cc=state.cc;cx.state=state;cx.stream=stream;cx.marked=null,cx.cc=cc;cx.style=style;state.lexical.hasOwnProperty("align")||(state.lexical.align=!0);for(;;){var combinator=cc.length?cc.pop():jsonMode?expression:statement;if(combinator(type,content)){for(;cc.length&&cc[cc.length-1].lex;)cc.pop()();return cx.marked?cx.marked:"variable"==type&&inScope(state,content)?"variable-2":style}}}function pass(){for(var i=arguments.length-1;i>=0;i--)cx.cc.push(arguments[i])}function cont(){pass.apply(null,arguments);return!0}function register(varname){function inList(list){for(var v=list;v;v=v.next)if(v.name==varname)return!0;return!1}var state=cx.state;cx.marked="def";if(state.context){if(inList(state.localVars))return;state.localVars={name:varname,next:state.localVars}}else{if(inList(state.globalVars))return;parserConfig.globalVars&&(state.globalVars={name:varname,next:state.globalVars})}}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,indent=state.indented;if("stat"==state.lexical.type)indent=state.lexical.indented;else for(var outer=state.lexical;outer&&")"==outer.type&&outer.align;outer=outer.prev)indent=outer.indented;state.lexical=new JSLexical(indent,cx.stream.column(),type,null,state.lexical,info)};result.lex=!0;return result}function poplex(){var state=cx.state;if(state.lexical.prev){")"==state.lexical.type&&(state.indented=state.lexical.indented);state.lexical=state.lexical.prev}}function expect(wanted){function exp(type){return type==wanted?cont():";"==wanted?pass():cont(exp)}return exp}function statement(type,value){if("var"==type)return cont(pushlex("vardef",value.length),vardef,expect(";"),poplex);if("keyword a"==type)return cont(pushlex("form"),expression,statement,poplex);if("keyword b"==type)return cont(pushlex("form"),statement,poplex);if("{"==type)return cont(pushlex("}"),block,poplex);if(";"==type)return cont();if("if"==type){"else"==cx.state.lexical.info&&cx.state.cc[cx.state.cc.length-1]==poplex&&cx.state.cc.pop()();return cont(pushlex("form"),expression,statement,poplex,maybeelse)}return"function"==type?cont(functiondef):"for"==type?cont(pushlex("form"),forspec,statement,poplex):"variable"==type?cont(pushlex("stat"),maybelabel):"switch"==type?cont(pushlex("form"),expression,pushlex("}","switch"),expect("{"),block,poplex,poplex):"case"==type?cont(expression,expect(":")):"default"==type?cont(expect(":")):"catch"==type?cont(pushlex("form"),pushcontext,expect("("),funarg,expect(")"),statement,poplex,popcontext):"class"==type?cont(pushlex("form"),className,poplex):"export"==type?cont(pushlex("stat"),afterExport,poplex):"import"==type?cont(pushlex("stat"),afterImport,poplex):"module"==type?cont(pushlex("form"),pattern,pushlex("}"),expect("{"),block,poplex,poplex):pass(pushlex("stat"),expression,expect(";"),poplex)}function expression(type){return expressionInner(type,!1)}function expressionNoComma(type){return expressionInner(type,!0)}function expressionInner(type,noComma){if(cx.state.fatArrowAt==cx.stream.start){var body=noComma?arrowBodyNoComma:arrowBody;if("("==type)return cont(pushcontext,pushlex(")"),commasep(pattern,")"),poplex,expect("=>"),body,popcontext);if("variable"==type)return pass(pushcontext,pattern,expect("=>"),body,popcontext)}var maybeop=noComma?maybeoperatorNoComma:maybeoperatorComma;return atomicTypes.hasOwnProperty(type)?cont(maybeop):"function"==type?cont(functiondef,maybeop):"keyword c"==type?cont(noComma?maybeexpressionNoComma:maybeexpression):"("==type?cont(pushlex(")"),maybeexpression,comprehension,expect(")"),poplex,maybeop):"operator"==type||"spread"==type?cont(noComma?expressionNoComma:expression):"["==type?cont(pushlex("]"),arrayLiteral,poplex,maybeop):"{"==type?contCommasep(objprop,"}",null,maybeop):"quasi"==type?pass(quasi,maybeop):"new"==type?cont(maybeTarget(noComma)):cont()}function maybeexpression(type){return type.match(/[;\}\)\],]/)?pass():pass(expression)}function maybeexpressionNoComma(type){return type.match(/[;\}\)\],]/)?pass():pass(expressionNoComma)}function maybeoperatorComma(type,value){return","==type?cont(expression):maybeoperatorNoComma(type,value,!1)}function maybeoperatorNoComma(type,value,noComma){var me=0==noComma?maybeoperatorComma:maybeoperatorNoComma,expr=0==noComma?expression:expressionNoComma;return"=>"==type?cont(pushcontext,noComma?arrowBodyNoComma:arrowBody,popcontext):"operator"==type?/\+\+|--/.test(value)?cont(me):"?"==value?cont(expression,expect(":"),expr):cont(expr):"quasi"==type?pass(quasi,me):";"!=type?"("==type?contCommasep(expressionNoComma,")","call",me):"."==type?cont(property,me):"["==type?cont(pushlex("]"),maybeexpression,expect("]"),poplex,me):void 0:void 0}function quasi(type,value){return"quasi"!=type?pass():"${"!=value.slice(value.length-2)?cont(quasi):cont(expression,continueQuasi)}function continueQuasi(type){if("}"==type){cx.marked="string-2";cx.state.tokenize=tokenQuasi;return cont(quasi)}}function arrowBody(type){findFatArrow(cx.stream,cx.state);return pass("{"==type?statement:expression)}function arrowBodyNoComma(type){findFatArrow(cx.stream,cx.state);return pass("{"==type?statement:expressionNoComma)}function maybeTarget(noComma){return function(type){return"."==type?cont(noComma?targetNoComma:target):pass(noComma?expressionNoComma:expression)}}function target(_,value){if("target"==value){cx.marked="keyword";return cont(maybeoperatorComma)}}function targetNoComma(_,value){if("target"==value){cx.marked="keyword";return cont(maybeoperatorNoComma)}}function maybelabel(type){return":"==type?cont(poplex,statement):pass(maybeoperatorComma,expect(";"),poplex)}function property(type){if("variable"==type){cx.marked="property";return cont()}}function objprop(type,value){if("variable"==type||"keyword"==cx.style){cx.marked="property";return cont("get"==value||"set"==value?getterSetter:afterprop)}if("number"==type||"string"==type){cx.marked=jsonldMode?"property":cx.style+" property";return cont(afterprop)}return"jsonld-keyword"==type?cont(afterprop):"modifier"==type?cont(objprop):"["==type?cont(expression,expect("]"),afterprop):"spread"==type?cont(expression):void 0}function getterSetter(type){if("variable"!=type)return pass(afterprop);cx.marked="property";return cont(functiondef)}function afterprop(type){return":"==type?cont(expressionNoComma):"("==type?pass(functiondef):void 0}function commasep(what,end){function proceed(type){if(","==type){var lex=cx.state.lexical;"call"==lex.info&&(lex.pos=(lex.pos||0)+1);return cont(what,proceed)}return type==end?cont():cont(expect(end))}return function(type){return type==end?cont():pass(what,proceed)}}function contCommasep(what,end,info){for(var i=3;i<arguments.length;i++)cx.cc.push(arguments[i]);return cont(pushlex(end,info),commasep(what,end),poplex)}function block(type){return"}"==type?cont():pass(statement,block)}function maybetype(type){return isTS&&":"==type?cont(typedef):void 0}function maybedefault(_,value){return"="==value?cont(expressionNoComma):void 0}function typedef(type){if("variable"==type){cx.marked="variable-3";return cont()}}function vardef(){return pass(pattern,maybetype,maybeAssign,vardefCont)}function pattern(type,value){if("modifier"==type)return cont(pattern);if("variable"==type){register(value);return cont()}return"spread"==type?cont(pattern):"["==type?contCommasep(pattern,"]"):"{"==type?contCommasep(proppattern,"}"):void 0}function proppattern(type,value){if("variable"==type&&!cx.stream.match(/^\s*:/,!1)){register(value);return cont(maybeAssign)}"variable"==type&&(cx.marked="property");return"spread"==type?cont(pattern):"}"==type?pass():cont(expect(":"),pattern,maybeAssign)}function maybeAssign(_type,value){return"="==value?cont(expressionNoComma):void 0}function vardefCont(type){return","==type?cont(vardef):void 0}function maybeelse(type,value){return"keyword b"==type&&"else"==value?cont(pushlex("form","else"),statement,poplex):void 0}function forspec(type){return"("==type?cont(pushlex(")"),forspec1,expect(")"),poplex):void 0}function forspec1(type){return"var"==type?cont(vardef,expect(";"),forspec2):";"==type?cont(forspec2):"variable"==type?cont(formaybeinof):pass(expression,expect(";"),forspec2)}function formaybeinof(_type,value){if("in"==value||"of"==value){cx.marked="keyword";return cont(expression)}return cont(maybeoperatorComma,forspec2)}function forspec2(type,value){if(";"==type)return cont(forspec3);if("in"==value||"of"==value){cx.marked="keyword";return cont(expression)}return pass(expression,expect(";"),forspec3)}function forspec3(type){")"!=type&&cont(expression)}function functiondef(type,value){if("*"==value){cx.marked="keyword";return cont(functiondef)}if("variable"==type){register(value);return cont(functiondef)}return"("==type?cont(pushcontext,pushlex(")"),commasep(funarg,")"),poplex,statement,popcontext):void 0}function funarg(type){return"spread"==type?cont(funarg):pass(pattern,maybetype,maybedefault)}function className(type,value){if("variable"==type){register(value);return cont(classNameAfter)}}function classNameAfter(type,value){return"extends"==value?cont(expression,classNameAfter):"{"==type?cont(pushlex("}"),classBody,poplex):void 0}function classBody(type,value){if("variable"==type||"keyword"==cx.style){if("static"==value){cx.marked="keyword";return cont(classBody)}cx.marked="property";return"get"==value||"set"==value?cont(classGetterSetter,functiondef,classBody):cont(functiondef,classBody)}if("*"==value){cx.marked="keyword";return cont(classBody)}return";"==type?cont(classBody):"}"==type?cont():void 0}function classGetterSetter(type){if("variable"!=type)return pass();cx.marked="property";return cont()}function afterExport(_type,value){if("*"==value){cx.marked="keyword";return cont(maybeFrom,expect(";"))}if("default"==value){cx.marked="keyword";return cont(expression,expect(";"))}return pass(statement)}function afterImport(type){return"string"==type?cont():pass(importSpec,maybeFrom)}function importSpec(type,value){if("{"==type)return contCommasep(importSpec,"}");"variable"==type&&register(value);"*"==value&&(cx.marked="keyword");return cont(maybeAs)}function maybeAs(_type,value){if("as"==value){cx.marked="keyword";return cont(importSpec)}}function maybeFrom(_type,value){if("from"==value){cx.marked="keyword";return cont(expression)}}function arrayLiteral(type){return"]"==type?cont():pass(expressionNoComma,maybeArrayComprehension)}function maybeArrayComprehension(type){return"for"==type?pass(comprehension,expect("]")):","==type?cont(commasep(maybeexpressionNoComma,"]")):pass(commasep(expressionNoComma,"]"))}function comprehension(type){return"for"==type?cont(forspec,comprehension):"if"==type?cont(expression,comprehension):void 0}function isContinuedStatement(state,textAfter){return"operator"==state.lastType||","==state.lastType||isOperatorChar.test(textAfter.charAt(0))||/[,.]/.test(textAfter.charAt(0))}var type,content,indentUnit=config.indentUnit,statementIndent=parserConfig.statementIndent,jsonldMode=parserConfig.jsonld,jsonMode=parserConfig.json||jsonldMode,isTS=parserConfig.typescript,wordRE=parserConfig.wordCharacters||/[\w$\xa1-\uffff]/,keywords=function(){function kw(type){return{type:type,style:"keyword"}}var A=kw("keyword a"),B=kw("keyword b"),C=kw("keyword c"),operator=kw("operator"),atom={type:"atom",style:"atom"},jsKeywords={"if":kw("if"),"while":A,"with":A,"else":B,"do":B,"try":B,"finally":B,"return":C,"break":C,"continue":C,"new":kw("new"),"delete":C,"throw":C,"debugger":C,"var":kw("var"),"const":kw("var"),let:kw("var"),"function":kw("function"),"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,"this":kw("this"),"class":kw("class"),"super":kw("atom"),"yield":C,"export":kw("export"),"import":kw("import"),"extends":C};if(isTS){var type={type:"variable",style:"variable-3"},tsKeywords={"interface":kw("class"),"implements":C,namespace:C,module:kw("module"),"enum":kw("module"),"public":kw("modifier"),"private":kw("modifier"),"protected":kw("modifier"),"abstract":kw("modifier"),as:operator,string:type,number:type,"boolean":type,any:type};for(var attr in tsKeywords)jsKeywords[attr]=tsKeywords[attr]}return jsKeywords}(),isOperatorChar=/[+\-*&%=<>!?|~^]/,isJsonldKeyword=/^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/,brackets="([{}])",atomicTypes={atom:!0,number:!0,variable:!0,string:!0,regexp:!0,"this":!0,"jsonld-keyword":!0},cx={state:null,column:null,marked:null,cc:null},defaultVars={name:"this",next:{name:"arguments"}};poplex.lex=!0;return{startState:function(basecolumn){var state={tokenize:tokenBase,lastType:"sof",cc:[],lexical:new JSLexical((basecolumn||0)-indentUnit,0,"block",!1),localVars:parserConfig.localVars,context:parserConfig.localVars&&{vars:parserConfig.localVars},indented:basecolumn||0};parserConfig.globalVars&&"object"==typeof parserConfig.globalVars&&(state.globalVars=parserConfig.globalVars);return state},token:function(stream,state){if(stream.sol()){state.lexical.hasOwnProperty("align")||(state.lexical.align=!1);state.indented=stream.indentation();findFatArrow(stream,state)}if(state.tokenize!=tokenComment&&stream.eatSpace())return null;var style=state.tokenize(stream,state);if("comment"==type)return style;state.lastType="operator"!=type||"++"!=content&&"--"!=content?type:"incdec";return parseJS(state,style,type,content,stream)},indent:function(state,textAfter){if(state.tokenize==tokenComment)return CodeMirror.Pass;if(state.tokenize!=tokenBase)return 0;var firstChar=textAfter&&textAfter.charAt(0),lexical=state.lexical;if(!/^\s*else\b/.test(textAfter))for(var i=state.cc.length-1;i>=0;--i){var c=state.cc[i];if(c==poplex)lexical=lexical.prev;else if(c!=maybeelse)break}"stat"==lexical.type&&"}"==firstChar&&(lexical=lexical.prev);statementIndent&&")"==lexical.type&&"stat"==lexical.prev.type&&(lexical=lexical.prev);var type=lexical.type,closing=firstChar==type;return"vardef"==type?lexical.indented+("operator"==state.lastType||","==state.lastType?lexical.info+1:0):"form"==type&&"{"==firstChar?lexical.indented:"form"==type?lexical.indented+indentUnit:"stat"==type?lexical.indented+(isContinuedStatement(state,textAfter)?statementIndent||indentUnit:0):"switch"!=lexical.info||closing||0==parserConfig.doubleIndentSwitch?lexical.align?lexical.column+(closing?0:1):lexical.indented+(closing?0:indentUnit):lexical.indented+(/^(?:case|default)\b/.test(textAfter)?indentUnit:2*indentUnit)},electricInput:/^\s*(?:case .*?:|default:|\{|\})$/,blockCommentStart:jsonMode?null:"/*",blockCommentEnd:jsonMode?null:"*/",lineComment:jsonMode?null:"//",fold:"brace",closeBrackets:"()[]{}''\"\"``",helperType:jsonMode?"json":"javascript",jsonldMode:jsonldMode,jsonMode:jsonMode,expressionAllowed:expressionAllowed,skipExpression:function(state){var top=state.cc[state.cc.length-1];(top==expression||top==expressionNoComma)&&state.cc.pop()}}});CodeMirror.registerHelper("wordChars","javascript",/[\w$]/);CodeMirror.defineMIME("text/javascript","javascript");CodeMirror.defineMIME("text/ecmascript","javascript");CodeMirror.defineMIME("application/javascript","javascript");CodeMirror.defineMIME("application/x-javascript","javascript");CodeMirror.defineMIME("application/ecmascript","javascript");CodeMirror.defineMIME("application/json",{name:"javascript",json:!0});CodeMirror.defineMIME("application/x-json",{name:"javascript",json:!0});CodeMirror.defineMIME("application/ld+json",{name:"javascript",jsonld:!0});CodeMirror.defineMIME("text/typescript",{name:"javascript",typescript:!0});CodeMirror.defineMIME("application/typescript",{name:"javascript",typescript:!0})});
1
+ !function(mod){"object"==typeof exports&&"object"==typeof module?mod(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],mod):mod(CodeMirror)}(function(CodeMirror){"use strict";function expressionAllowed(stream,state,backUp){return/^(?:operator|sof|keyword c|case|new|export|default|[\[{}\(,;:]|=>)$/.test(state.lastType)||"quasi"==state.lastType&&/\{\s*$/.test(stream.string.slice(0,stream.pos-(backUp||0)))}CodeMirror.defineMode("javascript",function(config,parserConfig){function readRegexp(stream){for(var next,escaped=!1,inSet=!1;null!=(next=stream.next());){if(!escaped){if("/"==next&&!inSet)return;"["==next?inSet=!0:inSet&&"]"==next&&(inSet=!1)}escaped=!escaped&&"\\"==next}}function ret(tp,style,cont){type=tp;content=cont;return style}function tokenBase(stream,state){var ch=stream.next();if('"'==ch||"'"==ch){state.tokenize=tokenString(ch);return state.tokenize(stream,state)}if("."==ch&&stream.match(/^\d+(?:[eE][+\-]?\d+)?/))return ret("number","number");if("."==ch&&stream.match(".."))return ret("spread","meta");if(/[\[\]{}\(\),;\:\.]/.test(ch))return ret(ch);if("="==ch&&stream.eat(">"))return ret("=>","operator");if("0"==ch&&stream.eat(/x/i)){stream.eatWhile(/[\da-f]/i);return ret("number","number")}if("0"==ch&&stream.eat(/o/i)){stream.eatWhile(/[0-7]/i);return ret("number","number")}if("0"==ch&&stream.eat(/b/i)){stream.eatWhile(/[01]/i);return ret("number","number")}if(/\d/.test(ch)){stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);return ret("number","number")}if("/"==ch){if(stream.eat("*")){state.tokenize=tokenComment;return tokenComment(stream,state)}if(stream.eat("/")){stream.skipToEnd();return ret("comment","comment")}if(expressionAllowed(stream,state,1)){readRegexp(stream);stream.match(/^\b(([gimyu])(?![gimyu]*\2))+\b/);return ret("regexp","string-2")}stream.eatWhile(isOperatorChar);return ret("operator","operator",stream.current())}if("`"==ch){state.tokenize=tokenQuasi;return tokenQuasi(stream,state)}if("#"==ch){stream.skipToEnd();return ret("error","error")}if(isOperatorChar.test(ch)){">"==ch&&state.lexical&&">"==state.lexical.type||stream.eatWhile(isOperatorChar);return ret("operator","operator",stream.current())}if(wordRE.test(ch)){stream.eatWhile(wordRE);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 tokenString(quote){return function(stream,state){var next,escaped=!1;if(jsonldMode&&"@"==stream.peek()&&stream.match(isJsonldKeyword)){state.tokenize=tokenBase;return ret("jsonld-keyword","meta")}for(;null!=(next=stream.next())&&(next!=quote||escaped);)escaped=!escaped&&"\\"==next;escaped||(state.tokenize=tokenBase);return ret("string","string")}}function tokenComment(stream,state){for(var ch,maybeEnd=!1;ch=stream.next();){if("/"==ch&&maybeEnd){state.tokenize=tokenBase;break}maybeEnd="*"==ch}return ret("comment","comment")}function tokenQuasi(stream,state){for(var next,escaped=!1;null!=(next=stream.next());){if(!escaped&&("`"==next||"$"==next&&stream.eat("{"))){state.tokenize=tokenBase;break}escaped=!escaped&&"\\"==next}return ret("quasi","string-2",stream.current())}function findFatArrow(stream,state){state.fatArrowAt&&(state.fatArrowAt=null);var arrow=stream.string.indexOf("=>",stream.start);if(!(arrow<0)){if(isTS){var m=/:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start,arrow));m&&(arrow=m.index)}for(var depth=0,sawSomething=!1,pos=arrow-1;pos>=0;--pos){var ch=stream.string.charAt(pos),bracket=brackets.indexOf(ch);if(bracket>=0&&bracket<3){if(!depth){++pos;break}if(0==--depth){"("==ch&&(sawSomething=!0);break}}else if(bracket>=3&&bracket<6)++depth;else if(wordRE.test(ch))sawSomething=!0;else{if(/["'\/]/.test(ch))return;if(sawSomething&&!depth){++pos;break}}}sawSomething&&!depth&&(state.fatArrowAt=pos)}}function JSLexical(indented,column,type,align,prev,info){this.indented=indented;this.column=column;this.type=type;this.prev=prev;this.info=info;null!=align&&(this.align=align)}function inScope(state,varname){for(var v=state.localVars;v;v=v.next)if(v.name==varname)return!0;for(var cx=state.context;cx;cx=cx.prev)for(var v=cx.vars;v;v=v.next)if(v.name==varname)return!0}function parseJS(state,style,type,content,stream){var cc=state.cc;cx.state=state;cx.stream=stream;cx.marked=null,cx.cc=cc;cx.style=style;state.lexical.hasOwnProperty("align")||(state.lexical.align=!0);for(;;){var combinator=cc.length?cc.pop():jsonMode?expression:statement;if(combinator(type,content)){for(;cc.length&&cc[cc.length-1].lex;)cc.pop()();return cx.marked?cx.marked:"variable"==type&&inScope(state,content)?"variable-2":style}}}function pass(){for(var i=arguments.length-1;i>=0;i--)cx.cc.push(arguments[i])}function cont(){pass.apply(null,arguments);return!0}function register(varname){function inList(list){for(var v=list;v;v=v.next)if(v.name==varname)return!0;return!1}var state=cx.state;cx.marked="def";if(state.context){if(inList(state.localVars))return;state.localVars={name:varname,next:state.localVars}}else{if(inList(state.globalVars))return;parserConfig.globalVars&&(state.globalVars={name:varname,next:state.globalVars})}}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,indent=state.indented;if("stat"==state.lexical.type)indent=state.lexical.indented;else for(var outer=state.lexical;outer&&")"==outer.type&&outer.align;outer=outer.prev)indent=outer.indented;state.lexical=new JSLexical(indent,cx.stream.column(),type,null,state.lexical,info)};result.lex=!0;return result}function poplex(){var state=cx.state;if(state.lexical.prev){")"==state.lexical.type&&(state.indented=state.lexical.indented);state.lexical=state.lexical.prev}}function expect(wanted){function exp(type){return type==wanted?cont():";"==wanted?pass():cont(exp)}return exp}function statement(type,value){if("var"==type)return cont(pushlex("vardef",value.length),vardef,expect(";"),poplex);if("keyword a"==type)return cont(pushlex("form"),parenExpr,statement,poplex);if("keyword b"==type)return cont(pushlex("form"),statement,poplex);if("{"==type)return cont(pushlex("}"),block,poplex);if(";"==type)return cont();if("if"==type){"else"==cx.state.lexical.info&&cx.state.cc[cx.state.cc.length-1]==poplex&&cx.state.cc.pop()();return cont(pushlex("form"),parenExpr,statement,poplex,maybeelse)}return"function"==type?cont(functiondef):"for"==type?cont(pushlex("form"),forspec,statement,poplex):"variable"==type?cont(pushlex("stat"),maybelabel):"switch"==type?cont(pushlex("form"),parenExpr,pushlex("}","switch"),expect("{"),block,poplex,poplex):"case"==type?cont(expression,expect(":")):"default"==type?cont(expect(":")):"catch"==type?cont(pushlex("form"),pushcontext,expect("("),funarg,expect(")"),statement,poplex,popcontext):"class"==type?cont(pushlex("form"),className,poplex):"export"==type?cont(pushlex("stat"),afterExport,poplex):"import"==type?cont(pushlex("stat"),afterImport,poplex):"module"==type?cont(pushlex("form"),pattern,pushlex("}"),expect("{"),block,poplex,poplex):"type"==type?cont(typeexpr,expect("operator"),typeexpr,expect(";")):"async"==type?cont(statement):pass(pushlex("stat"),expression,expect(";"),poplex)}function expression(type){return expressionInner(type,!1)}function expressionNoComma(type){return expressionInner(type,!0)}function parenExpr(type){return"("!=type?pass():cont(pushlex(")"),expression,expect(")"),poplex)}function expressionInner(type,noComma){if(cx.state.fatArrowAt==cx.stream.start){var body=noComma?arrowBodyNoComma:arrowBody;if("("==type)return cont(pushcontext,pushlex(")"),commasep(pattern,")"),poplex,expect("=>"),body,popcontext);if("variable"==type)return pass(pushcontext,pattern,expect("=>"),body,popcontext)}var maybeop=noComma?maybeoperatorNoComma:maybeoperatorComma;return atomicTypes.hasOwnProperty(type)?cont(maybeop):"function"==type?cont(functiondef,maybeop):"class"==type?cont(pushlex("form"),classExpression,poplex):"keyword c"==type||"async"==type?cont(noComma?maybeexpressionNoComma:maybeexpression):"("==type?cont(pushlex(")"),maybeexpression,expect(")"),poplex,maybeop):"operator"==type||"spread"==type?cont(noComma?expressionNoComma:expression):"["==type?cont(pushlex("]"),arrayLiteral,poplex,maybeop):"{"==type?contCommasep(objprop,"}",null,maybeop):"quasi"==type?pass(quasi,maybeop):"new"==type?cont(maybeTarget(noComma)):cont()}function maybeexpression(type){return type.match(/[;\}\)\],]/)?pass():pass(expression)}function maybeexpressionNoComma(type){return type.match(/[;\}\)\],]/)?pass():pass(expressionNoComma)}function maybeoperatorComma(type,value){return","==type?cont(expression):maybeoperatorNoComma(type,value,!1)}function maybeoperatorNoComma(type,value,noComma){var me=0==noComma?maybeoperatorComma:maybeoperatorNoComma,expr=0==noComma?expression:expressionNoComma;return"=>"==type?cont(pushcontext,noComma?arrowBodyNoComma:arrowBody,popcontext):"operator"==type?/\+\+|--/.test(value)?cont(me):"?"==value?cont(expression,expect(":"),expr):cont(expr):"quasi"==type?pass(quasi,me):";"!=type?"("==type?contCommasep(expressionNoComma,")","call",me):"."==type?cont(property,me):"["==type?cont(pushlex("]"),maybeexpression,expect("]"),poplex,me):void 0:void 0}function quasi(type,value){return"quasi"!=type?pass():"${"!=value.slice(value.length-2)?cont(quasi):cont(expression,continueQuasi)}function continueQuasi(type){if("}"==type){cx.marked="string-2";cx.state.tokenize=tokenQuasi;return cont(quasi)}}function arrowBody(type){findFatArrow(cx.stream,cx.state);return pass("{"==type?statement:expression)}function arrowBodyNoComma(type){findFatArrow(cx.stream,cx.state);return pass("{"==type?statement:expressionNoComma)}function maybeTarget(noComma){return function(type){return"."==type?cont(noComma?targetNoComma:target):pass(noComma?expressionNoComma:expression)}}function target(_,value){if("target"==value){cx.marked="keyword";return cont(maybeoperatorComma)}}function targetNoComma(_,value){if("target"==value){cx.marked="keyword";return cont(maybeoperatorNoComma)}}function maybelabel(type){return":"==type?cont(poplex,statement):pass(maybeoperatorComma,expect(";"),poplex)}function property(type){if("variable"==type){cx.marked="property";return cont()}}function objprop(type,value){if("async"==type){cx.marked="property";return cont(objprop)}if("variable"==type||"keyword"==cx.style){cx.marked="property";return cont("get"==value||"set"==value?getterSetter:afterprop)}if("number"==type||"string"==type){cx.marked=jsonldMode?"property":cx.style+" property";return cont(afterprop)}return"jsonld-keyword"==type?cont(afterprop):"modifier"==type?cont(objprop):"["==type?cont(expression,expect("]"),afterprop):"spread"==type?cont(expression):":"==type?pass(afterprop):void 0}function getterSetter(type){if("variable"!=type)return pass(afterprop);cx.marked="property";return cont(functiondef)}function afterprop(type){return":"==type?cont(expressionNoComma):"("==type?pass(functiondef):void 0}function commasep(what,end){function proceed(type,value){if(","==type){var lex=cx.state.lexical;"call"==lex.info&&(lex.pos=(lex.pos||0)+1);return cont(function(type,value){return type==end||value==end?pass():pass(what)},proceed)}return type==end||value==end?cont():cont(expect(end))}return function(type,value){return type==end||value==end?cont():pass(what,proceed)}}function contCommasep(what,end,info){for(var i=3;i<arguments.length;i++)cx.cc.push(arguments[i]);return cont(pushlex(end,info),commasep(what,end),poplex)}function block(type){return"}"==type?cont():pass(statement,block)}function maybetype(type,value){if(isTS){if(":"==type)return cont(typeexpr);if("?"==value)return cont(maybetype)}}function typeexpr(type){if("variable"==type){cx.marked="variable-3";return cont(afterType)}return"string"==type||"number"==type||"atom"==type?cont(afterType):"{"==type?cont(commasep(typeprop,"}")):"("==type?cont(commasep(typearg,")"),maybeReturnType):void 0}function maybeReturnType(type){if("=>"==type)return cont(typeexpr)}function typeprop(type){if("variable"==type||"keyword"==cx.style){cx.marked="property";return cont(typeprop)}if(":"==type)return cont(typeexpr)}function typearg(type){return"variable"==type?cont(typearg):":"==type?cont(typeexpr):void 0}function afterType(type,value){return"<"==value?cont(pushlex(">"),commasep(typeexpr,">"),poplex,afterType):"|"==value||"."==type?cont(typeexpr):"["==type?cont(expect("]"),afterType):void 0}function vardef(){return pass(pattern,maybetype,maybeAssign,vardefCont)}function pattern(type,value){if("modifier"==type)return cont(pattern);if("variable"==type){register(value);return cont()}return"spread"==type?cont(pattern):"["==type?contCommasep(pattern,"]"):"{"==type?contCommasep(proppattern,"}"):void 0}function proppattern(type,value){if("variable"==type&&!cx.stream.match(/^\s*:/,!1)){register(value);return cont(maybeAssign)}"variable"==type&&(cx.marked="property");return"spread"==type?cont(pattern):"}"==type?pass():cont(expect(":"),pattern,maybeAssign)}function maybeAssign(_type,value){if("="==value)return cont(expressionNoComma)}function vardefCont(type){if(","==type)return cont(vardef)}function maybeelse(type,value){if("keyword b"==type&&"else"==value)return cont(pushlex("form","else"),statement,poplex)}function forspec(type){if("("==type)return cont(pushlex(")"),forspec1,expect(")"),poplex)}function forspec1(type){return"var"==type?cont(vardef,expect(";"),forspec2):";"==type?cont(forspec2):"variable"==type?cont(formaybeinof):pass(expression,expect(";"),forspec2)}function formaybeinof(_type,value){if("in"==value||"of"==value){cx.marked="keyword";return cont(expression)}return cont(maybeoperatorComma,forspec2)}function forspec2(type,value){if(";"==type)return cont(forspec3);if("in"==value||"of"==value){cx.marked="keyword";return cont(expression)}return pass(expression,expect(";"),forspec3)}function forspec3(type){")"!=type&&cont(expression)}function functiondef(type,value){if("*"==value){cx.marked="keyword";return cont(functiondef)}if("variable"==type){register(value);return cont(functiondef)}if("("==type)return cont(pushcontext,pushlex(")"),commasep(funarg,")"),poplex,maybetype,statement,popcontext)}function funarg(type){return"spread"==type?cont(funarg):pass(pattern,maybetype,maybeAssign)}function classExpression(type,value){return"variable"==type?className(type,value):classNameAfter(type,value)}function className(type,value){if("variable"==type){register(value);return cont(classNameAfter)}}function classNameAfter(type,value){return"extends"==value||"implements"==value?cont(isTS?typeexpr:expression,classNameAfter):"{"==type?cont(pushlex("}"),classBody,poplex):void 0}function classBody(type,value){if("variable"==type||"keyword"==cx.style){if(("static"==value||"get"==value||"set"==value||isTS&&("public"==value||"private"==value||"protected"==value||"readonly"==value||"abstract"==value))&&cx.stream.match(/^\s+[\w$\xa1-\uffff]/,!1)){cx.marked="keyword";return cont(classBody)}cx.marked="property";return cont(isTS?classfield:functiondef,classBody)}if("*"==value){cx.marked="keyword";return cont(classBody)}return";"==type?cont(classBody):"}"==type?cont():void 0}function classfield(type,value){return"?"==value?cont(classfield):":"==type?cont(typeexpr,maybeAssign):pass(functiondef)}function afterExport(type,value){if("*"==value){cx.marked="keyword";return cont(maybeFrom,expect(";"))}if("default"==value){cx.marked="keyword";return cont(expression,expect(";"))}return"{"==type?cont(commasep(exportField,"}"),maybeFrom,expect(";")):pass(statement)}function exportField(type,value){if("as"==value){cx.marked="keyword";return cont(expect("variable"))}if("variable"==type)return pass(expressionNoComma,exportField)}function afterImport(type){return"string"==type?cont():pass(importSpec,maybeMoreImports,maybeFrom)}function importSpec(type,value){if("{"==type)return contCommasep(importSpec,"}");"variable"==type&&register(value);"*"==value&&(cx.marked="keyword");return cont(maybeAs)}function maybeMoreImports(type){if(","==type)return cont(importSpec,maybeMoreImports)}function maybeAs(_type,value){if("as"==value){cx.marked="keyword";return cont(importSpec)}}function maybeFrom(_type,value){if("from"==value){cx.marked="keyword";return cont(expression)}}function arrayLiteral(type){return"]"==type?cont():pass(commasep(expressionNoComma,"]"))}function isContinuedStatement(state,textAfter){return"operator"==state.lastType||","==state.lastType||isOperatorChar.test(textAfter.charAt(0))||/[,.]/.test(textAfter.charAt(0))}var type,content,indentUnit=config.indentUnit,statementIndent=parserConfig.statementIndent,jsonldMode=parserConfig.jsonld,jsonMode=parserConfig.json||jsonldMode,isTS=parserConfig.typescript,wordRE=parserConfig.wordCharacters||/[\w$\xa1-\uffff]/,keywords=function(){function kw(type){return{type:type,style:"keyword"}}var A=kw("keyword a"),B=kw("keyword b"),C=kw("keyword c"),operator=kw("operator"),atom={type:"atom",style:"atom"},jsKeywords={"if":kw("if"),"while":A,"with":A,"else":B,"do":B,"try":B,"finally":B,"return":C,"break":C,"continue":C,"new":kw("new"),"delete":C,"throw":C,"debugger":C,"var":kw("var"),"const":kw("var"),"let":kw("var"),"function":kw("function"),"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,"this":kw("this"),"class":kw("class"),"super":kw("atom"),"yield":C,"export":kw("export"),"import":kw("import"),"extends":C,await:C,async:kw("async")};if(isTS){var type={type:"variable",style:"variable-3"},tsKeywords={"interface":kw("class"),"implements":C,namespace:C,module:kw("module"),"enum":kw("module"),type:kw("type"),"public":kw("modifier"),"private":kw("modifier"),"protected":kw("modifier"),"abstract":kw("modifier"),as:operator,string:type,number:type,"boolean":type,any:type};for(var attr in tsKeywords)jsKeywords[attr]=tsKeywords[attr]}return jsKeywords}(),isOperatorChar=/[+\-*&%=<>!?|~^]/,isJsonldKeyword=/^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/,brackets="([{}])",atomicTypes={atom:!0,number:!0,variable:!0,string:!0,regexp:!0,"this":!0,"jsonld-keyword":!0},cx={state:null,column:null,marked:null,cc:null},defaultVars={name:"this",next:{name:"arguments"}};poplex.lex=!0;return{startState:function(basecolumn){var state={tokenize:tokenBase,lastType:"sof",cc:[],lexical:new JSLexical((basecolumn||0)-indentUnit,0,"block",(!1)),localVars:parserConfig.localVars,context:parserConfig.localVars&&{vars:parserConfig.localVars},indented:basecolumn||0};parserConfig.globalVars&&"object"==typeof parserConfig.globalVars&&(state.globalVars=parserConfig.globalVars);return state},token:function(stream,state){if(stream.sol()){state.lexical.hasOwnProperty("align")||(state.lexical.align=!1);state.indented=stream.indentation();findFatArrow(stream,state)}if(state.tokenize!=tokenComment&&stream.eatSpace())return null;var style=state.tokenize(stream,state);if("comment"==type)return style;state.lastType="operator"!=type||"++"!=content&&"--"!=content?type:"incdec";return parseJS(state,style,type,content,stream)},indent:function(state,textAfter){if(state.tokenize==tokenComment)return CodeMirror.Pass;if(state.tokenize!=tokenBase)return 0;var top,firstChar=textAfter&&textAfter.charAt(0),lexical=state.lexical;if(!/^\s*else\b/.test(textAfter))for(var i=state.cc.length-1;i>=0;--i){var c=state.cc[i];if(c==poplex)lexical=lexical.prev;else if(c!=maybeelse)break}for(;("stat"==lexical.type||"form"==lexical.type)&&("}"==firstChar||(top=state.cc[state.cc.length-1])&&(top==maybeoperatorComma||top==maybeoperatorNoComma)&&!/^[,\.=+\-*:?[\(]/.test(textAfter));)lexical=lexical.prev;statementIndent&&")"==lexical.type&&"stat"==lexical.prev.type&&(lexical=lexical.prev);var type=lexical.type,closing=firstChar==type;return"vardef"==type?lexical.indented+("operator"==state.lastType||","==state.lastType?lexical.info+1:0):"form"==type&&"{"==firstChar?lexical.indented:"form"==type?lexical.indented+indentUnit:"stat"==type?lexical.indented+(isContinuedStatement(state,textAfter)?statementIndent||indentUnit:0):"switch"!=lexical.info||closing||0==parserConfig.doubleIndentSwitch?lexical.align?lexical.column+(closing?0:1):lexical.indented+(closing?0:indentUnit):lexical.indented+(/^(?:case|default)\b/.test(textAfter)?indentUnit:2*indentUnit)},electricInput:/^\s*(?:case .*?:|default:|\{|\})$/,blockCommentStart:jsonMode?null:"/*",blockCommentEnd:jsonMode?null:"*/",lineComment:jsonMode?null:"//",fold:"brace",closeBrackets:"()[]{}''\"\"``",helperType:jsonMode?"json":"javascript",jsonldMode:jsonldMode,jsonMode:jsonMode,expressionAllowed:expressionAllowed,skipExpression:function(state){var top=state.cc[state.cc.length-1];top!=expression&&top!=expressionNoComma||state.cc.pop()}}});CodeMirror.registerHelper("wordChars","javascript",/[\w$]/);CodeMirror.defineMIME("text/javascript","javascript");CodeMirror.defineMIME("text/ecmascript","javascript");CodeMirror.defineMIME("application/javascript","javascript");CodeMirror.defineMIME("application/x-javascript","javascript");CodeMirror.defineMIME("application/ecmascript","javascript");CodeMirror.defineMIME("application/json",{name:"javascript",json:!0});CodeMirror.defineMIME("application/x-json",{name:"javascript",json:!0});CodeMirror.defineMIME("application/ld+json",{name:"javascript",jsonld:!0});CodeMirror.defineMIME("text/typescript",{name:"javascript",typescript:!0});CodeMirror.defineMIME("application/typescript",{name:"javascript",typescript:!0})});
js/esites_editor/dist/js/vendor/codemirror/theme/dracula.css CHANGED
@@ -1 +1 @@
1
- .cm-s-dracula .CodeMirror-gutters,.cm-s-dracula.CodeMirror{background-color:#282a36!important;color:#f8f8f2!important;border:none}.cm-s-dracula .CodeMirror-gutters{color:#282a36}.cm-s-dracula .CodeMirror-cursor{border-left:solid thin #f8f8f0}.cm-s-dracula .CodeMirror-linenumber{color:#6D8A88}.cm-s-dracula .CodeMirror-line::selection,.cm-s-dracula .CodeMirror-line>span::selection,.cm-s-dracula .CodeMirror-line>span>span::selection,.cm-s-dracula.CodeMirror-focused div.CodeMirror-selected{background:rgba(255,255,255,.1)}.cm-s-dracula .CodeMirror-line::-moz-selection,.cm-s-dracula .CodeMirror-line>span::-moz-selection,.cm-s-dracula .CodeMirror-line>span>span::-moz-selection{background:rgba(255,255,255,.1)}.cm-s-dracula span.cm-comment{color:#6272a4}.cm-s-dracula span.cm-string,.cm-s-dracula span.cm-string-2{color:#f1fa8c}.cm-s-dracula span.cm-number{color:#bd93f9}.cm-s-dracula span.cm-variable{color:#50fa7b}.cm-s-dracula span.cm-variable-2{color:#fff}.cm-s-dracula span.cm-def{color:#ffb86c}.cm-s-dracula span.cm-keyword,.cm-s-dracula span.cm-operator{color:#ff79c6}.cm-s-dracula span.cm-atom{color:#bd93f9}.cm-s-dracula span.cm-meta{color:#f8f8f2}.cm-s-dracula span.cm-tag{color:#ff79c6}.cm-s-dracula span.cm-attribute,.cm-s-dracula span.cm-qualifier{color:#50fa7b}.cm-s-dracula span.cm-property{color:#66d9ef}.cm-s-dracula span.cm-builtin,.cm-s-dracula span.cm-variable-3{color:#50fa7b}.cm-s-dracula .CodeMirror-activeline-background{background:rgba(255,255,255,.1)}.cm-s-dracula .CodeMirror-matchingbracket{text-decoration:underline;color:#fff!important}
1
+ .cm-s-dracula .CodeMirror-gutters,.cm-s-dracula.CodeMirror{background-color:#282a36!important;color:#f8f8f2!important;border:none}.cm-s-dracula .CodeMirror-gutters{color:#282a36}.cm-s-dracula .CodeMirror-cursor{border-left:solid thin #f8f8f0}.cm-s-dracula .CodeMirror-linenumber{color:#6D8A88}.cm-s-dracula .CodeMirror-line::selection,.cm-s-dracula .CodeMirror-line>span::selection,.cm-s-dracula .CodeMirror-line>span>span::selection,.cm-s-dracula .CodeMirror-selected{background:rgba(255,255,255,.1)}.cm-s-dracula .CodeMirror-line::-moz-selection,.cm-s-dracula .CodeMirror-line>span::-moz-selection,.cm-s-dracula .CodeMirror-line>span>span::-moz-selection{background:rgba(255,255,255,.1)}.cm-s-dracula span.cm-comment{color:#6272a4}.cm-s-dracula span.cm-string,.cm-s-dracula span.cm-string-2{color:#f1fa8c}.cm-s-dracula span.cm-number{color:#bd93f9}.cm-s-dracula span.cm-variable{color:#50fa7b}.cm-s-dracula span.cm-variable-2{color:#fff}.cm-s-dracula span.cm-def{color:#ffb86c}.cm-s-dracula span.cm-keyword,.cm-s-dracula span.cm-operator{color:#ff79c6}.cm-s-dracula span.cm-atom{color:#bd93f9}.cm-s-dracula span.cm-meta{color:#f8f8f2}.cm-s-dracula span.cm-tag{color:#ff79c6}.cm-s-dracula span.cm-attribute,.cm-s-dracula span.cm-qualifier{color:#50fa7b}.cm-s-dracula span.cm-property{color:#66d9ef}.cm-s-dracula span.cm-builtin,.cm-s-dracula span.cm-variable-3{color:#50fa7b}.cm-s-dracula .CodeMirror-activeline-background{background:rgba(255,255,255,.1)}.cm-s-dracula .CodeMirror-matchingbracket{text-decoration:underline;color:#fff!important}
js/esites_editor/dist/js/vendor/codemirror/theme/duotone-dark.css ADDED
@@ -0,0 +1 @@
 
1
+ .cm-s-duotone-dark.CodeMirror{background:#2a2734;color:#6c6783}.cm-s-duotone-dark div.CodeMirror-selected{background:#545167!important}.cm-s-duotone-dark .CodeMirror-gutters{background:#2a2734;border-right:0}.cm-s-duotone-dark .CodeMirror-linenumber{color:#545167}.cm-s-duotone-dark .CodeMirror-cursor{border-left:1px solid #ffad5c;border-right:.5em solid #ffad5c;opacity:.5}.cm-s-duotone-dark .CodeMirror-activeline-background{background:#363342;opacity:.5}.cm-s-duotone-dark .cm-fat-cursor .CodeMirror-cursor{background:#ffad5c;opacity:.5}.cm-s-duotone-dark span.cm-atom,.cm-s-duotone-dark span.cm-attribute,.cm-s-duotone-dark span.cm-hr,.cm-s-duotone-dark span.cm-keyword,.cm-s-duotone-dark span.cm-link,.cm-s-duotone-dark span.cm-number,.cm-s-duotone-dark span.cm-quote,.cm-s-duotone-dark span.cm-variable{color:#fc9}.cm-s-duotone-dark span.cm-property{color:#9a86fd}.cm-s-duotone-dark span.cm-negative,.cm-s-duotone-dark span.cm-punctuation,.cm-s-duotone-dark span.cm-unit{color:#e09142}.cm-s-duotone-dark span.cm-string{color:#ffb870}.cm-s-duotone-dark span.cm-operator{color:#ffad5c}.cm-s-duotone-dark span.cm-positive{color:#6a51e6}.cm-s-duotone-dark span.cm-string-2,.cm-s-duotone-dark span.cm-url,.cm-s-duotone-dark span.cm-variable-2,.cm-s-duotone-dark span.cm-variable-3{color:#7a63ee}.cm-s-duotone-dark span.cm-builtin,.cm-s-duotone-dark span.cm-def,.cm-s-duotone-dark span.cm-em,.cm-s-duotone-dark span.cm-header,.cm-s-duotone-dark span.cm-qualifier,.cm-s-duotone-dark span.cm-tag{color:#eeebff}.cm-s-duotone-dark span.cm-bracket,.cm-s-duotone-dark span.cm-comment{color:#6c6783}.cm-s-duotone-dark span.cm-error,.cm-s-duotone-dark span.cm-invalidchar{color:red}.cm-s-duotone-dark span.cm-header{font-weight:400}.cm-s-duotone-dark .CodeMirror-matchingbracket{text-decoration:underline;color:#eeebff!important}
js/esites_editor/dist/js/vendor/codemirror/theme/duotone-light.css ADDED
@@ -0,0 +1 @@
 
1
+ .cm-s-duotone-light.CodeMirror{background:#faf8f5;color:#b29762}.cm-s-duotone-light div.CodeMirror-selected{background:#e3dcce!important}.cm-s-duotone-light .CodeMirror-gutters{background:#faf8f5;border-right:0}.cm-s-duotone-light .CodeMirror-linenumber{color:#cdc4b1}.cm-s-duotone-light .CodeMirror-cursor{border-left:1px solid #93abdc;border-right:.5em solid #93abdc;opacity:.5}.cm-s-duotone-light .CodeMirror-activeline-background{background:#e3dcce;opacity:.5}.cm-s-duotone-light .cm-fat-cursor .CodeMirror-cursor{background:#93abdc;opacity:.5}.cm-s-duotone-light span.cm-atom,.cm-s-duotone-light span.cm-attribute,.cm-s-duotone-light span.cm-keyword,.cm-s-duotone-light span.cm-number,.cm-s-duotone-light span.cm-quote,.cm-s-duotone-light span.cm-variable,.cm-s-duotone-light-light span.cm-hr,.cm-s-duotone-light-light span.cm-link{color:#063289}.cm-s-duotone-light span.cm-property{color:#b29762}.cm-s-duotone-light span.cm-negative,.cm-s-duotone-light span.cm-punctuation,.cm-s-duotone-light span.cm-unit{color:#063289}.cm-s-duotone-light span.cm-operator,.cm-s-duotone-light span.cm-string{color:#1659df}.cm-s-duotone-light span.cm-positive,.cm-s-duotone-light span.cm-string-2,.cm-s-duotone-light span.cm-url,.cm-s-duotone-light span.cm-variable-2,.cm-s-duotone-light span.cm-variable-3{color:#896724}.cm-s-duotone-light span.cm-builtin,.cm-s-duotone-light span.cm-def,.cm-s-duotone-light span.cm-em,.cm-s-duotone-light span.cm-header,.cm-s-duotone-light span.cm-qualifier,.cm-s-duotone-light span.cm-tag{color:#2d2006}.cm-s-duotone-light span.cm-bracket,.cm-s-duotone-light span.cm-comment{color:#b6ad9a}.cm-s-duotone-light span.cm-error,.cm-s-duotone-light span.cm-invalidchar{color:red}.cm-s-duotone-light span.cm-header{font-weight:400}.cm-s-duotone-light .CodeMirror-matchingbracket{text-decoration:underline;color:#faf8f5!important}
js/esites_editor/dist/js/vendor/codemirror/theme/panda-syntax.css ADDED
@@ -0,0 +1 @@
 
1
+ .cm-s-panda-syntax{background:#292A2B;color:#E6E6E6;line-height:1.5;font-family:'Operator Mono','Source Sans Pro',Menlo,Monaco,Consolas,Courier New,monospace}.cm-s-panda-syntax .CodeMirror-cursor{border-color:#ff2c6d}.cm-s-panda-syntax .CodeMirror-activeline-background{background:rgba(99,123,156,.1)}.cm-s-panda-syntax .CodeMirror-selected{background:#FFF}.cm-s-panda-syntax .cm-comment{font-style:italic;color:#676B79}.cm-s-panda-syntax .cm-operator{color:#f3f3f3}.cm-s-panda-syntax .cm-string{color:#19F9D8}.cm-s-panda-syntax .cm-string-2{color:#FFB86C}.cm-s-panda-syntax .cm-tag{color:#ff2c6d}.cm-s-panda-syntax .cm-meta{color:#b084eb}.cm-s-panda-syntax .cm-number{color:#FFB86C}.cm-s-panda-syntax .cm-atom{color:#ff2c6d}.cm-s-panda-syntax .cm-keyword{color:#FF75B5}.cm-s-panda-syntax .cm-variable{color:#ffb86c}.cm-s-panda-syntax .cm-variable-2,.cm-s-panda-syntax .cm-variable-3{color:#ff9ac1}.cm-s-panda-syntax .cm-def{color:#e6e6e6}.cm-s-panda-syntax .cm-property{color:#f3f3f3}.cm-s-panda-syntax .cm-attribute,.cm-s-panda-syntax .cm-unit{color:#ffb86c}.cm-s-panda-syntax .CodeMirror-matchingbracket{border-bottom:1px dotted #19F9D8;padding-bottom:2px;color:#e6e6e6}.cm-s-panda-syntax .CodeMirror-gutters{background:#292a2b;border-right-color:rgba(255,255,255,.1)}.cm-s-panda-syntax .CodeMirror-linenumber{color:#e6e6e6;opacity:.6}
js/esites_editor/dist/js/vendor/codemirror/theme/pastel-on-dark.css CHANGED
@@ -1 +1 @@
1
- .cm-s-pastel-on-dark.CodeMirror{background:#2c2827;color:#8F938F;line-height:1.5;font-size:14px}.cm-s-pastel-on-dark .CodeMirror-line::selection,.cm-s-pastel-on-dark .CodeMirror-line>span::selection,.cm-s-pastel-on-dark .CodeMirror-line>span>span::selection,.cm-s-pastel-on-dark div.CodeMirror-selected{background:rgba(221,240,255,.2)}.cm-s-pastel-on-dark .CodeMirror-line::-moz-selection,.cm-s-pastel-on-dark .CodeMirror-line>span::-moz-selection,.cm-s-pastel-on-dark .CodeMirror-line>span>span::-moz-selection{background:rgba(221,240,255,.2)}.cm-s-pastel-on-dark .CodeMirror-gutters{background:#34302f;border-right:0;padding:0 3px}.cm-s-pastel-on-dark .CodeMirror-guttermarker{color:#fff}.cm-s-pastel-on-dark .CodeMirror-guttermarker-subtle,.cm-s-pastel-on-dark .CodeMirror-linenumber{color:#8F938F}.cm-s-pastel-on-dark .CodeMirror-cursor{border-left:1px solid #A7A7A7}.cm-s-pastel-on-dark span.cm-comment{color:#A6C6FF}.cm-s-pastel-on-dark span.cm-atom{color:#DE8E30}.cm-s-pastel-on-dark span.cm-number{color:#CCC}.cm-s-pastel-on-dark span.cm-property{color:#8F938F}.cm-s-pastel-on-dark span.cm-attribute{color:#a6e22e}.cm-s-pastel-on-dark span.cm-keyword{color:#AEB2F8}.cm-s-pastel-on-dark span.cm-string{color:#66A968}.cm-s-pastel-on-dark span.cm-variable{color:#AEB2F8}.cm-s-pastel-on-dark span.cm-variable-2{color:#BEBF55}.cm-s-pastel-on-dark span.cm-variable-3{color:#DE8E30}.cm-s-pastel-on-dark span.cm-def{color:#757aD8}.cm-s-pastel-on-dark span.cm-bracket{color:#f8f8f2}.cm-s-pastel-on-dark span.cm-tag{color:#C1C144}.cm-s-pastel-on-dark span.cm-link{color:#ae81ff}.cm-s-pastel-on-dark span.cm-builtin,.cm-s-pastel-on-dark span.cm-qualifier{color:#C1C144}.cm-s-pastel-on-dark span.cm-error{background:#757aD8;color:#f8f8f0}.cm-s-pastel-on-dark .CodeMirror-activeline-background{background:rgba(255,255,255,.031)}.cm-s-pastel-on-dark .CodeMirror-matchingbracket{border:1px solid rgba(255,255,255,.25);color:#8F938F!important;margin:-1px -1px 0}
1
+ .cm-s-pastel-on-dark.CodeMirror{background:#2c2827;color:#8F938F;line-height:1.5}.cm-s-pastel-on-dark .CodeMirror-line::selection,.cm-s-pastel-on-dark .CodeMirror-line>span::selection,.cm-s-pastel-on-dark .CodeMirror-line>span>span::selection,.cm-s-pastel-on-dark div.CodeMirror-selected{background:rgba(221,240,255,.2)}.cm-s-pastel-on-dark .CodeMirror-line::-moz-selection,.cm-s-pastel-on-dark .CodeMirror-line>span::-moz-selection,.cm-s-pastel-on-dark .CodeMirror-line>span>span::-moz-selection{background:rgba(221,240,255,.2)}.cm-s-pastel-on-dark .CodeMirror-gutters{background:#34302f;border-right:0;padding:0 3px}.cm-s-pastel-on-dark .CodeMirror-guttermarker{color:#fff}.cm-s-pastel-on-dark .CodeMirror-guttermarker-subtle,.cm-s-pastel-on-dark .CodeMirror-linenumber{color:#8F938F}.cm-s-pastel-on-dark .CodeMirror-cursor{border-left:1px solid #A7A7A7}.cm-s-pastel-on-dark span.cm-comment{color:#A6C6FF}.cm-s-pastel-on-dark span.cm-atom{color:#DE8E30}.cm-s-pastel-on-dark span.cm-number{color:#CCC}.cm-s-pastel-on-dark span.cm-property{color:#8F938F}.cm-s-pastel-on-dark span.cm-attribute{color:#a6e22e}.cm-s-pastel-on-dark span.cm-keyword{color:#AEB2F8}.cm-s-pastel-on-dark span.cm-string{color:#66A968}.cm-s-pastel-on-dark span.cm-variable{color:#AEB2F8}.cm-s-pastel-on-dark span.cm-variable-2{color:#BEBF55}.cm-s-pastel-on-dark span.cm-variable-3{color:#DE8E30}.cm-s-pastel-on-dark span.cm-def{color:#757aD8}.cm-s-pastel-on-dark span.cm-bracket{color:#f8f8f2}.cm-s-pastel-on-dark span.cm-tag{color:#C1C144}.cm-s-pastel-on-dark span.cm-link{color:#ae81ff}.cm-s-pastel-on-dark span.cm-builtin,.cm-s-pastel-on-dark span.cm-qualifier{color:#C1C144}.cm-s-pastel-on-dark span.cm-error{background:#757aD8;color:#f8f8f0}.cm-s-pastel-on-dark .CodeMirror-activeline-background{background:rgba(255,255,255,.031)}.cm-s-pastel-on-dark .CodeMirror-matchingbracket{border:1px solid rgba(255,255,255,.25);color:#8F938F!important;margin:-1px -1px 0}
js/esites_editor/dist/js/vendor/codemirror/theme/solarized.css CHANGED
@@ -1 +1 @@
1
- .solarized.base03{color:#002b36}.solarized.base02{color:#073642}.solarized.base01{color:#586e75}.solarized.base00{color:#657b83}.solarized.base0{color:#839496}.solarized.base1{color:#93a1a1}.solarized.base2{color:#eee8d5}.solarized.base3{color:#fdf6e3}.solarized.solar-yellow{color:#b58900}.solarized.solar-orange{color:#cb4b16}.solarized.solar-red{color:#dc322f}.solarized.solar-magenta{color:#d33682}.solarized.solar-violet{color:#6c71c4}.solarized.solar-blue{color:#268bd2}.solarized.solar-cyan{color:#2aa198}.solarized.solar-green{color:#859900}.cm-s-solarized{line-height:1.45em;color-profile:sRGB;rendering-intent:auto}.cm-s-solarized.cm-s-dark{color:#839496;background-color:#002b36;text-shadow:#002b36 0 1px}.cm-s-solarized.cm-s-light{background-color:#fdf6e3;color:#657b83;text-shadow:#eee8d5 0 1px}.cm-s-solarized .CodeMirror-widget{text-shadow:none}.cm-s-solarized .cm-header{color:#586e75}.cm-s-solarized .cm-quote{color:#93a1a1}.cm-s-solarized .cm-keyword{color:#cb4b16}.cm-s-solarized .cm-atom,.cm-s-solarized .cm-number{color:#d33682}.cm-s-solarized .cm-def{color:#2aa198}.cm-s-solarized .cm-variable{color:#839496}.cm-s-solarized .cm-variable-2{color:#b58900}.cm-s-solarized .cm-variable-3{color:#6c71c4}.cm-s-solarized .cm-property{color:#2aa198}.cm-s-solarized .cm-operator{color:#6c71c4}.cm-s-solarized .cm-comment{color:#586e75;font-style:italic}.cm-s-solarized .cm-string{color:#859900}.cm-s-solarized .cm-string-2{color:#b58900}.cm-s-solarized .cm-meta{color:#859900}.cm-s-solarized .cm-qualifier{color:#b58900}.cm-s-solarized .cm-builtin{color:#d33682}.cm-s-solarized .cm-bracket{color:#cb4b16}.cm-s-solarized .CodeMirror-matchingbracket{color:#859900}.cm-s-solarized .CodeMirror-nonmatchingbracket{color:#dc322f}.cm-s-solarized .cm-tag{color:#93a1a1}.cm-s-solarized .cm-attribute{color:#2aa198}.cm-s-solarized .cm-hr{color:transparent;border-top:1px solid #586e75;display:block}.cm-s-solarized .cm-link{color:#93a1a1;cursor:pointer}.cm-s-solarized .cm-special{color:#6c71c4}.cm-s-solarized .cm-em{color:#999;text-decoration:underline;text-decoration-style:dotted}.cm-s-solarized .cm-strong{color:#eee}.cm-s-solarized .cm-error,.cm-s-solarized .cm-invalidchar{color:#586e75;border-bottom:1px dotted #dc322f}.cm-s-solarized.cm-s-dark div.CodeMirror-selected{background:#073642}.cm-s-solarized.cm-s-dark.CodeMirror ::selection{background:rgba(7,54,66,.99)}.cm-s-dark .CodeMirror-line>span::-moz-selection,.cm-s-dark .CodeMirror-line>span>span::-moz-selection,.cm-s-solarized.cm-s-dark .CodeMirror-line::-moz-selection{background:rgba(7,54,66,.99)}.cm-s-light .CodeMirror-line>span::selection,.cm-s-light .CodeMirror-line>span>span::selection,.cm-s-solarized.cm-s-light .CodeMirror-line::selection,.cm-s-solarized.cm-s-light div.CodeMirror-selected{background:#eee8d5}.cm-s-ligh .CodeMirror-line>span::-moz-selection,.cm-s-ligh .CodeMirror-line>span>span::-moz-selection,.cm-s-solarized.cm-s-light .CodeMirror-line::-moz-selection{background:#eee8d5}.cm-s-solarized.CodeMirror{-moz-box-shadow:inset 7px 0 12px -6px #000;-webkit-box-shadow:inset 7px 0 12px -6px #000;box-shadow:inset 7px 0 12px -6px #000}.cm-s-solarized .CodeMirror-gutters{border-right:1px solid}.cm-s-solarized.cm-s-dark .CodeMirror-gutters{background-color:#002b36;border-color:#00232c}.cm-s-solarized.cm-s-dark .CodeMirror-linenumber{text-shadow:#021014 0 -1px}.cm-s-solarized.cm-s-light .CodeMirror-gutters{background-color:#fdf6e3;border-color:#eee8d5}.cm-s-solarized .CodeMirror-linenumber{color:#586e75;padding:0 5px}.cm-s-solarized .CodeMirror-guttermarker-subtle{color:#586e75}.cm-s-solarized.cm-s-dark .CodeMirror-guttermarker{color:#ddd}.cm-s-solarized.cm-s-light .CodeMirror-guttermarker{color:#cb4b16}.cm-s-solarized .CodeMirror-gutter .CodeMirror-gutter-text{color:#586e75}.cm-s-solarized .CodeMirror-cursor{border-left:1px solid #819090}.cm-s-solarized.cm-s-dark .CodeMirror-activeline-background{background:rgba(255,255,255,.1)}.cm-s-solarized.cm-s-light .CodeMirror-activeline-background{background:rgba(0,0,0,.1)}
1
+ .solarized.base03{color:#002b36}.solarized.base02{color:#073642}.solarized.base01{color:#586e75}.solarized.base00{color:#657b83}.solarized.base0{color:#839496}.solarized.base1{color:#93a1a1}.solarized.base2{color:#eee8d5}.solarized.base3{color:#fdf6e3}.solarized.solar-yellow{color:#b58900}.solarized.solar-orange{color:#cb4b16}.solarized.solar-red{color:#dc322f}.solarized.solar-magenta{color:#d33682}.solarized.solar-violet{color:#6c71c4}.solarized.solar-blue{color:#268bd2}.solarized.solar-cyan{color:#2aa198}.solarized.solar-green{color:#859900}.cm-s-solarized{line-height:1.45em;color-profile:sRGB;rendering-intent:auto}.cm-s-solarized.cm-s-dark{color:#839496;background-color:#002b36;text-shadow:#002b36 0 1px}.cm-s-solarized.cm-s-light{background-color:#fdf6e3;color:#657b83;text-shadow:#eee8d5 0 1px}.cm-s-solarized .CodeMirror-widget{text-shadow:none}.cm-s-solarized .cm-header{color:#586e75}.cm-s-solarized .cm-quote{color:#93a1a1}.cm-s-solarized .cm-keyword{color:#cb4b16}.cm-s-solarized .cm-atom,.cm-s-solarized .cm-number{color:#d33682}.cm-s-solarized .cm-def{color:#2aa198}.cm-s-solarized .cm-variable{color:#839496}.cm-s-solarized .cm-variable-2{color:#b58900}.cm-s-solarized .cm-variable-3{color:#6c71c4}.cm-s-solarized .cm-property{color:#2aa198}.cm-s-solarized .cm-operator{color:#6c71c4}.cm-s-solarized .cm-comment{color:#586e75;font-style:italic}.cm-s-solarized .cm-string{color:#859900}.cm-s-solarized .cm-string-2{color:#b58900}.cm-s-solarized .cm-meta{color:#859900}.cm-s-solarized .cm-qualifier{color:#b58900}.cm-s-solarized .cm-builtin{color:#d33682}.cm-s-solarized .cm-bracket{color:#cb4b16}.cm-s-solarized .CodeMirror-matchingbracket{color:#859900}.cm-s-solarized .CodeMirror-nonmatchingbracket{color:#dc322f}.cm-s-solarized .cm-tag{color:#93a1a1}.cm-s-solarized .cm-attribute{color:#2aa198}.cm-s-solarized .cm-hr{color:transparent;border-top:1px solid #586e75;display:block}.cm-s-solarized .cm-link{color:#93a1a1;cursor:pointer}.cm-s-solarized .cm-special{color:#6c71c4}.cm-s-solarized .cm-em{color:#999;text-decoration:underline;text-decoration-style:dotted}.cm-s-solarized .cm-strong{color:#eee}.cm-s-solarized .cm-error,.cm-s-solarized .cm-invalidchar{color:#586e75;border-bottom:1px dotted #dc322f}.cm-s-solarized.cm-s-dark div.CodeMirror-selected{background:#073642}.cm-s-solarized.cm-s-dark.CodeMirror ::selection{background:rgba(7,54,66,.99)}.cm-s-dark .CodeMirror-line>span::-moz-selection,.cm-s-dark .CodeMirror-line>span>span::-moz-selection,.cm-s-solarized.cm-s-dark .CodeMirror-line::-moz-selection{background:rgba(7,54,66,.99)}.cm-s-light .CodeMirror-line>span::selection,.cm-s-light .CodeMirror-line>span>span::selection,.cm-s-solarized.cm-s-light .CodeMirror-line::selection,.cm-s-solarized.cm-s-light div.CodeMirror-selected{background:#eee8d5}.cm-s-ligh .CodeMirror-line>span::-moz-selection,.cm-s-ligh .CodeMirror-line>span>span::-moz-selection,.cm-s-solarized.cm-s-light .CodeMirror-line::-moz-selection{background:#eee8d5}.cm-s-solarized.CodeMirror{-moz-box-shadow:inset 7px 0 12px -6px #000;-webkit-box-shadow:inset 7px 0 12px -6px #000;box-shadow:inset 7px 0 12px -6px #000}.cm-s-solarized .CodeMirror-gutters{border-right:0}.cm-s-solarized.cm-s-dark .CodeMirror-gutters{background-color:#073642}.cm-s-solarized.cm-s-dark .CodeMirror-linenumber{color:#586e75;text-shadow:#021014 0 -1px}.cm-s-solarized.cm-s-light .CodeMirror-gutters{background-color:#eee8d5}.cm-s-solarized.cm-s-light .CodeMirror-linenumber{color:#839496}.cm-s-solarized .CodeMirror-linenumber{padding:0 5px}.cm-s-solarized .CodeMirror-guttermarker-subtle{color:#586e75}.cm-s-solarized.cm-s-dark .CodeMirror-guttermarker{color:#ddd}.cm-s-solarized.cm-s-light .CodeMirror-guttermarker{color:#cb4b16}.cm-s-solarized .CodeMirror-gutter .CodeMirror-gutter-text{color:#586e75}.cm-s-solarized .CodeMirror-cursor{border-left:1px solid #819090}.cm-s-solarized.cm-s-light.cm-fat-cursor .CodeMirror-cursor{background:#7e7}.cm-s-solarized.cm-s-light .cm-animate-fat-cursor{background-color:#7e7}.cm-s-solarized.cm-s-dark.cm-fat-cursor .CodeMirror-cursor{background:#586e75}.cm-s-solarized.cm-s-dark .cm-animate-fat-cursor{background-color:#586e75}.cm-s-solarized.cm-s-dark .CodeMirror-activeline-background{background:rgba(255,255,255,.06)}.cm-s-solarized.cm-s-light .CodeMirror-activeline-background{background:rgba(0,0,0,.06)}
js/esites_editor/dist/js/vendor/emmet-codemirror/dist/emmet.js CHANGED
@@ -1,6 +1,6 @@
1
- !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var o;"undefined"!=typeof window?o=window:"undefined"!=typeof global?o=global:"undefined"!=typeof self&&(o=self),o.emmetCodeMirror=e()}}(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){"use strict";function posToIndex(cm,pos){arguments.length>2&&"object"!=typeof pos&&(pos={line:arguments[1],ch:arguments[2]});return cm.indexFromPos(pos)}function indexToPos(cm,ix){return cm.posFromIndex(ix)}var _interopRequire=function(obj){return obj&&obj.__esModule?obj["default"]:obj},_createClass=function(){function defineProperties(target,props){for(var key in props){var prop=props[key];prop.configurable=!0;prop.value&&(prop.writable=!0)}Object.defineProperties(target,props)}return function(Constructor,protoProps,staticProps){protoProps&&defineProperties(Constructor.prototype,protoProps);staticProps&&defineProperties(Constructor,staticProps);return Constructor}}(),_classCallCheck=function(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")};Object.defineProperty(exports,"__esModule",{value:!0});var emmet=_interopRequire(require("./emmet")),modeMap={"text/html":"html","application/xml":"xml","text/xsl":"xsl","text/css":"css","text/x-less":"less","text/x-scss":"scss","text/x-sass":"sass"};exports.modeMap=modeMap;var EmmetEditor=function(){function EmmetEditor(ctx){var selIndex=void 0===arguments[1]?0:arguments[1];_classCallCheck(this,EmmetEditor);this.context=ctx;this.selectionIndex=selIndex||0}_createClass(EmmetEditor,{selectionList:{value:function(){var cm=this.context;return cm.listSelections().map(function(sel){var anchor=posToIndex(cm,sel.anchor),head=posToIndex(cm,sel.head);return{start:Math.min(anchor,head),end:Math.max(anchor,head)}})}},getCaretPos:{value:function(){return this.getSelectionRange().start}},setCaretPos:{value:function(pos){this.createSelection(pos)}},getSelectionRange:{value:function(){return this.selectionList()[this.selectionIndex]}},createSelection:{value:function(start,end){"undefined"==typeof end&&(end=start);var sels=this.selectionList(),cm=this.context;sels[this.selectionIndex]={start:start,end:end};this.context.setSelections(sels.map(function(sel){return{head:indexToPos(cm,sel.start),anchor:indexToPos(cm,sel.end)}}))}},getSelection:{value:function(){var sel=this.getSelectionRange();sel.start=indexToPos(this.context,sel.start);sel.end=indexToPos(this.context,sel.end);return this.context.getRange(sel.start,sel.end)}},getCurrentLineRange:{value:function(){var caret=indexToPos(this.context,this.getCaretPos());return{start:posToIndex(this.context,caret.line,0),end:posToIndex(this.context,caret.line,this.context.getLine(caret.line).length)}}},getCurrentLine:{value:function(){var caret=indexToPos(this.context,this.getCaretPos());return this.context.getLine(caret.line)||""}},replaceContent:{value:function(value,start,end,noIndent){"undefined"==typeof end&&(end="undefined"==typeof start?this.getContent().length:start);"undefined"==typeof start&&(start=0);value=this.normalize(value);noIndent||(value=emmet.utils.common.padString(value,emmet.utils.common.getLinePaddingFromPosition(this.getContent(),start)));var tabstopData=emmet.tabStops.extract(value,{escape:function(ch){return ch}});value=tabstopData.text;var firstTabStop=tabstopData.tabstops[0]||{start:value.length,end:value.length};firstTabStop.start+=start;firstTabStop.end+=start;this.context.replaceRange(value,indexToPos(this.context,start),indexToPos(this.context,end));this.createSelection(firstTabStop.start,firstTabStop.end)}},normalize:{value:function(str){var indent=" ",ctx=this.context;ctx.getOption("indentWithTabs")||(indent=emmet.utils.common.repeatString(" ",ctx.getOption("indentUnit")));return emmet.utils.editor.normalize(str,{indentation:indent})}},getContent:{value:function(){return this.context.getValue()}},getSyntax:{value:function(){var editor=this.context,mode=(editor.posFromIndex(this.getCaretPos()),editor.getModeAt(editor.getCursor())),syntax=mode.name;"xml"===syntax&&mode.configuration&&(syntax=mode.configuration);return syntax||emmet.utils.action.detectSyntax(this,syntax)}},getProfileName:{value:function(){return this.context.getOption("profile")?this.context.getOption("profile"):emmet.utils.action.detectProfile(this)}},prompt:{value:function(_prompt){var _promptWrapper=function(_x){return _prompt.apply(this,arguments)};_promptWrapper.toString=function(){return _prompt.toString()};return _promptWrapper}(function(title){return prompt(title)})},getFilePath:{value:function(){return location.href}},isValidSyntax:{value:function(){return emmet.resources.hasSyntax(this.getSyntax())}}});return EmmetEditor}();exports["default"]=EmmetEditor},{"./emmet":2}],2:[function(require,module,exports){"use strict";var _interopRequire=function(obj){return obj&&obj.__esModule?obj["default"]:obj},emmet=_interopRequire(require("emmet"));require("emmet/bundles/snippets");require("emmet/bundles/caniuse");module.exports=emmet},{emmet:39,"emmet/bundles/caniuse":3,"emmet/bundles/snippets":4}],3:[function(require,module,exports){var ciu=require("../lib/assets/caniuse"),db=require("../lib/caniuse.json");ciu.load(db,!0)},{"../lib/assets/caniuse":23,"../lib/caniuse.json":35}],4:[function(require,module,exports){var res=require("../lib/assets/resources"),snippets=require("../lib/snippets.json");res.setVocabulary(snippets,"system")},{"../lib/assets/resources":31,"../lib/snippets.json":68}],5:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function last(arr){return arr[arr.length-1]}function balanceHTML(editor,direction){var info=editorUtils.outputInfo(editor),content=info.content,sel=range(editor.getSelectionRange());lastMatch&&!lastMatch.range.equal(sel)&&(lastMatch=null);if(lastMatch&&sel.length())if("in"==direction){if("tag"==lastMatch.type&&!lastMatch.close)return!1;if(lastMatch.range.equal(lastMatch.outerRange))lastMatch.range=lastMatch.innerRange;else{var narrowed=utils.narrowToNonSpace(content,lastMatch.innerRange);lastMatch=htmlMatcher.find(content,narrowed.start+1);lastMatch&&lastMatch.range.equal(sel)&&lastMatch.outerRange.equal(sel)&&(lastMatch.range=lastMatch.innerRange)}}else if(!lastMatch.innerRange.equal(lastMatch.outerRange)&&lastMatch.range.equal(lastMatch.innerRange)&&sel.equal(lastMatch.range))lastMatch.range=lastMatch.outerRange;else{lastMatch=htmlMatcher.find(content,sel.start);lastMatch&&lastMatch.range.equal(sel)&&lastMatch.innerRange.equal(sel)&&(lastMatch.range=lastMatch.outerRange)}else lastMatch=htmlMatcher.find(content,sel.start);if(lastMatch){lastMatch.innerRange.equal(sel)&&(lastMatch.range=lastMatch.outerRange);if(!lastMatch.range.equal(sel)){editor.createSelection(lastMatch.range.start,lastMatch.range.end);return!0}}lastMatch=null;return!1}function rangesForCSSRule(rule,pos){var ranges=[rule.range(!0)];ranges.push(rule.valueRange(!0));var nestedSections=cssSections.nestedSectionsInRule(rule),items=rule.list();if(items.length||nestedSections.length){var start=Number.POSITIVE_INFINITY,end=-1;if(items.length){start=items[0].namePosition(!0);end=last(items).range(!0).end}if(nestedSections.length){nestedSections[0].start<start&&(start=nestedSections[0].start);last(nestedSections).end>end&&(end=last(nestedSections).end)}ranges.push(range.create2(start,end))}ranges=ranges.concat(nestedSections);var prop=cssEditTree.propertyFromPosition(rule,pos)||items[0];if(prop){ranges.push(prop.range(!0));var valueRange=prop.valueRange(!0);prop.end()||(valueRange._unterminated=!0);ranges.push(valueRange)}return ranges}function getCSSRanges(content,pos){var rule;if("string"==typeof content){var ruleRange=cssSections.matchEnclosingRule(content,pos);ruleRange&&(rule=cssEditTree.parse(ruleRange.substring(content),{offset:ruleRange.start}))}else rule=content;if(!rule)return null;var ranges=rangesForCSSRule(rule,pos);ranges=ranges.filter(function(item){return!!item.length});return utils.unique(ranges,function(item){return item.valueOf()})}function balanceCSS(editor,direction){var info=editorUtils.outputInfo(editor),content=info.content,sel=range(editor.getSelectionRange()),ranges=getCSSRanges(info.content,sel.start);if(!ranges&&sel.length())try{var rule=cssEditTree.parse(sel.substring(info.content),{offset:sel.start});ranges=getCSSRanges(rule,sel.start)}catch(e){}if(!ranges)return!1;ranges=range.sort(ranges,!0);var bestMatch=utils.find(ranges,function(r){return r.equal(sel)});bestMatch||(bestMatch=utils.find(ranges,function(r){return r._unterminated?r.include(sel.start):r.inside(sel.start)}));if(!bestMatch)return!1;var bestMatchIx=ranges.indexOf(bestMatch);bestMatch.equal(sel)&&(bestMatchIx+="out"==direction?1:-1);if(0>bestMatchIx||bestMatchIx>=ranges.length)if(bestMatchIx>=ranges.length&&"out"==direction){pos=bestMatch.start-1;var outerRanges=getCSSRanges(content,pos);outerRanges&&(bestMatch=last(outerRanges.filter(function(r){return r.inside(pos)})))}else bestMatch=null;else bestMatch=ranges[bestMatchIx];if(bestMatch){editor.createSelection(bestMatch.start,bestMatch.end);return!0}return!1}var htmlMatcher=require("../assets/htmlMatcher"),utils=require("../utils/common"),editorUtils=require("../utils/editor"),actionUtils=require("../utils/action"),range=require("../assets/range"),cssEditTree=require("../editTree/css"),cssSections=require("../utils/cssSections"),lastMatch=null;return{balance:function(editor,direction){direction=String((direction||"out").toLowerCase());var info=editorUtils.outputInfo(editor);return actionUtils.isSupportedCSS(info.syntax)?balanceCSS(editor,direction):balanceHTML(editor,direction)},balanceInwardAction:function(editor){return this.balance(editor,"in")},balanceOutwardAction:function(editor){return this.balance(editor,"out")},goToMatchingPairAction:function(editor){var content=String(editor.getContent()),caretPos=editor.getCaretPos();"<"==content.charAt(caretPos)&&caretPos++;var tag=htmlMatcher.tag(content,caretPos);if(tag&&tag.close){tag.open.range.inside(caretPos)?editor.setCaretPos(tag.close.range.start):editor.setCaretPos(tag.open.range.start);return!0}return!1}}})},{"../assets/htmlMatcher":26,"../assets/range":30,"../editTree/css":37,"../utils/action":70,"../utils/common":73,"../utils/cssSections":74,"../utils/editor":75}],6:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function startsWith(token,text,pos){pos=pos||0;return text.charAt(pos)==token.charAt(0)&&text.substr(pos,token.length)==token}function encodeToBase64(editor,imgPath,pos){var editorFile=editor.getFilePath(),defaultMimeType="application/octet-stream";if(null===editorFile)throw"You should save your file before using this action";var realImgPath=file.locateFile(editorFile,imgPath);if(null===realImgPath)throw"Can't find "+imgPath+" file";file.read(realImgPath,function(err,content){if(err)throw"Unable to read "+realImgPath+": "+err;var b64=base64.encode(String(content));if(!b64)throw"Can't encode file content to base64";b64="data:"+(actionUtils.mimeTypes[String(file.getExt(realImgPath))]||defaultMimeType)+";base64,"+b64;editor.replaceContent("$0"+b64,pos,pos+imgPath.length)});return!0}function decodeFromBase64(editor,data,pos){var filePath=String(editor.prompt("Enter path to file (absolute or relative)"));if(!filePath)return!1;var absPath=file.createPath(editor.getFilePath(),filePath);if(!absPath)throw"Can't save file";file.save(absPath,base64.decode(data.replace(/^data\:.+?;.+?,/,"")));editor.replaceContent("$0"+filePath,pos,pos+data.length);return!0}var file=require("../plugin/file"),base64=require("../utils/base64"),actionUtils=require("../utils/action"),editorUtils=require("../utils/editor");return{encodeDecodeDataUrlAction:function(editor){var data=String(editor.getSelection()),caretPos=editor.getCaretPos(),info=editorUtils.outputInfo(editor);if(!data)for(var m,text=info.content;caretPos-->=0;){if(startsWith("src=",text,caretPos)){if(m=text.substr(caretPos).match(/^(src=(["'])?)([^'"<>\s]+)\1?/)){data=m[3];caretPos+=m[1].length}break}if(startsWith("url(",text,caretPos)){if(m=text.substr(caretPos).match(/^(url\((['"])?)([^'"\)\s]+)\1?/)){data=m[3];caretPos+=m[1].length}break}}return data?startsWith("data:",data)?decodeFromBase64(editor,data,caretPos):encodeToBase64(editor,data,caretPos):!1}}})},{"../plugin/file":63,"../utils/action":70,"../utils/base64":71,"../utils/editor":75}],7:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function findNewEditPoint(editor,inc,offset){function getLine(ix){for(var start=ix;start>=0;){var c=content.charAt(start);if("\n"==c||"\r"==c)break;start--}return content.substring(start,ix)}inc=inc||1;offset=offset||0;for(var curPoint=editor.getCaretPos()+offset,content=String(editor.getContent()),maxLen=content.length,nextPoint=-1,reEmptyLine=/^\s+$/;maxLen>=curPoint&&curPoint>=0;){curPoint+=inc;var curChar=content.charAt(curPoint),nextChar=content.charAt(curPoint+1),prevChar=content.charAt(curPoint-1);switch(curChar){case'"':case"'":nextChar==curChar&&"="==prevChar&&(nextPoint=curPoint+1);break;case">":"<"==nextChar&&(nextPoint=curPoint+1);break;case"\n":case"\r":reEmptyLine.test(getLine(curPoint-1))&&(nextPoint=curPoint)}if(-1!=nextPoint)break}return nextPoint}return{previousEditPointAction:function(editor,syntax,profile){var curPos=editor.getCaretPos(),newPoint=findNewEditPoint(editor,-1);newPoint==curPos&&(newPoint=findNewEditPoint(editor,-1,-2));if(-1!=newPoint){editor.setCaretPos(newPoint);return!0}return!1},nextEditPointAction:function(editor,syntax,profile){var newPoint=findNewEditPoint(editor,1);if(-1!=newPoint){editor.setCaretPos(newPoint);return!0}return!1}}})},{}],8:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){var actionUtils=require("../utils/action"),utils=require("../utils/common"),math=require("../utils/math"),range=require("../assets/range");return{evaluateMathAction:function(editor){var content=editor.getContent(),chars=".+-*/\\",sel=range(editor.getSelectionRange());sel.length()||(sel=actionUtils.findExpressionBounds(editor,function(ch){return utils.isNumeric(ch)||-1!=chars.indexOf(ch)}));if(sel&&sel.length()){var expr=sel.substring(content);expr=expr.replace(/([\d\.\-]+)\\([\d\.\-]+)/g,"round($1/$2)");try{var result=utils.prettifyNumber(math.evaluate(expr));editor.replaceContent(result,sel.start,sel.end);editor.setCaretPos(sel.start+result.length);return!0}catch(e){}}return!1}}})},{"../assets/range":30,"../utils/action":70,"../utils/common":73,"../utils/math":76}],9:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function findAbbreviation(editor){var r=range(editor.getSelectionRange()),content=String(editor.getContent());if(r.length())return r.substring(content);var curLine=editor.getCurrentLineRange();return actionUtils.extractAbbreviation(content.substring(curLine.start,r.start))}var handlerList=require("../assets/handlerList"),range=require("../assets/range"),prefs=require("../assets/preferences"),utils=require("../utils/common"),editorUtils=require("../utils/editor"),actionUtils=require("../utils/action"),cssGradient=require("../resolver/cssGradient"),parser=require("../parser/abbreviation"),handlers=handlerList.create();handlers.add(function(editor,syntax,profile){var caretPos=editor.getSelectionRange().end,abbr=findAbbreviation(editor);if(abbr){var content=parser.expand(abbr,{syntax:syntax,profile:profile,contextNode:actionUtils.captureContext(editor)});if(content){var replaceFrom=caretPos-abbr.length,replaceTo=caretPos,cssSyntaxes=prefs.getArray("css.syntaxes");if(cssSyntaxes&&~cssSyntaxes.indexOf(syntax)){var curContent=editor.getContent();";"==curContent.charAt(caretPos)&&";"==content.charAt(content.length-1)&&replaceTo++}editor.replaceContent(content,replaceFrom,replaceTo);return!0}}return!1},{order:-1});handlers.add(cssGradient.expandAbbreviationHandler.bind(cssGradient));return{expandAbbreviationAction:function(editor,syntax,profile){var args=utils.toArray(arguments),info=editorUtils.outputInfo(editor,syntax,profile);args[1]=info.syntax;args[2]=info.profile;return handlers.exec(!1,args)},expandAbbreviationWithTabAction:function(editor,syntax,profile){var sel=editor.getSelection(),indent=" ";if(sel){var selRange=range(editor.getSelectionRange()),content=utils.padString(sel,indent);editor.replaceContent(indent+"${0}",editor.getCaretPos());var replaceRange=range(editor.getCaretPos(),selRange.length());editor.replaceContent(content,replaceRange.start,replaceRange.end,!0);editor.createSelection(replaceRange.start,replaceRange.start+content.length);return!0}this.expandAbbreviationAction(editor,syntax,profile)||editor.replaceContent(indent,editor.getCaretPos());return!0},_defaultHandler:function(editor,syntax,profile){var caretPos=editor.getSelectionRange().end,abbr=this.findAbbreviation(editor);if(abbr){var ctx=actionUtils.captureContext(editor),content=parser.expand(abbr,syntax,profile,ctx);if(content){editor.replaceContent(content,caretPos-abbr.length,caretPos);return!0}}return!1},addHandler:function(fn,options){handlers.add(fn,options)},removeHandler:function(fn){handlers.remove(fn)},findAbbreviation:findAbbreviation}})},{"../assets/handlerList":25,"../assets/preferences":28,"../assets/range":30,"../parser/abbreviation":55,"../resolver/cssGradient":65,"../utils/action":70,"../utils/common":73,"../utils/editor":75}],10:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function intLength(num){num=num.replace(/^\-/,"");return~num.indexOf(".")?num.split(".")[0].length:num.length}var utils=require("../utils/common"),actionUtils=require("../utils/action");return{increment01Action:function(editor){return this.incrementNumber(editor,.1)},increment1Action:function(editor){return this.incrementNumber(editor,1)},increment10Action:function(editor){return this.incrementNumber(editor,10)},decrement01Action:function(editor){return this.incrementNumber(editor,-.1)},decrement1Action:function(editor){return this.incrementNumber(editor,-1)},decrement10Action:function(editor){return this.incrementNumber(editor,-10)},incrementNumber:function(editor,step){var hasSign=!1,hasDecimal=!1,r=actionUtils.findExpressionBounds(editor,function(ch,pos,content){return utils.isNumeric(ch)?!0:"."==ch?utils.isNumeric(content.charAt(pos+1))?hasDecimal?!1:hasDecimal=!0:!1:"-"==ch?hasSign?!1:hasSign=!0:!1});if(r&&r.length()){var strNum=r.substring(String(editor.getContent())),num=parseFloat(strNum);if(!isNaN(num)){num=utils.prettifyNumber(num+step);if(/^(\-?)0+[1-9]/.test(strNum)){var minus="";if(RegExp.$1){minus="-";num=num.substring(1)}var parts=num.split(".");parts[0]=utils.zeroPadString(parts[0],intLength(strNum));num=minus+parts.join(".")}editor.replaceContent(num,r.start,r.end);editor.createSelection(r.start,r.start+num.length);return!0}}return!1}}})},{"../utils/action":70,"../utils/common":73}],11:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){var prefs=require("../assets/preferences"),utils=require("../utils/common"),htmlMatcher=(require("../assets/resources"),require("../assets/htmlMatcher")),editorUtils=require("../utils/editor"),xmlSyntaxes=["html","xml","xsl"];prefs.define("css.closeBraceIndentation","\n","Indentation before closing brace of CSS rule. Some users prefere indented closing brace of CSS rule for better readability. This preference’s value will be automatically inserted before closing brace when user adds newline in newly created CSS rule (e.g. when “Insert formatted linebreak” action will be performed in CSS file). If you’re such user, you may want to write put a value like <code>\\n\\t</code> in this preference.");return{insertLineBreakAction:function(editor){if(!this.insertLineBreakOnlyAction(editor)){for(var ch,curPadding=editorUtils.getCurrentLinePadding(editor),content=String(editor.getContent()),caretPos=editor.getCaretPos(),len=content.length,nl="\n",lineRange=editor.getCurrentLineRange(),nextPadding="",i=lineRange.end+1;len>i;i++){ch=content.charAt(i);if(" "!=ch&&" "!=ch)break;nextPadding+=ch}nextPadding.length>curPadding.length?editor.replaceContent(nl+nextPadding,caretPos,caretPos,!0):editor.replaceContent(nl,caretPos)}return!0},insertLineBreakOnlyAction:function(editor){var info=editorUtils.outputInfo(editor),caretPos=editor.getCaretPos(),nl="\n",pad=" ";if(~xmlSyntaxes.indexOf(info.syntax)){var tag=htmlMatcher.tag(info.content,caretPos);if(tag&&!tag.innerRange.length()){editor.replaceContent(nl+pad+utils.getCaretPlaceholder()+nl,caretPos);return!0}}else if("css"==info.syntax){var content=info.content;if(caretPos&&"{"==content.charAt(caretPos-1)){var append=prefs.get("css.closeBraceIndentation"),hasCloseBrace="}"==content.charAt(caretPos);if(!hasCloseBrace)for(var ch,i=caretPos,il=content.length;il>i;i++){ch=content.charAt(i);if("{"==ch)break;if("}"==ch){append="";hasCloseBrace=!0;break}}hasCloseBrace||(append+="}");var insValue=nl+pad+utils.getCaretPlaceholder()+append;editor.replaceContent(insValue,caretPos);return!0}}return!1}}})},{"../assets/htmlMatcher":26,"../assets/preferences":28,"../assets/resources":31,"../utils/common":73,"../utils/editor":75}],12:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function addAction(name,fn,options){name=name.toLowerCase();options=options||{};"string"==typeof options&&(options={label:options});options.label||(options.label=humanizeActionName(name));actions[name]={name:name,fn:fn,options:options}}function humanizeActionName(name){return utils.trim(name.charAt(0).toUpperCase()+name.substring(1).replace(/_[a-z]/g,function(str){return" "+str.charAt(1).toUpperCase()}))}var utils=require("../utils/common"),actions={},actionModules={base64:require("./base64"),editPoints:require("./editPoints"),evaluateMath:require("./evaluateMath"),expandAbbreviation:require("./expandAbbreviation"),incrementDecrement:require("./incrementDecrement"),lineBreaks:require("./lineBreaks"),balance:require("./balance"),mergeLines:require("./mergeLines"),reflectCSSValue:require("./reflectCSSValue"),removeTag:require("./removeTag"),selectItem:require("./selectItem"),selectLine:require("./selectLine"),splitJoinTag:require("./splitJoinTag"),toggleComment:require("./toggleComment"),updateImageSize:require("./updateImageSize"),wrapWithAbbreviation:require("./wrapWithAbbreviation"),updateTag:require("./updateTag")},bind=function(name,method){var m=actionModules[name];return m[method].bind(m)};addAction("encode_decode_data_url",bind("base64","encodeDecodeDataUrlAction"),"Encode\\Decode data:URL image");addAction("prev_edit_point",bind("editPoints","previousEditPointAction"),"Previous Edit Point");addAction("next_edit_point",bind("editPoints","nextEditPointAction"),"Next Edit Point");addAction("evaluate_math_expression",bind("evaluateMath","evaluateMathAction"),"Numbers/Evaluate Math Expression");addAction("expand_abbreviation_with_tab",bind("expandAbbreviation","expandAbbreviationWithTabAction"),{hidden:!0});addAction("expand_abbreviation",bind("expandAbbreviation","expandAbbreviationAction"),"Expand Abbreviation");addAction("insert_formatted_line_break_only",bind("lineBreaks","insertLineBreakOnlyAction"),{hidden:!0});addAction("insert_formatted_line_break",bind("lineBreaks","insertLineBreakAction"),{hidden:!0});addAction("balance_inward",bind("balance","balanceInwardAction"),"Balance (inward)");addAction("balance_outward",bind("balance","balanceOutwardAction"),"Balance (outward)");addAction("matching_pair",bind("balance","goToMatchingPairAction"),"HTML/Go To Matching Tag Pair");addAction("merge_lines",bind("mergeLines","mergeLinesAction"),"Merge Lines");addAction("reflect_css_value",bind("reflectCSSValue","reflectCSSValueAction"),"CSS/Reflect Value");addAction("remove_tag",bind("removeTag","removeTagAction"),"HTML/Remove Tag");addAction("select_next_item",bind("selectItem","selectNextItemAction"),"Select Next Item");addAction("select_previous_item",bind("selectItem","selectPreviousItemAction"),"Select Previous Item");addAction("split_join_tag",bind("splitJoinTag","splitJoinTagAction"),"HTML/Split\\Join Tag Declaration");addAction("toggle_comment",bind("toggleComment","toggleCommentAction"),"Toggle Comment");addAction("update_image_size",bind("updateImageSize","updateImageSizeAction"),"Update Image Size");addAction("wrap_with_abbreviation",bind("wrapWithAbbreviation","wrapWithAbbreviationAction"),"Wrap With Abbreviation");addAction("update_tag",bind("updateTag","updateTagAction"),"HTML/Update Tag");[1,-1,10,-10,.1,-.1].forEach(function(num){var prefix=num>0?"increment":"decrement",suffix=String(Math.abs(num)).replace(".","").substring(0,2),actionId=prefix+"_number_by_"+suffix,actionMethod=prefix+suffix+"Action",actionLabel="Numbers/"+prefix.charAt(0).toUpperCase()+prefix.substring(1)+" number by "+Math.abs(num);addAction(actionId,bind("incrementDecrement",actionMethod),actionLabel)});return{add:addAction,get:function(name){return actions[name.toLowerCase()]},run:function(name,args){Array.isArray(args)||(args=utils.toArray(arguments,1));var action=this.get(name);if(!action)throw new Error('Action "'+name+'" is not defined');return action.fn.apply(action,args)},getAll:function(){return actions},getList:function(){var all=this.getAll();return Object.keys(all).map(function(key){return all[key]})},getMenu:function(skipActions){var result=[];skipActions=skipActions||[];this.getList().forEach(function(action){if(!action.options.hidden&&!~skipActions.indexOf(action.name)){var actionName=humanizeActionName(action.name),ctx=result;if(action.options.label){var parts=action.options.label.split("/");actionName=parts.pop();for(var menuName,submenu;menuName=parts.shift();){submenu=utils.find(ctx,function(item){return"submenu"==item.type&&item.name==menuName});if(!submenu){submenu={name:menuName,type:"submenu",items:[]};ctx.push(submenu)}ctx=submenu.items}}ctx.push({type:"action",name:action.name,label:actionName})}});return result},getActionNameForMenuTitle:function(title,menu){return utils.find(menu||this.getMenu(),function(val){return"action"!=val.type?this.getActionNameForMenuTitle(title,val.items):val.label==title||val.name==title?val.name:void 0},this)}}})},{"../utils/common":73,"./balance":5,"./base64":6,"./editPoints":7,"./evaluateMath":8,"./expandAbbreviation":9,"./incrementDecrement":10,"./lineBreaks":11,"./mergeLines":13,"./reflectCSSValue":14,"./removeTag":15,"./selectItem":16,"./selectLine":17,"./splitJoinTag":18,"./toggleComment":19,"./updateImageSize":20,"./updateTag":21,"./wrapWithAbbreviation":22}],13:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){var htmlMatcher=require("../assets/htmlMatcher"),utils=require("../utils/common"),editorUtils=require("../utils/editor"),range=require("../assets/range");return{mergeLinesAction:function(editor){var info=editorUtils.outputInfo(editor),selection=range(editor.getSelectionRange());if(!selection.length()){var pair=htmlMatcher.find(info.content,editor.getCaretPos());pair&&(selection=pair.outerRange)}if(selection.length()){for(var text=selection.substring(info.content),lines=utils.splitByLines(text),i=1;i<lines.length;i++)lines[i]=lines[i].replace(/^\s+/,"");text=lines.join("").replace(/\s{2,}/," ");var textLen=text.length;text=utils.escapeText(text);editor.replaceContent(text,selection.start,selection.end);editor.createSelection(selection.start,selection.start+textLen);return!0}return!1}}})},{"../assets/htmlMatcher":26,"../assets/range":30,"../utils/common":73,"../utils/editor":75}],14:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function doCSSReflection(editor){var outputInfo=editorUtils.outputInfo(editor),caretPos=editor.getCaretPos(),cssRule=cssEditTree.parseFromPosition(outputInfo.content,caretPos);if(cssRule){var property=cssRule.itemFromPosition(caretPos,!0);if(property){var oldRule=cssRule.source,offset=cssRule.options.offset,caretDelta=caretPos-offset-property.range().start;handlers.exec(!1,[property]);return oldRule!==cssRule.source?{data:cssRule.source,start:offset,end:offset+oldRule.length,caret:offset+property.range().start+caretDelta}:void 0}}}function getReflectedCSSName(name){name=cssEditTree.baseName(name);var m,vendorPrefix="^(?:\\-\\w+\\-)?";return"opacity"!=name&&"filter"!=name||!prefs.get("css.reflect.oldIEOpacity")?(m=name.match(/^border-radius-(top|bottom)(left|right)/))?new RegExp(vendorPrefix+"(?:"+name+"|border-"+m[1]+"-"+m[2]+"-radius)$"):(m=name.match(/^border-(top|bottom)-(left|right)-radius/))?new RegExp(vendorPrefix+"(?:"+name+"|border-radius-"+m[1]+m[2]+")$"):new RegExp(vendorPrefix+name+"$"):new RegExp(vendorPrefix+"(?:opacity|filter)$")}function reflectValueParts(name,value){var reVendor=/^\-(\w+)\-/,propPrefix=reVendor.test(name)?RegExp.$1.toLowerCase():"",parts=cssEditTree.findParts(value);parts.reverse();parts.forEach(function(part){var partValue=part.substring(value).replace(reVendor,""),prefixes=cssResolver.vendorPrefixes(partValue);if(prefixes){propPrefix&&~prefixes.indexOf(propPrefix)&&(partValue="-"+propPrefix+"-"+partValue);value=utils.replaceSubstring(value,partValue,part)}});return value}function reflectValue(donor,receiver){var value=getReflectedValue(donor.name(),donor.value(),receiver.name(),receiver.value());value=reflectValueParts(receiver.name(),value);receiver.value(value)}function getReflectedValue(curName,curValue,refName,refValue){curName=cssEditTree.baseName(curName);refName=cssEditTree.baseName(refName);if("opacity"==curName&&"filter"==refName)return refValue.replace(/opacity=[^)]*/i,"opacity="+Math.floor(100*parseFloat(curValue)));if("filter"==curName&&"opacity"==refName){var m=curValue.match(/opacity=([^)]*)/i);return m?utils.prettifyNumber(parseInt(m[1],10)/100):refValue}return curValue}var handlerList=require("../assets/handlerList"),prefs=require("../assets/preferences"),cssResolver=require("../resolver/css"),cssEditTree=require("../editTree/css"),utils=require("../utils/common"),actionUtils=require("../utils/action"),editorUtils=require("../utils/editor"),cssGradient=require("../resolver/cssGradient");prefs.define("css.reflect.oldIEOpacity",!1,"Support IE6/7/8 opacity notation, e.g. <code>filter:alpha(opacity=...)</code>. Note that CSS3 and SVG also provides <code>filter</code> property so this option is disabled by default.");
2
- var handlers=handlerList.create();module=module||{};module.exports={reflectCSSValueAction:function(editor){return"css"!=editor.getSyntax()?!1:actionUtils.compoundUpdate(editor,doCSSReflection(editor))},_defaultHandler:function(property){var reName=getReflectedCSSName(property.name());property.parent.list().forEach(function(p){reName.test(p.name())&&reflectValue(property,p)})},addHandler:function(fn,options){handlers.add(fn,options)},removeHandler:function(fn){handlers.remove(fn)}};handlers.add(module.exports._defaultHandler.bind(module.exports),{order:-1});handlers.add(cssGradient.reflectValueHandler.bind(cssGradient));return module.exports})},{"../assets/handlerList":25,"../assets/preferences":28,"../editTree/css":37,"../resolver/css":64,"../resolver/cssGradient":65,"../utils/action":70,"../utils/common":73,"../utils/editor":75}],15:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){var utils=require("../utils/common"),editorUtils=require("../utils/editor"),htmlMatcher=require("../assets/htmlMatcher");return{removeTagAction:function(editor){var info=editorUtils.outputInfo(editor),tag=htmlMatcher.tag(info.content,editor.getCaretPos());if(tag){if(tag.close){var tagContentRange=utils.narrowToNonSpace(info.content,tag.innerRange),startLineBounds=utils.findNewlineBounds(info.content,tagContentRange.start),startLinePad=utils.getLinePadding(startLineBounds.substring(info.content)),tagContent=tagContentRange.substring(info.content);tagContent=utils.unindentString(tagContent,startLinePad);editor.replaceContent(utils.getCaretPlaceholder()+utils.escapeText(tagContent),tag.outerRange.start,tag.outerRange.end)}else editor.replaceContent(utils.getCaretPlaceholder(),tag.range.start,tag.range.end);return!0}return!1}}})},{"../assets/htmlMatcher":26,"../utils/common":73,"../utils/editor":75}],16:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function findItem(editor,isBackward,extractFn,rangeFn){for(var itemRange,rng,content=editorUtils.outputInfo(editor).content,contentLength=content.length,prevRange=range(-1,0),sel=range(editor.getSelectionRange()),searchPos=sel.start,loop=1e5;searchPos>=0&&contentLength>searchPos&&--loop>0;){if(itemRange=extractFn(content,searchPos,isBackward)){if(prevRange.equal(itemRange))break;prevRange=itemRange.clone();rng=rangeFn(itemRange.substring(content),itemRange.start,sel.clone());if(rng){editor.createSelection(rng.start,rng.end);return!0}searchPos=isBackward?itemRange.start:itemRange.end-1}searchPos+=isBackward?-1:1}return!1}function findNextHTMLItem(editor){var isFirst=!0;return findItem(editor,!1,function(content,searchPos){if(isFirst){isFirst=!1;return findOpeningTagFromPosition(content,searchPos)}return getOpeningTagFromPosition(content,searchPos)},function(tag,offset,selRange){return getRangeForHTMLItem(tag,offset,selRange,!1)})}function findPrevHTMLItem(editor){return findItem(editor,!0,getOpeningTagFromPosition,function(tag,offset,selRange){return getRangeForHTMLItem(tag,offset,selRange,!0)})}function makePossibleRangesHTML(source,tokens,offset){offset=offset||0;var attrValueRange,tagName,result=[],attrStart=-1,attrName="",attrValue="";tokens.forEach(function(tok){switch(tok.type){case"tag":tagName=source.substring(tok.start,tok.end);/^<[\w\:\-]/.test(tagName)&&result.push(range({start:tok.start+1,end:tok.end}));break;case"attribute":attrStart=tok.start;attrName=source.substring(tok.start,tok.end);break;case"string":result.push(range(attrStart,tok.end-attrStart));attrValueRange=range(tok);attrValue=attrValueRange.substring(source);isQuote(attrValue.charAt(0))&&attrValueRange.start++;isQuote(attrValue.charAt(attrValue.length-1))&&attrValueRange.end--;result.push(attrValueRange);"class"==attrName&&(result=result.concat(classNameRanges(attrValueRange.substring(source),attrValueRange.start)))}});result=result.filter(function(item){if(item.length()){item.shift(offset);return!0}});return utils.unique(result,function(item){return item.toString()})}function classNameRanges(className,offset){offset=offset||0;var result=[],stream=stringStream.create(className);stream.eatSpace();stream.start=stream.pos;for(var ch;ch=stream.next();)if(/[\s\u00a0]/.test(ch)){result.push(range(stream.start+offset,stream.pos-stream.start-1));stream.eatSpace();stream.start=stream.pos}result.push(range(stream.start+offset,stream.pos-stream.start));return result}function getRangeForHTMLItem(tag,offset,selRange,isBackward){var ranges=makePossibleRangesHTML(tag,xmlParser.parse(tag),offset);isBackward&&ranges.reverse();var curRange=utils.find(ranges,function(r){return r.equal(selRange)});if(curRange){var ix=ranges.indexOf(curRange);return ix<ranges.length-1?ranges[ix+1]:null}if(isBackward)return utils.find(ranges,function(r){return r.start<selRange.start});if(!curRange){var matchedRanges=ranges.filter(function(r){return r.inside(selRange.end)});if(matchedRanges.length>1)return matchedRanges[1]}return utils.find(ranges,function(r){return r.end>selRange.end})}function findOpeningTagFromPosition(html,pos){for(var tag;pos>=0;){if(tag=getOpeningTagFromPosition(html,pos))return tag;pos--}return null}function getOpeningTagFromPosition(html,pos){var m;return"<"==html.charAt(pos)&&(m=html.substring(pos,html.length).match(startTag))?range(pos,m[0]):void 0}function isQuote(ch){return'"'==ch||"'"==ch}function findInnerRanges(rule){var ranges=[rule.nameRange(!0)],nestedSections=cssSections.nestedSectionsInRule(rule);nestedSections.forEach(function(section){ranges.push(range.create2(section.start,section._selectorEnd))});rule.list().forEach(function(property){ranges=ranges.concat(makePossibleRangesCSS(property))});ranges=range.sort(ranges);ranges=ranges.filter(function(item){return!!item.length()});return utils.unique(ranges,function(item){return item.toString()})}function makePossibleRangesCSS(property){var valueRange=property.valueRange(!0),result=[property.range(!0),valueRange],value=property.value();property.valueParts().forEach(function(r){var clone=r.clone();result.push(clone.shift(valueRange.start));var stream=stringStream.create(r.substring(value));if(stream.match(/^[\w\-]+\(/,!0)){stream.start=stream.pos;stream.backUp(1);stream.skipToPair("(",")");stream.backUp(1);var fnBody=stream.current();result.push(range(clone.start+stream.start,fnBody));cssEditTree.findParts(fnBody).forEach(function(part){result.push(range(clone.start+stream.start+part.start,part.substring(fnBody)))})}});return result}function matchedRangeForCSSProperty(rule,selRange,isBackward){var ranges=findInnerRanges(rule);isBackward&&ranges.reverse();var r=utils.find(ranges,function(item){return item.equal(selRange)});if(r)return ranges[ranges.indexOf(r)+1];var nested=ranges.filter(function(item){return item.inside(selRange.end)});if(nested.length)return nested.sort(function(a,b){return a.length()-b.length()})[0];r=utils.find(ranges,isBackward?function(item){return item.end<selRange.start}:function(item){return item.end>selRange.start});r||(r=ranges[0]);return r}function findNextCSSItem(editor){return findItem(editor,!1,cssSections.locateRule.bind(cssSections),getRangeForNextItemInCSS)}function findPrevCSSItem(editor){return findItem(editor,!0,cssSections.locateRule.bind(cssSections),getRangeForPrevItemInCSS)}function getRangeForNextItemInCSS(rule,offset,selRange){var tree=cssEditTree.parse(rule,{offset:offset});return matchedRangeForCSSProperty(tree,selRange,!1)}function getRangeForPrevItemInCSS(rule,offset,selRange){var tree=cssEditTree.parse(rule,{offset:offset});return matchedRangeForCSSProperty(tree,selRange,!0)}var range=require("../assets/range"),utils=require("../utils/common"),editorUtils=require("../utils/editor"),actionUtils=require("../utils/action"),stringStream=require("../assets/stringStream"),xmlParser=require("../parser/xml"),cssEditTree=require("../editTree/css"),cssSections=require("../utils/cssSections"),startTag=/^<([\w\:\-]+)((?:\s+[\w\-:]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/;return{selectNextItemAction:function(editor){return actionUtils.isSupportedCSS(editor.getSyntax())?findNextCSSItem(editor):findNextHTMLItem(editor)},selectPreviousItemAction:function(editor){return actionUtils.isSupportedCSS(editor.getSyntax())?findPrevCSSItem(editor):findPrevHTMLItem(editor)}}})},{"../assets/range":30,"../assets/stringStream":32,"../editTree/css":37,"../parser/xml":62,"../utils/action":70,"../utils/common":73,"../utils/cssSections":74,"../utils/editor":75}],17:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){return{selectLineAction:function(editor){var range=editor.getCurrentLineRange();editor.createSelection(range.start,range.end);return!0}}})},{}],18:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function joinTag(editor,profile,tag){var slash=profile.selfClosing()||" /",content=tag.open.range.substring(tag.source).replace(/\s*>$/,slash+">"),caretPos=editor.getCaretPos();content.length+tag.outerRange.start<caretPos&&(caretPos=content.length+tag.outerRange.start);content=utils.escapeText(content);editor.replaceContent(content,tag.outerRange.start,tag.outerRange.end);editor.setCaretPos(caretPos);return!0}function splitTag(editor,profile,tag){var caretPos=editor.getCaretPos(),tagContent=profile.tag_nl===!0?"\n \n":"",content=tag.outerContent().replace(/\s*\/>$/,">");caretPos=tag.outerRange.start+content.length;content+=tagContent+"</"+tag.open.name+">";content=utils.escapeText(content);editor.replaceContent(content,tag.outerRange.start,tag.outerRange.end);editor.setCaretPos(caretPos);return!0}var utils=require("../utils/common"),matcher=(require("../assets/resources"),require("../assets/htmlMatcher")),editorUtils=require("../utils/editor"),profile=require("../assets/profile");return{splitJoinTagAction:function(editor,profileName){var info=editorUtils.outputInfo(editor,null,profileName),curProfile=profile.get(info.profile),tag=matcher.tag(info.content,editor.getCaretPos());return tag?tag.close?joinTag(editor,curProfile,tag):splitTag(editor,curProfile,tag):!1}}})},{"../assets/htmlMatcher":26,"../assets/profile":29,"../assets/resources":31,"../utils/common":73,"../utils/editor":75}],19:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function toggleHTMLComment(editor){var r=range(editor.getSelectionRange()),info=editorUtils.outputInfo(editor);if(!r.length()){var tag=htmlMatcher.tag(info.content,editor.getCaretPos());tag&&(r=tag.outerRange)}return genericCommentToggle(editor,"<!--","-->",r)}function toggleCSSComment(editor){var rng=range(editor.getSelectionRange()),info=editorUtils.outputInfo(editor);if(!rng.length()){var rule=cssEditTree.parseFromPosition(info.content,editor.getCaretPos());if(rule){var property=cssItemFromPosition(rule,editor.getCaretPos());rng=property?property.range(!0):range(rule.nameRange(!0).start,rule.source)}}if(!rng.length()){rng=range(editor.getCurrentLineRange());utils.narrowToNonSpace(info.content,rng)}return genericCommentToggle(editor,"/*","*/",rng)}function cssItemFromPosition(rule,absPos){var relPos=absPos-(rule.options.offset||0),reSafeChar=/^[\s\n\r]/;return utils.find(rule.list(),function(item){return item.range().end===relPos?reSafeChar.test(rule.source.charAt(relPos)):item.range().inside(relPos)})}function searchComment(text,from,startToken,endToken){for(var commentStart=-1,commentEnd=-1,hasMatch=function(str,start){return text.substr(start,str.length)==str};from--;)if(hasMatch(startToken,from)){commentStart=from;break}if(-1!=commentStart){from=commentStart;for(var contentLen=text.length;contentLen>=from++;)if(hasMatch(endToken,from)){commentEnd=from+endToken.length;break}}return-1!=commentStart&&-1!=commentEnd?range(commentStart,commentEnd-commentStart):null}function genericCommentToggle(editor,commentStart,commentEnd,range){function removeComment(str){return str.replace(new RegExp("^"+utils.escapeForRegexp(commentStart)+"\\s*"),function(str){caretPos-=str.length;return""}).replace(new RegExp("\\s*"+utils.escapeForRegexp(commentEnd)+"$"),"")}var content=editorUtils.outputInfo(editor).content,caretPos=editor.getCaretPos(),newContent=null,commentRange=searchComment(content,caretPos,commentStart,commentEnd);if(commentRange&&commentRange.overlap(range)){range=commentRange;newContent=removeComment(range.substring(content))}else{newContent=commentStart+" "+range.substring(content).replace(new RegExp(utils.escapeForRegexp(commentStart)+"\\s*|\\s*"+utils.escapeForRegexp(commentEnd),"g"),"")+" "+commentEnd;caretPos+=commentStart.length+1}if(null!==newContent){newContent=utils.escapeText(newContent);editor.setCaretPos(range.start);editor.replaceContent(editorUtils.unindent(editor,newContent),range.start,range.end);editor.setCaretPos(caretPos);return!0}return!1}var prefs=require("../assets/preferences"),range=require("../assets/range"),utils=require("../utils/common"),actionUtils=require("../utils/action"),editorUtils=require("../utils/editor"),htmlMatcher=require("../assets/htmlMatcher"),cssEditTree=require("../editTree/css");return{toggleCommentAction:function(editor){var info=editorUtils.outputInfo(editor);if(actionUtils.isSupportedCSS(info.syntax)){var caretPos=editor.getCaretPos(),tag=htmlMatcher.tag(info.content,caretPos);tag&&tag.open.range.inside(caretPos)&&(info.syntax="html")}var cssSyntaxes=prefs.getArray("css.syntaxes");return~cssSyntaxes.indexOf(info.syntax)?toggleCSSComment(editor):toggleHTMLComment(editor)}}})},{"../assets/htmlMatcher":26,"../assets/preferences":28,"../assets/range":30,"../editTree/css":37,"../utils/action":70,"../utils/common":73,"../utils/editor":75}],20:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function updateImageSizeHTML(editor){var offset=editor.getCaretPos(),info=editorUtils.outputInfo(editor),xmlElem=xmlEditTree.parseFromPosition(info.content,offset,!0);xmlElem&&"img"==(xmlElem.name()||"").toLowerCase()&&getImageSizeForSource(editor,xmlElem.value("src"),function(size){if(size){var compoundData=xmlElem.range(!0);xmlElem.value("width",size.width);xmlElem.value("height",size.height,xmlElem.indexOf("width")+1);actionUtils.compoundUpdate(editor,utils.extend(compoundData,{data:xmlElem.toString(),caret:offset}))}})}function updateImageSizeCSS(editor){var offset=editor.getCaretPos(),info=editorUtils.outputInfo(editor),cssRule=cssEditTree.parseFromPosition(info.content,offset,!0);if(cssRule){var m,prop=cssRule.itemFromPosition(offset,!0);prop&&(m=/url\((["']?)(.+?)\1\)/i.exec(prop.value()||""))&&getImageSizeForSource(editor,m[2],function(size){if(size){var compoundData=cssRule.range(!0);cssRule.value("width",size.width+"px");cssRule.value("height",size.height+"px",cssRule.indexOf("width")+1);actionUtils.compoundUpdate(editor,utils.extend(compoundData,{data:cssRule.toString(),caret:offset}))}})}}function getImageSizeForSource(editor,src,callback){var fileContent;if(src){if(/^data:/.test(src)){fileContent=base64.decode(src.replace(/^data\:.+?;.+?,/,""));return callback(actionUtils.getImageSize(fileContent))}var absPath=file.locateFile(editor.getFilePath(),src);if(null===absPath)throw"Can't find "+src+" file";file.read(absPath,function(err,content){if(err)throw"Unable to read "+absPath+": "+err;content=String(content);callback(actionUtils.getImageSize(content))})}}var utils=require("../utils/common"),editorUtils=require("../utils/editor"),actionUtils=require("../utils/action"),xmlEditTree=require("../editTree/xml"),cssEditTree=require("../editTree/css"),base64=require("../utils/base64"),file=require("../plugin/file");return{updateImageSizeAction:function(editor){actionUtils.isSupportedCSS(editor.getSyntax())?updateImageSizeCSS(editor):updateImageSizeHTML(editor);return!0}}})},{"../editTree/css":37,"../editTree/xml":38,"../plugin/file":63,"../utils/action":70,"../utils/base64":71,"../utils/common":73,"../utils/editor":75}],21:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function updateAttributes(tag,abbrNode,ix){var classNames=(abbrNode.attribute("class")||"").split(/\s+/g);ix&&classNames.push("+"+abbrNode.name());var r=function(str){return utils.replaceCounter(str,abbrNode.counter)};classNames.forEach(function(className){if(className){className=r(className);var ch=className.charAt(0);"+"==ch?tag.addClass(className.substr(1)):"-"==ch?tag.removeClass(className.substr(1)):tag.value("class",className)}});abbrNode.attributeList().forEach(function(attr){if("class"!=attr.name.toLowerCase()){var ch=attr.name.charAt(0);if("+"==ch){var attrName=attr.name.substr(1),tagAttr=tag.get(attrName);tagAttr?tagAttr.value(tagAttr.value()+r(attr.value)):tag.value(attrName,r(attr.value))}else"-"==ch?tag.remove(attr.name.substr(1)):tag.value(attr.name,r(attr.value))}})}var xmlEditTree=require("../editTree/xml"),actionUtils=(require("../utils/editor"),require("../utils/action")),utils=require("../utils/common"),parser=require("../parser/abbreviation");return{updateTagAction:function(editor,abbr){abbr=abbr||editor.prompt("Enter abbreviation");if(!abbr)return!1;var content=editor.getContent(),ctx=actionUtils.captureContext(editor),tag=this.getUpdatedTag(abbr,ctx,content);if(!tag)return!1;tag.name()!=ctx.name&&ctx.match.close&&editor.replaceContent("</"+tag.name()+">",ctx.match.close.range.start,ctx.match.close.range.end,!0);editor.replaceContent(tag.source,ctx.match.open.range.start,ctx.match.open.range.end,!0);return!0},getUpdatedTag:function(abbr,ctx,content,options){if(!ctx)return null;var tree=parser.parse(abbr,options||{}),tag=xmlEditTree.parse(ctx.match.open.range.substring(content),{offset:ctx.match.outerRange.start});tree.children.forEach(function(node,i){updateAttributes(tag,node,i)});var el=tree.children[0];el.data("nameResolved")||tag.name(el.name());return tag}}})},{"../editTree/xml":38,"../parser/abbreviation":55,"../utils/action":70,"../utils/common":73,"../utils/editor":75}],22:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){var range=require("../assets/range"),htmlMatcher=require("../assets/htmlMatcher"),utils=require("../utils/common"),editorUtils=require("../utils/editor"),actionUtils=require("../utils/action"),parser=require("../parser/abbreviation");return{wrapWithAbbreviationAction:function(editor,abbr,syntax,profile){var info=editorUtils.outputInfo(editor,syntax,profile);abbr=abbr||editor.prompt("Enter abbreviation");if(!abbr)return null;abbr=String(abbr);var r=range(editor.getSelectionRange());if(!r.length()){var match=htmlMatcher.tag(info.content,r.start);if(!match)return!1;r=utils.narrowToNonSpace(info.content,match.range)}var newContent=utils.escapeText(r.substring(info.content)),result=parser.expand(abbr,{pastedContent:editorUtils.unindent(editor,newContent),syntax:info.syntax,profile:info.profile,contextNode:actionUtils.captureContext(editor)});if(result){editor.replaceContent(result,r.start,r.end);return!0}return!1}}})},{"../assets/htmlMatcher":26,"../assets/range":30,"../parser/abbreviation":55,"../utils/action":70,"../utils/common":73,"../utils/editor":75}],23:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function intersection(arr1,arr2){var result=[],smaller=arr1,larger=arr2;if(smaller.length>larger.length){smaller=arr2;larger=arr1}larger.forEach(function(item){~smaller.indexOf(item)&&result.push(item)});return result}function parseDB(data,optimized){"string"==typeof data&&(data=JSON.parse(data));optimized||(data=optimize(data));vendorsDB=data.vendors;cssDB=data.css;erasDB=data.era}function optimize(data){"string"==typeof data&&(data=JSON.parse(data));return{vendors:parseVendors(data),css:parseCSS(data),era:parseEra(data)}}function parseVendors(data){var out={};Object.keys(data.agents).forEach(function(name){var agent=data.agents[name];out[name]={prefix:agent.prefix,versions:agent.versions}});return out}function parseCSS(data){var out={};data.cats.CSS;Object.keys(data.data).forEach(function(name){var section=data.data[name];name in cssSections&&cssSections[name].forEach(function(kw){out[kw]=section.stats})});return out}function parseEra(data){return Object.keys(data.eras).sort(function(a,b){return parseInt(a.substr(1))-parseInt(b.substr(1))})}function getVendorsList(){var allVendors=Object.keys(vendorsDB),vendors=prefs.getArray("caniuse.vendors");return vendors&&"all"!=vendors[0]?intersection(allVendors,vendors):allVendors}function getVersionSlice(){var era=prefs.get("caniuse.era"),ix=erasDB.indexOf(era);~ix||(ix=erasDB.indexOf("e-2"));return ix}var prefs=require("./preferences"),utils=require("../utils/common");prefs.define("caniuse.enabled",!0,"Enable support of Can I Use database. When enabled, CSS abbreviation resolver will look at Can I Use database first before detecting CSS properties that should be resolved");prefs.define("caniuse.vendors","all","A comma-separated list vendor identifiers (as described in Can I Use database) that should be supported when resolving vendor-prefixed properties. Set value to <code>all</code> to support all available properties");prefs.define("caniuse.era","e-2","Browser era, as defined in Can I Use database. Examples: <code>e0</code> (current version), <code>e1</code> (near future) <code>e-2</code> (2 versions back) and so on.");var cssSections={"border-image":["border-image"],"css-boxshadow":["box-shadow"],"css3-boxsizing":["box-sizing"],multicolumn:["column-width","column-count","columns","column-gap","column-rule-color","column-rule-style","column-rule-width","column-rule","column-span","column-fill"],"border-radius":["border-radius","border-top-left-radius","border-top-right-radius","border-bottom-right-radius","border-bottom-left-radius"],transforms2d:["transform"],"css-hyphens":["hyphens"],"css-transitions":["transition","transition-property","transition-duration","transition-timing-function","transition-delay"],"font-feature":["font-feature-settings"],"css-animation":["animation","animation-name","animation-duration","animation-timing-function","animation-iteration-count","animation-direction","animation-play-state","animation-delay","animation-fill-mode","@keyframes"],"css-gradients":["linear-gradient"],"css-masks":["mask-image","mask-source-type","mask-repeat","mask-position","mask-clip","mask-origin","mask-size","mask","mask-type","mask-box-image-source","mask-box-image-slice","mask-box-image-width","mask-box-image-outset","mask-box-image-repeat","mask-box-image","clip-path","clip-rule"],"css-featurequeries":["@supports"],flexbox:["flex","inline-flex","flex-direction","flex-wrap","flex-flow","order","flex"],calc:["calc"],"object-fit":["object-fit","object-position"],"css-grid":["grid","inline-grid","grid-template-rows","grid-template-columns","grid-template-areas","grid-template","grid-auto-rows","grid-auto-columns"," grid-auto-flow","grid-auto-position","grid"," grid-row-start","grid-column-start","grid-row-end","grid-column-end","grid-column","grid-row","grid-area","justify-self","justify-items","align-self","align-items"],"css-repeating-gradients":["repeating-linear-gradient"],"css-filters":["filter"],"user-select-none":["user-select"],"intrinsic-width":["min-content","max-content","fit-content","fill-available"],"css3-tabsize":["tab-size"]},cssDB=null,vendorsDB=null,erasDB=null,db=null;!function(r){if("undefined"==typeof define||!define.amd)try{var fs=r("fs"),path=r("path");db=fs.readFileSync(path.join(__dirname,"../caniuse.json"),{encoding:"utf8"})}catch(e){}}(require);db&&parseDB(db);return{load:parseDB,optimize:optimize,resolvePrefixes:function(property){if(!(prefs.get("caniuse.enabled")&&cssDB&&property in cssDB))return null;var prefixes=[],propStats=cssDB[property],versions=getVersionSlice();getVendorsList().forEach(function(vendor){for(var v,vendorVesions=vendorsDB[vendor].versions.slice(versions),i=0;i<vendorVesions.length;i++){v=vendorVesions[i];if(v&&~propStats[vendor][v].indexOf("x")){prefixes.push(vendorsDB[vendor].prefix);break}}});return utils.unique(prefixes).sort(function(a,b){return b.length-a.length})}}})},{"../utils/common":73,"./preferences":28}],24:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function commonFactory(value){return{data:value}}var factories={},reAttrs=/([@\!]?)([\w\-:]+)\s*=\s*(['"])(.*?)\3/g;module=module||{};module.exports={add:function(name,factory){var that=this;factories[name]=function(){var elem=factory.apply(that,arguments);elem&&(elem.type=name);return elem}},get:function(name){return factories[name]},create:function(name){var args=[].slice.call(arguments,1),factory=this.get(name);return factory?factory.apply(this,args):null},is:function(elem,type){return this.type(elem)===type},type:function(elem){return elem&&elem.type}};module.exports.add("element",function(elementName,attrs,isEmpty){var ret={name:elementName,is_empty:!!isEmpty};if(attrs){ret.attributes=[];if(Array.isArray(attrs))ret.attributes=attrs;else if("string"==typeof attrs)for(var m;m=reAttrs.exec(attrs);)ret.attributes.push({name:m[2],value:m[4],isDefault:"@"==m[1],isImplied:"!"==m[1]});else ret.attributes=Object.keys(attrs).map(function(name){return{name:name,value:attrs[name]}})}return ret});module.exports.add("snippet",commonFactory);module.exports.add("reference",commonFactory);module.exports.add("empty",function(){return{}});return module.exports})},{}],25:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function HandlerList(){this._list=[]}var utils=require("../utils/common");HandlerList.prototype={add:function(fn,options){var order=this._list.length;options&&"order"in options&&(order=1e4*options.order);this._list.push(utils.extend({},options,{order:order,fn:fn}))},remove:function(fn){var item=utils.find(this._list,function(item){return item.fn===fn});item&&this._list.splice(this._list.indexOf(item),1)},list:function(){return this._list.sort(function(a,b){return b.order-a.order})},listFn:function(){return this.list().map(function(item){return item.fn})},exec:function(skipValue,args){args=args||[];var result=null;utils.find(this.list(),function(h){result=h.fn.apply(h,args);return result!==skipValue?!0:void 0});return result}};return{create:function(){return new HandlerList}}})},{"../utils/common":73}],26:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function openTag(i,match){return{name:match[1],selfClose:!!match[3],range:range(i,match[0]),type:"open"}}function closeTag(i,match){return{name:match[1],range:range(i,match[0]),type:"close"}}function comment(i,match){return{range:range(i,"number"==typeof match?match-i:match[0]),type:"comment"}}function createMatcher(text){var m,memo={};return{open:function(i){var m=this.matches(i);return m&&"open"==m.type?m:null},close:function(i){var m=this.matches(i);return m&&"close"==m.type?m:null},matches:function(i){var key="p"+i;if(!(key in memo)){memo[key]=!1;if("<"==text.charAt(i)){var substr=text.slice(i);(m=substr.match(reOpenTag))?memo[key]=openTag(i,m):(m=substr.match(reCloseTag))&&(memo[key]=closeTag(i,m))}}return memo[key]},text:function(){return text},clean:function(){memo=text=m=null}}}function matches(text,pos,pattern){return text.substring(pos,pos+pattern.length)==pattern}function findClosingPair(open,matcher){for(var stack=[],tag=null,text=matcher.text(),pos=open.range.end,len=text.length;len>pos;pos++){if(matches(text,pos,"<!--"))for(var j=pos;len>j;j++)if(matches(text,j,"-->")){pos=j+3;break}if(tag=matcher.matches(pos)){if("open"!=tag.type||tag.selfClose){if("close"==tag.type){if(!stack.length)return tag.name==open.name?tag:null;if(stack[stack.length-1]==tag.name)stack.pop();else{for(var found=!1;stack.length&&!found;){var last=stack.pop();last==tag.name&&(found=!0)}if(!stack.length&&!found)return tag.name==open.name?tag:null}}}else stack.push(tag.name);pos=tag.range.end-1}}}var range=require("./range"),reOpenTag=/^<([\w\:\-]+)((?:\s+[\w\-:]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/,reCloseTag=/^<\/([\w\:\-]+)[^>]*>/;return{find:function(text,pos){for(var j,jl,matcher=createMatcher(text),open=null,close=null,i=pos;i>=0;i--)if(open=matcher.open(i)){if(open.selfClose){if(open.range.cmp(pos,"lt","gt"))break;continue}close=findClosingPair(open,matcher);if(close){var r=range.create2(open.range.start,close.range.end);if(r.contains(pos))break}else if(open.range.contains(pos))break;open=null}else if(matches(text,i,"-->")){for(j=i-1;j>=0&&!matches(text,j,"-->");j--)if(matches(text,j,"<!--")){i=j;break}}else if(matches(text,i,"<!--")){for(j=i+4,jl=text.length;jl>j;j++)if(matches(text,j,"-->")){j+=3;break}open=comment(i,j);break}matcher.clean();if(open){var outerRange=null,innerRange=null;if(close){outerRange=range.create2(open.range.start,close.range.end);innerRange=range.create2(open.range.end,close.range.start)}else outerRange=innerRange=range.create2(open.range.start,open.range.end);if("comment"==open.type){var _c=outerRange.substring(text);innerRange.start+=_c.length-_c.replace(/^<\!--\s*/,"").length;innerRange.end-=_c.length-_c.replace(/\s*-->$/,"").length}return{open:open,close:close,type:"comment"==open.type?"comment":"tag",innerRange:innerRange,innerContent:function(){return this.innerRange.substring(text)},outerRange:outerRange,outerContent:function(){return this.outerRange.substring(text)},range:innerRange.length()&&innerRange.cmp(pos,"lte","gte")?innerRange:outerRange,content:function(){return this.range.substring(text)},source:text}}},tag:function(text,pos){var result=this.find(text,pos);return result&&"tag"==result.type?result:void 0}}})},{"./range":30}],27:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){return{log:function(){"undefined"!=typeof console&&console.log&&console.log.apply(console,arguments)}}})},{}],28:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function toBoolean(val){if("string"==typeof val){val=val.toLowerCase();return"yes"==val||"true"==val||"1"==val}return!!val}function isValueObj(obj){return"object"==typeof obj&&!Array.isArray(obj)&&"value"in obj&&Object.keys(obj).length<3}var utils=require("../utils/common"),preferences={},defaults={},_dbgDefaults=null,_dbgPreferences=null;return{define:function(name,value,description){var prefs=name;if("string"==typeof name){prefs={};prefs[name]={value:value,description:description}}Object.keys(prefs).forEach(function(k){
3
- var v=prefs[k];defaults[k]=isValueObj(v)?v:{value:v}})},set:function(name,value){var prefs=name;if("string"==typeof name){prefs={};prefs[name]=value}Object.keys(prefs).forEach(function(k){var v=prefs[k];if(!(k in defaults))throw new Error('Property "'+k+'" is not defined. You should define it first with `define` method of current module');if(v!==defaults[k].value){switch(typeof defaults[k].value){case"boolean":v=toBoolean(v);break;case"number":v=parseInt(v+"",10)||0;break;default:null!==v&&(v+="")}preferences[k]=v}else k in preferences&&delete preferences[k]})},get:function(name){return name in preferences?preferences[name]:name in defaults?defaults[name].value:void 0},getArray:function(name){var val=this.get(name);if("undefined"==typeof val||null===val||""===val)return null;val=val.split(",").map(utils.trim);return val.length?val:null},getDict:function(name){var result={};this.getArray(name).forEach(function(val){var parts=val.split(":");result[parts[0]]=parts[1]});return result},description:function(name){return name in defaults?defaults[name].description:void 0},remove:function(name){Array.isArray(name)||(name=[name]);name.forEach(function(key){key in preferences&&delete preferences[key];key in defaults&&delete defaults[key]})},list:function(){return Object.keys(defaults).sort().map(function(key){return{name:key,value:this.get(key),type:typeof defaults[key].value,description:defaults[key].description}},this)},load:function(json){Object.keys(json).forEach(function(key){this.set(key,json[key])},this)},exportModified:function(){return utils.extend({},preferences)},reset:function(){preferences={}},_startTest:function(){_dbgDefaults=defaults;_dbgPreferences=preferences;defaults={};preferences={}},_stopTest:function(){defaults=_dbgDefaults;preferences=_dbgPreferences}}})},{"../utils/common":73}],29:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function OutputProfile(options){utils.extend(this,defaultProfile,options)}function stringCase(str,caseValue){switch(String(caseValue||"").toLowerCase()){case"lower":return str.toLowerCase();case"upper":return str.toUpperCase()}return str}function createProfile(name,options){return profiles[name.toLowerCase()]=new OutputProfile(options)}function createDefaultProfiles(){createProfile("xhtml");createProfile("html",{self_closing_tag:!1,compact_bool:!0});createProfile("xml",{self_closing_tag:!0,tag_nl:!0});createProfile("plain",{tag_nl:!1,indent:!1,place_cursor:!1});createProfile("line",{tag_nl:!1,indent:!1,extraFilters:"s"});createProfile("css",{tag_nl:!0});createProfile("css_line",{tag_nl:!1})}var utils=require("../utils/common"),resources=require("./resources"),prefs=require("./preferences");prefs.define("profile.allowCompactBoolean",!0,'This option can be used to globally disable compact form of boolean attribues (attributes where name and value are equal). With compactform enabled, HTML tags can be outputted as <code>&lt;div contenteditable&gt;</code> instead of <code>&lt;div contenteditable="contenteditable"&gt;</code>');prefs.define("profile.booleanAttributes","^contenteditable|seamless$","A regular expression for attributes that should be boolean by default.If attribute name matches this expression, you don’t have to write dot after attribute name in Emmet abbreviation to mark it as boolean.");var profiles={},defaultProfile={tag_case:"asis",attr_case:"asis",attr_quotes:"double",tag_nl:"decide",tag_nl_leaf:!1,place_cursor:!0,indent:!0,inline_break:3,compact_bool:!1,self_closing_tag:"xhtml",filters:"",extraFilters:""};OutputProfile.prototype={tagName:function(name){return stringCase(name,this.tag_case)},attributeName:function(name){return stringCase(name,this.attr_case)},attributeQuote:function(){return"single"==this.attr_quotes?"'":'"'},selfClosing:function(){return"xhtml"==this.self_closing_tag?" /":this.self_closing_tag===!0?"/":""},cursor:function(){return this.place_cursor?utils.getCaretPlaceholder():""},isBoolean:function(name,value){if(name==value)return!0;var boolAttrs=prefs.get("profile.booleanAttributes");if(!value&&boolAttrs){boolAttrs=new RegExp(boolAttrs,"i");return boolAttrs.test(name)}return!1},allowCompactBoolean:function(){return this.compact_bool&&prefs.get("profile.allowCompactBoolean")}};createDefaultProfiles();return{create:function(name,options){return 2==arguments.length?createProfile(name,options):new OutputProfile(utils.defaults(name||{},defaultProfile))},get:function(name,syntax){if(!name&&syntax){var profile=resources.findItem(syntax,"profile");profile&&(name=profile)}return name?name instanceof OutputProfile?name:"string"==typeof name&&name.toLowerCase()in profiles?profiles[name.toLowerCase()]:this.create(name):profiles.plain},remove:function(name){name=(name||"").toLowerCase();name in profiles&&delete profiles[name]},reset:function(){profiles={};createDefaultProfiles()},stringCase:stringCase}})},{"../utils/common":73,"./preferences":28,"./resources":31}],30:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function cmp(a,b,op){switch(op){case"eq":case"==":return a===b;case"lt":case"<":return b>a;case"lte":case"<=":return b>=a;case"gt":case">":return a>b;case"gte":case">=":return a>=b}}function Range(start,len){if("object"==typeof start&&"start"in start){this.start=Math.min(start.start,start.end);this.end=Math.max(start.start,start.end)}else if(Array.isArray(start)){this.start=start[0];this.end=start[1]}else{len="string"==typeof len?len.length:+len;this.start=start;this.end=start+len}}Range.prototype={length:function(){return Math.abs(this.end-this.start)},equal:function(range){return this.cmp(range,"eq","eq")},shift:function(delta){this.start+=delta;this.end+=delta;return this},overlap:function(range){return range.start<=this.end&&range.end>=this.start},intersection:function(range){if(this.overlap(range)){var start=Math.max(range.start,this.start),end=Math.min(range.end,this.end);return new Range(start,end-start)}return null},union:function(range){if(this.overlap(range)){var start=Math.min(range.start,this.start),end=Math.max(range.end,this.end);return new Range(start,end-start)}return null},inside:function(loc){return this.cmp(loc,"lte","gt")},contains:function(loc){return this.cmp(loc,"lt","gt")},include:function(r){return this.cmp(r,"lte","gte")},cmp:function(loc,left,right){var a,b;if(loc instanceof Range){a=loc.start;b=loc.end}else a=b=loc;return cmp(this.start,a,left||"<=")&&cmp(this.end,b,right||">")},substring:function(str){return this.length()>0?str.substring(this.start,this.end):""},clone:function(){return new Range(this.start,this.length())},toArray:function(){return[this.start,this.end]},toString:function(){return this.valueOf()},valueOf:function(){return"{"+this.start+", "+this.length()+"}"}};module.exports=function(start,len){if("undefined"==typeof start||null===start)return null;if(start instanceof Range)return start;if("object"==typeof start&&"start"in start&&"end"in start){len=start.end-start.start;start=start.start}return new Range(start,len)};module.exports.create=module.exports;module.exports.isRange=function(val){return val instanceof Range};module.exports.create2=function(start,end){"number"==typeof start&&"number"==typeof end&&(end-=start);return this.create(start,end)};module.exports.sort=function(ranges,reverse){ranges=ranges.sort(function(a,b){return a.start===b.start?b.end-a.end:a.start-b.start});reverse&&ranges.reverse();return ranges};return module.exports})},{}],31:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function each(obj,fn){obj&&Object.keys(obj).forEach(function(key){fn(obj[key],key)})}function normalizeCaretPlaceholder(text){return utils.replaceUnescapedSymbol(text,"|",utils.getCaretPlaceholder())}function parseItem(name,value,type){value=normalizeCaretPlaceholder(value);return"snippets"==type?elements.create("snippet",value):"abbreviations"==type?parseAbbreviation(name,value):void 0}function parseAbbreviation(key,value){key=utils.trim(key);var m;return(m=reTag.exec(value))?elements.create("element",m[1],m[2],"/"==m[4]):elements.create("reference",value)}function normalizeName(str){return str.replace(/:$/,"").replace(/:/g,"-")}function expandSnippetsDefinition(snippets){var out={};each(snippets,function(val,key){for(var items=key.split("|"),i=items.length-1;i>=0;i--)out[items[i]]=val});return out}var handlerList=require("./handlerList"),utils=require("../utils/common"),elements=require("./elements"),stringScore=(require("../assets/logger"),require("../vendor/stringScore")),cssResolver=require("../resolver/css"),VOC_SYSTEM="system",VOC_USER="user",cache={},reTag=/^<(\w+\:?[\w\-]*)((?:\s+[@\!]?[\w\:\-]+\s*=\s*(['"]).*?\3)*)\s*(\/?)>/,systemSettings={},userSettings={},resolvers=handlerList.create();utils.extend(exports,{setVocabulary:function(data,type){cache={};var voc={};each(data,function(section,syntax){var _section={};each(section,function(subsection,name){("abbreviations"==name||"snippets"==name)&&(subsection=expandSnippetsDefinition(subsection));_section[name]=subsection});voc[syntax]=_section});type==VOC_SYSTEM?systemSettings=voc:userSettings=voc},getVocabulary:function(name){return name==VOC_SYSTEM?systemSettings:userSettings},getMatchedResource:function(node,syntax){return resolvers.exec(null,utils.toArray(arguments))||this.findSnippet(syntax,node.name())},getVariable:function(name){return(this.getSection("variables")||{})[name]},setVariable:function(name,value){var voc=this.getVocabulary("user")||{};"variables"in voc||(voc.variables={});voc.variables[name]=value;this.setVocabulary(voc,"user")},hasSyntax:function(syntax){return syntax in this.getVocabulary(VOC_USER)||syntax in this.getVocabulary(VOC_SYSTEM)},addResolver:function(fn,options){resolvers.add(fn,options)},removeResolver:function(fn){resolvers.remove(fn)},getSection:function(name){if(!name)return null;name in cache||(cache[name]=utils.deepMerge({},systemSettings[name],userSettings[name]));for(var key,data=cache[name],subsections=utils.toArray(arguments,1);data&&(key=subsections.shift());){if(!(key in data))return null;data=data[key]}return data},findItem:function(topSection,subsection){for(var data=this.getSection(topSection);data;){if(subsection in data)return data[subsection];data=this.getSection(data["extends"])}},findSnippet:function(syntax,name,memo){if(!syntax||!name)return null;memo=memo||[];var names=[name];~name.indexOf("-")&&names.push(name.replace(/\-/g,":"));var data=this.getSection(syntax),matchedItem=null;["snippets","abbreviations"].some(function(sectionName){var data=this.getSection(syntax,sectionName);return data?names.some(function(n){return data[n]?matchedItem=parseItem(n,data[n],sectionName):void 0}):void 0},this);memo.push(syntax);return matchedItem||!data["extends"]||~memo.indexOf(data["extends"])?matchedItem:this.findSnippet(data["extends"],name,memo)},fuzzyFindSnippet:function(syntax,name,minScore){var result=this.fuzzyFindMatches(syntax,name,minScore)[0];return result?result.value.parsedValue:void 0},fuzzyFindMatches:function(syntax,name,minScore){minScore=minScore||.3;name=normalizeName(name);var snippets=this.getAllSnippets(syntax);return Object.keys(snippets).map(function(key){var value=snippets[key];return{key:key,score:stringScore.score(value.nk,name,.1),value:value}}).filter(function(item){return item.score>=minScore}).sort(function(a,b){return a.score-b.score}).reverse()},getAllSnippets:function(syntax){var cacheKey="all-"+syntax;if(!cache[cacheKey]){var stack=[],sectionKey=syntax,memo=[];do{var section=this.getSection(sectionKey);if(!section)break;["snippets","abbreviations"].forEach(function(sectionName){var stackItem={};each(section[sectionName]||null,function(v,k){stackItem[k]={nk:normalizeName(k),value:v,parsedValue:parseItem(k,v,sectionName),type:sectionName}});stack.push(stackItem)});memo.push(sectionKey);sectionKey=section["extends"]}while(sectionKey&&!~memo.indexOf(sectionKey));cache[cacheKey]=utils.extend.apply(utils,stack.reverse())}return cache[cacheKey]},getNewline:function(){var nl=this.getVariable("newline");return"string"==typeof nl?nl:"\n"},setNewline:function(str){this.setVariable("newline",str);this.setVariable("nl",str)}});exports.addResolver(cssResolver.resolve.bind(cssResolver));!function(r){if("undefined"==typeof define||!define.amd)try{var fs=r("fs"),path=r("path"),defaultSnippets=fs.readFileSync(path.join(__dirname,"../snippets.json"),{encoding:"utf8"});exports.setVocabulary(JSON.parse(defaultSnippets),VOC_SYSTEM)}catch(e){}}(require);return exports})},{"../assets/logger":27,"../resolver/css":64,"../utils/common":73,"../vendor/stringScore":79,"./elements":24,"./handlerList":25}],32:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function StringStream(string){this.pos=this.start=0;this.string=string;this._length=string.length}StringStream.prototype={eol:function(){return this.pos>=this._length},sol:function(){return 0===this.pos},peek:function(){return this.string.charAt(this.pos)},next:function(){return this.pos<this._length?this.string.charAt(this.pos++):void 0},eat:function(match){var ok,ch=this.string.charAt(this.pos);ok="string"==typeof match?ch==match:ch&&(match.test?match.test(ch):match(ch));if(ok){++this.pos;return ch}},eatWhile:function(match){for(var start=this.pos;this.eat(match););return this.pos>start},eatSpace:function(){for(var start=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>start},skipToEnd:function(){this.pos=this._length},skipTo:function(ch){var found=this.string.indexOf(ch,this.pos);if(found>-1){this.pos=found;return!0}},skipToPair:function(open,close,skipString){for(var ch,braceCount=0,pos=this.pos,len=this._length;len>pos;){ch=this.string.charAt(pos++);if(ch==open)braceCount++;else if(ch==close){braceCount--;if(1>braceCount){this.pos=pos;return!0}}else!skipString||'"'!=ch&&"'"!=ch||this.skipString(ch)}return!1},skipQuoted:function(noBackup){var ch=this.string.charAt(noBackup?this.pos:this.pos-1);if('"'===ch||"'"===ch){noBackup&&this.pos++;return this.skipString(ch)}},skipString:function(quote){for(var ch,pos=this.pos,len=this._length;len>pos;){ch=this.string.charAt(pos++);if("\\"!=ch&&ch==quote){this.pos=pos;return!0}}return!1},backUp:function(n){this.pos-=n},match:function(pattern,consume,caseInsensitive){if("string"!=typeof pattern){var match=this.string.slice(this.pos).match(pattern);match&&consume!==!1&&(this.pos+=match[0].length);return match}var cased=caseInsensitive?function(str){return str.toLowerCase()}:function(str){return str};if(cased(this.string).indexOf(cased(pattern),this.pos)==this.pos){consume!==!1&&(this.pos+=pattern.length);return!0}},current:function(backUp){return this.string.slice(this.start,this.pos-(backUp?1:0))}};module.exports=function(string){return new StringStream(string)};module.exports.create=module.exports;return module.exports})},{}],33:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){var utils=require("../utils/common"),stringStream=require("./stringStream"),resources=require("./resources"),startPlaceholderNum=100,tabstopIndex=0,defaultOptions={replaceCarets:!1,escape:function(ch){return"\\"+ch},tabstop:function(data){return data.token},variable:function(data){return data.token}};return{extract:function(text,options){var placeholders={carets:""},marks=[];options=utils.extend({},defaultOptions,options,{tabstop:function(data){var token=data.token,ret="";if("cursor"==data.placeholder)marks.push({start:data.start,end:data.start+token.length,group:"carets",value:""});else{"placeholder"in data&&(placeholders[data.group]=data.placeholder);data.group in placeholders&&(ret=placeholders[data.group]);marks.push({start:data.start,end:data.start+token.length,group:data.group,value:ret})}return token}});options.replaceCarets&&(text=text.replace(new RegExp(utils.escapeForRegexp(utils.getCaretPlaceholder()),"g"),"${0:cursor}"));text=this.processText(text,options);var buf="",lastIx=0,tabStops=marks.map(function(mark){buf+=text.substring(lastIx,mark.start);var pos=buf.length,ph=placeholders[mark.group]||"";buf+=ph;lastIx=mark.end;return{group:mark.group,start:pos,end:pos+ph.length}});buf+=text.substring(lastIx);return{text:buf,tabstops:tabStops.sort(function(a,b){return a.start-b.start})}},processText:function(text,options){options=utils.extend({},defaultOptions,options);for(var ch,m,a,buf="",stream=stringStream.create(text);ch=stream.next();)if("\\"!=ch||stream.eol()){a=ch;if("$"==ch){stream.start=stream.pos-1;if(m=stream.match(/^[0-9]+/))a=options.tabstop({start:buf.length,group:stream.current().substr(1),token:stream.current()});else if(m=stream.match(/^\{([a-z_\-][\w\-]*)\}/))a=options.variable({start:buf.length,name:m[1],token:stream.current()});else if(m=stream.match(/^\{([0-9]+)(:.+?)?\}/,!1)){stream.skipToPair("{","}");var obj={start:buf.length,group:m[1],token:stream.current()},placeholder=obj.token.substring(obj.group.length+2,obj.token.length-1);placeholder&&(obj.placeholder=placeholder.substr(1));a=options.tabstop(obj)}}buf+=a}else buf+=options.escape(stream.next());return buf},upgrade:function(node,offset){var maxNum=0,options={tabstop:function(data){var group=parseInt(data.group,10);group>maxNum&&(maxNum=group);return data.placeholder?"${"+(group+offset)+":"+data.placeholder+"}":"${"+(group+offset)+"}"}};["start","end","content"].forEach(function(p){node[p]=this.processText(node[p],options)},this);return maxNum},variablesResolver:function(node){var placeholderMemo={};return function(str,varName){if("child"==varName)return str;if("cursor"==varName)return utils.getCaretPlaceholder();var attr=node.attribute(varName);if("undefined"!=typeof attr&&attr!==str)return attr;var varValue=resources.getVariable(varName);if(varValue)return varValue;placeholderMemo[varName]||(placeholderMemo[varName]=startPlaceholderNum++);return"${"+placeholderMemo[varName]+":"+varName+"}"}},replaceVariables:function(str,vars){vars=vars||{};var resolver="function"==typeof vars?vars:function(str,p1){return p1 in vars?vars[p1]:null};return this.processText(str,{variable:function(data){var newValue=resolver(data.token,data.name,data);null===newValue&&(newValue=resources.getVariable(data.name));(null===newValue||"undefined"==typeof newValue)&&(newValue=data.token);return newValue}})},resetTabstopIndex:function(){tabstopIndex=0;startPlaceholderNum=100},abbrOutputProcessor:function(text,node,type){var maxNum=0,that=this,tsOptions={tabstop:function(data){var group=parseInt(data.group,10);if(0===group)return"${0}";group>maxNum&&(maxNum=group);if(data.placeholder){var ix=group+tabstopIndex,placeholder=that.processText(data.placeholder,tsOptions);return"${"+ix+":"+placeholder+"}"}return"${"+(group+tabstopIndex)+"}"}};text=this.processText(text,tsOptions);text=this.replaceVariables(text,this.variablesResolver(node));tabstopIndex+=maxNum+1;return text}}})},{"../utils/common":73,"./resources":31,"./stringStream":32}],34:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function TokenIterator(tokens){this.tokens=tokens;this._position=0;this.reset()}TokenIterator.prototype={next:function(){if(this.hasNext()){var token=this.tokens[++this._i];this._position=token.start;return token}this._i=this._il;return null},current:function(){return this.tokens[this._i]},peek:function(){return this.tokens[this._i+i]},position:function(){return this._position},hasNext:function(){return this._i<this._il-1},reset:function(){this._i=0;this._il=this.tokens.length},item:function(){return this.tokens[this._i]},itemNext:function(){return this.tokens[this._i+1]},itemPrev:function(){return this.tokens[this._i-1]},nextUntil:function(type,callback){for(var token,test="string"==typeof type?function(t){return t.type==type}:type;token=this.next();){callback&&callback.call(this,token);if(test.call(this,token))break}}};return{create:function(tokens){return new TokenIterator(tokens)}}})},{}],35:[function(require,module,exports){module.exports={eras:{"e-26":"26 versions back","e-25":"25 versions back","e-24":"24 versions back","e-23":"23 versions back","e-22":"22 versions back","e-21":"21 versions back","e-20":"20 versions back","e-19":"19 versions back","e-18":"18 versions back","e-17":"17 versions back","e-16":"16 versions back","e-15":"15 versions back","e-14":"14 versions back","e-13":"13 versions back","e-12":"12 versions back","e-11":"11 versions back","e-10":"10 versions back","e-9":"9 versions back","e-8":"8 versions back","e-7":"7 versions back","e-6":"6 versions back","e-5":"5 versions back","e-4":"4 versions back","e-3":"3 versions back","e-2":"2 versions back","e-1":"Previous version",e0:"Current",e1:"Near future",e2:"Farther future"},agents:{ie:{browser:"IE",abbr:"IE",prefix:"ms",type:"desktop",usage_global:{10:10.7866,11:.114751,5.5:.009298,6:.204912,7:.508182,8:8.31124,9:5.21297},versions:[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"5.5","6","7","8","9","10","11",null,null],current_version:""},firefox:{browser:"Firefox",abbr:"FF",prefix:"moz",type:"desktop",usage_global:{10:.112406,11:.088319,12:.208754,13:.096348,14:.096348,15:.136493,16:.264957,17:.192696,18:.112406,19:.128464,2:.016058,20:.16058,21:.216783,22:.256928,23:.907277,24:11.0318,25:.529914,26:.016058,27:.016058,3:.088319,3.5:.040145,3.6:.305102,4:.072261,5:.048174,6:.048174,7:.040145,8:.072261,9:.056203},versions:[null,"2","3","3.5","3.6","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27"],current_version:""},chrome:{browser:"Chrome",abbr:"Chr.",prefix:"webkit",type:"desktop",usage_global:{10:.048174,11:.112406,12:.064232,13:.056203,14:.056203,15:.072261,16:.048174,17:.040145,18:.08029,19:.040145,20:.040145,21:.48174,22:.248899,23:.216783,24:.200725,25:.361305,26:.353276,27:.369334,28:.610204,29:5.08236,30:24.6089,31:.16058,32:.064232,4:.024087,5:.024087,6:.032116,7:.024087,8:.032116,9:.024087},versions:["4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32"],current_version:""},safari:{browser:"Safari",abbr:"Saf.",prefix:"webkit",type:"desktop",usage_global:{3.1:0,3.2:.008692,4:.104377,5:.305102,5.1:1.28464,6:2.04739,6.1:.064232,7:.16058},versions:[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"3.1","3.2","4","5","5.1","6","6.1","7",null,null],current_version:""},opera:{browser:"Opera",abbr:"Op.",prefix:"o",type:"desktop",usage_global:{"10.0-10.1":.016058,10.5:.008392,10.6:.008029,11:.008219,11.1:.008219,11.5:.016058,11.6:.032116,12:.040145,12.1:.48174,15:.032116,16:.104377,17:.16058,18:0,"9.5-9.6":.008219},versions:[null,null,null,null,null,null,null,null,null,null,null,null,null,null,"9.5-9.6","10.0-10.1","10.5","10.6","11","11.1","11.5","11.6","12","12.1","15","16","17","18",null],current_version:"",prefix_exceptions:{15:"webkit",16:"webkit",17:"webkit",18:"webkit"}},ios_saf:{browser:"iOS Safari",abbr:"iOS",prefix:"webkit",type:"mobile",usage_global:{3.2:.00400113,"4.0-4.1":.00800226,"4.2-4.3":.0280079,"5.0-5.1":.28408,"6.0-6.1":1.15633,"7.0":2.52071},versions:[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"3.2","4.0-4.1","4.2-4.3","5.0-5.1","6.0-6.1","7.0",null,null],current_version:""},op_mini:{browser:"Opera Mini",abbr:"O.Mini",prefix:"o",type:"mobile",usage_global:{"5.0-7.0":4.58374},versions:[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"5.0-7.0",null,null],current_version:""},android:{browser:"Android Browser",abbr:"And.",prefix:"webkit",type:"mobile",usage_global:{2.1:.0251229,2.2:.0854178,2.3:1.32146,3:.00502458,4:.994867,4.1:1.87417,"4.2-4.3":.743638,4.4:0},versions:[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"2.1","2.2","2.3","3","4","4.1","4.2-4.3","4.4",null],current_version:""},op_mob:{browser:"Opera Mobile",abbr:"O.Mob",prefix:"o",type:"mobile",usage_global:{0:0,10:0,11.5:.00726525,12:.0363263,12.1:.101714},versions:[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"10",null,null,"11.5","12","12.1","0",null,null],current_version:"16",prefix_exceptions:{0:"webkit"}},bb:{browser:"Blackberry Browser",abbr:"BB",prefix:"webkit",type:"mobile",usage_global:{10:0,7:.141419},versions:[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"7","10",null,null],current_version:""},and_chr:{browser:"Chrome for Android",abbr:"Chr/And.",prefix:"webkit",type:"mobile",usage_global:{0:1.38176},versions:[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"0",null,null],current_version:"30"},and_ff:{browser:"Firefox for Android",abbr:"FF/And.",prefix:"moz",type:"mobile",usage_global:{0:.070956},versions:[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"0",null,null],current_version:"25"},ie_mob:{browser:"IE Mobile",abbr:"IE.Mob",prefix:"ms",type:"mobile",usage_global:{10:.205595},versions:[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"10",null,null],current_version:""}},statuses:{rec:"Recommendation",pr:"Proposed Recommendation",cr:"Candidate Recommendation",wd:"Working Draft",other:"Other",unoff:"Unofficial / Note"},cats:{CSS:["CSS","CSS2","CSS3"],HTML5:["Canvas","HTML5"],"JS API":["JS API"],Other:["PNG","Other","DOM"],SVG:["SVG"]},updated:1383587152,data:{"png-alpha":{title:"PNG alpha transparency",description:"Semi-transparent areas in PNG files",spec:"http://www.w3.org/TR/PNG/",status:"rec",links:[{url:"http://dillerdesign.com/experiment/DD_belatedPNG/",title:"Workaround for IE6"},{url:"http://en.wikipedia.org/wiki/Portable_Network_Graphics",title:"Wikipedia"}],categories:["PNG"],stats:{ie:{5.5:"n",6:"p",7:"y",8:"y",9:"y",10:"y",11:"y"},firefox:{2:"y",3:"y",3.5:"y",3.6:"y",4:"y",5:"y",6:"y",7:"y",8:"y",9:"y",10:"y",11:"y",12:"y",13:"y",14:"y",15:"y",16:"y",17:"y",18:"y",19:"y",20:"y",21:"y",22:"y",23:"y",24:"y",25:"y",26:"y",27:"y"},chrome:{4:"y",5:"y",6:"y",7:"y",8:"y",9:"y",10:"y",11:"y",12:"y",13:"y",14:"y",15:"y",16:"y",17:"y",18:"y",19:"y",20:"y",21:"y",22:"y",23:"y",24:"y",25:"y",26:"y",27:"y",28:"y",29:"y",30:"y",31:"y",32:"y"},safari:{3.1:"y",3.2:"y",4:"y",5:"y",5.1:"y",6:"y",6.1:"y",7:"y"},opera:{9:"y","9.5-9.6":"y","10.0-10.1":"y",10.5:"y",10.6:"y",11:"y",11.1:"y",11.5:"y",11.6:"y",12:"y",12.1:"y",15:"y",16:"y",17:"y",18:"y"},ios_saf:{3.2:"y","4.0-4.1":"y","4.2-4.3":"y","5.0-5.1":"y","6.0-6.1":"y","7.0":"y"},op_mini:{"5.0-7.0":"y"},android:{2.1:"y",2.2:"y",2.3:"y",3:"y",4:"y",4.1:"y","4.2-4.3":"y",4.4:"y"},bb:{7:"y",10:"y"},op_mob:{10:"y",11:"y",11.1:"y",11.5:"y",12:"y",12.1:"y",0:"y"},and_chr:{0:"y"},and_ff:{0:"y"},ie_mob:{10:"y"}},notes:"IE6 does support full transparency in 8-bit PNGs, which can sometimes be an alternative to 24-bit PNGs.",usage_perc_y:94.36,usage_perc_a:0,ucprefix:!1,parent:"",keywords:""},apng:{title:"Animated PNG (APNG)",description:"Like animated GIFs, but allowing 24-bit colors and alpha transparency",spec:"https://wiki.mozilla.org/APNG_Specification",status:"unoff",links:[{url:"http://en.wikipedia.org/wiki/APNG",title:"Wikipedia"},{url:"https://github.com/davidmz/apng-canvas",title:"Polyfill using canvas"},{url:"https://chrome.google.com/webstore/detail/ehkepjiconegkhpodgoaeamnpckdbblp",title:"Chrome extension providing support"},{url:"http://www.truekolor.net/learn-how-to-create-an-animated-png/",title:"APNG tutorial"}],categories:["PNG"],stats:{ie:{5.5:"n",6:"n",7:"n",8:"n",9:"n",10:"n",11:"n"},firefox:{2:"n",3:"y",3.5:"y",3.6:"y",4:"y",5:"y",6:"y",7:"y",8:"y",9:"y",10:"y",11:"y",12:"y",13:"y",14:"y",15:"y",16:"y",17:"y",18:"y",19:"y",20:"y",21:"y",22:"y",23:"y",24:"y",25:"y",26:"y",27:"y"},chrome:{4:"n",5:"n",6:"n",7:"n",8:"n",9:"n",10:"n",11:"n",12:"n",13:"n",14:"n",15:"n",16:"n",17:"n",18:"n",19:"n",20:"n",21:"n",22:"n",23:"n",24:"n",25:"n",26:"n",27:"n",28:"n",29:"n",30:"n",31:"n",32:"n"},safari:{3.1:"n",3.2:"n",4:"n",5:"n",5.1:"n",6:"n",6.1:"n",7:"n"},opera:{9:"n","9.5-9.6":"y","10.0-10.1":"y",10.5:"y",10.6:"y",11:"y",11.1:"y",11.5:"y",11.6:"y",12:"y",12.1:"y",15:"n",16:"n",17:"n",18:"n"},ios_saf:{3.2:"n","4.0-4.1":"n","4.2-4.3":"n","5.0-5.1":"n","6.0-6.1":"n","7.0":"n"},op_mini:{"5.0-7.0":"n"},android:{2.1:"n",2.2:"n",2.3:"n",3:"n",4:"n",4.1:"n","4.2-4.3":"n",4.4:"n"},bb:{7:"n",10:"n"},op_mob:{10:"y",11:"y",11.1:"y",11.5:"y",12:"y",12.1:"y",0:"n"},and_chr:{0:"n"},and_ff:{0:"y"},ie_mob:{10:"n"}},notes:"Where support for APNG is missing, only the first frame is displayed",usage_perc_y:16.19,usage_perc_a:0,ucprefix:!1,parent:"",keywords:""},video:{title:"Video element",description:"Method of playing videos on webpages (without requiring a plug-in)",spec:"http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#video",status:"wd",links:[{url:"https://raw.github.com/phiggins42/has.js/master/detect/video.js#video",title:"has.js test"},{url:"http://webmproject.org",title:"WebM format information"},{url:"http://docs.webplatform.org/wiki/html/elements/video",title:"WebPlatform Docs"},{url:"http://camendesign.co.uk/code/video_for_everybody",title:"Video for Everybody"},{url:"http://diveinto.org/html5/video.html",title:"Video on the Web - includes info on Android support"},{url:"http://dev.opera.com/articles/view/everything-you-need-to-know-about-html5-video-and-audio/",title:"Detailed article on video/audio elements"}],categories:["HTML5"],stats:{ie:{5.5:"n",6:"n",7:"n",8:"n",9:"y",10:"y",11:"y"},firefox:{2:"n",3:"n",3.5:"y",3.6:"y",4:"y",5:"y",6:"y",7:"y",8:"y",9:"y",10:"y",11:"y",12:"y",13:"y",14:"y",15:"y",16:"y",17:"y",18:"y",19:"y",20:"y",21:"y",22:"y",23:"y",24:"y",25:"y",26:"y",27:"y"},chrome:{4:"y",5:"y",6:"y",7:"y",8:"y",9:"y",10:"y",11:"y",12:"y",13:"y",14:"y",15:"y",16:"y",17:"y",18:"y",19:"y",20:"y",21:"y",22:"y",23:"y",24:"y",25:"y",26:"y",27:"y",28:"y",29:"y",30:"y",31:"y",32:"y"},safari:{3.1:"n",3.2:"n",4:"y",5:"y",5.1:"y",6:"y",6.1:"y",7:"y"},opera:{9:"n","9.5-9.6":"n","10.0-10.1":"n",10.5:"y",10.6:"y",11:"y",11.1:"y",11.5:"y",11.6:"y",12:"y",12.1:"y",15:"y",16:"y",17:"y",18:"y"},ios_saf:{3.2:"y","4.0-4.1":"y","4.2-4.3":"y","5.0-5.1":"y","6.0-6.1":"y","7.0":"y"},op_mini:{"5.0-7.0":"n"},android:{2.1:"a",2.2:"a",2.3:"y",3:"y",4:"y",4.1:"y","4.2-4.3":"y",4.4:"y"},bb:{7:"y",10:"y"},op_mob:{10:"n",11:"y",11.1:"y",11.5:"y",12:"y",12.1:"y",0:"y"},and_chr:{0:"y"},and_ff:{0:"y"},ie_mob:{10:"y"}},notes:'Different browsers have support for different video formats, see sub-features for details. \r\n\r\nThe Android browser (before 2.3) requires <a href="http://www.broken-links.com/2010/07/08/making-html5-video-work-on-android-phones/">specific handling</a> to run the video element.',usage_perc_y:80.71,usage_perc_a:.11,ucprefix:!1,parent:"",keywords:"<video>"},audio:{title:"Audio element",description:"Method of playing sound on webpages (without requiring a plug-in)",spec:"http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#audio",
1
+ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var o;"undefined"!=typeof window?o=window:"undefined"!=typeof global?o=global:"undefined"!=typeof self&&(o=self),o.emmetCodeMirror=e()}}(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){"use strict";function posToIndex(cm,pos){arguments.length>2&&"object"!=typeof pos&&(pos={line:arguments[1],ch:arguments[2]});return cm.indexFromPos(pos)}function indexToPos(cm,ix){return cm.posFromIndex(ix)}var _interopRequire=function(obj){return obj&&obj.__esModule?obj["default"]:obj},_createClass=function(){function defineProperties(target,props){for(var key in props){var prop=props[key];prop.configurable=!0;prop.value&&(prop.writable=!0)}Object.defineProperties(target,props)}return function(Constructor,protoProps,staticProps){protoProps&&defineProperties(Constructor.prototype,protoProps);staticProps&&defineProperties(Constructor,staticProps);return Constructor}}(),_classCallCheck=function(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")};Object.defineProperty(exports,"__esModule",{value:!0});var emmet=_interopRequire(require("./emmet")),modeMap={"text/html":"html","application/xml":"xml","text/xsl":"xsl","text/css":"css","text/x-less":"less","text/x-scss":"scss","text/x-sass":"sass"};exports.modeMap=modeMap;var EmmetEditor=function(){function EmmetEditor(ctx){var selIndex=void 0===arguments[1]?0:arguments[1];_classCallCheck(this,EmmetEditor);this.context=ctx;this.selectionIndex=selIndex||0}_createClass(EmmetEditor,{selectionList:{value:function(){var cm=this.context;return cm.listSelections().map(function(sel){var anchor=posToIndex(cm,sel.anchor),head=posToIndex(cm,sel.head);return{start:Math.min(anchor,head),end:Math.max(anchor,head)}})}},getCaretPos:{value:function(){return this.getSelectionRange().start}},setCaretPos:{value:function(pos){this.createSelection(pos)}},getSelectionRange:{value:function(){return this.selectionList()[this.selectionIndex]}},createSelection:{value:function(start,end){"undefined"==typeof end&&(end=start);var sels=this.selectionList(),cm=this.context;sels[this.selectionIndex]={start:start,end:end};this.context.setSelections(sels.map(function(sel){return{head:indexToPos(cm,sel.start),anchor:indexToPos(cm,sel.end)}}))}},getSelection:{value:function(){var sel=this.getSelectionRange();sel.start=indexToPos(this.context,sel.start);sel.end=indexToPos(this.context,sel.end);return this.context.getRange(sel.start,sel.end)}},getCurrentLineRange:{value:function(){var caret=indexToPos(this.context,this.getCaretPos());return{start:posToIndex(this.context,caret.line,0),end:posToIndex(this.context,caret.line,this.context.getLine(caret.line).length)}}},getCurrentLine:{value:function(){var caret=indexToPos(this.context,this.getCaretPos());return this.context.getLine(caret.line)||""}},replaceContent:{value:function(value,start,end,noIndent){"undefined"==typeof end&&(end="undefined"==typeof start?this.getContent().length:start);"undefined"==typeof start&&(start=0);value=this.normalize(value);noIndent||(value=emmet.utils.common.padString(value,emmet.utils.common.getLinePaddingFromPosition(this.getContent(),start)));var tabstopData=emmet.tabStops.extract(value,{escape:function(ch){return ch}});value=tabstopData.text;var firstTabStop=tabstopData.tabstops[0]||{start:value.length,end:value.length};firstTabStop.start+=start;firstTabStop.end+=start;this.context.replaceRange(value,indexToPos(this.context,start),indexToPos(this.context,end));this.createSelection(firstTabStop.start,firstTabStop.end)}},normalize:{value:function(str){var indent="\t",ctx=this.context;ctx.getOption("indentWithTabs")||(indent=emmet.utils.common.repeatString(" ",ctx.getOption("indentUnit")));return emmet.utils.editor.normalize(str,{indentation:indent})}},getContent:{value:function(){return this.context.getValue()}},getSyntax:{value:function(){var editor=this.context,mode=(editor.posFromIndex(this.getCaretPos()),editor.getModeAt(editor.getCursor())),syntax=mode.name;"xml"===syntax&&mode.configuration&&(syntax=mode.configuration);return syntax||emmet.utils.action.detectSyntax(this,syntax)}},getProfileName:{value:function(){return this.context.getOption("profile")?this.context.getOption("profile"):emmet.utils.action.detectProfile(this)}},prompt:{value:function(_prompt){var _promptWrapper=function(_x){return _prompt.apply(this,arguments)};_promptWrapper.toString=function(){return _prompt.toString()};return _promptWrapper}(function(title){return prompt(title)})},getFilePath:{value:function(){return location.href}},isValidSyntax:{value:function(){return emmet.resources.hasSyntax(this.getSyntax())}}});return EmmetEditor}();exports["default"]=EmmetEditor},{"./emmet":2}],2:[function(require,module,exports){"use strict";var _interopRequire=function(obj){return obj&&obj.__esModule?obj["default"]:obj},emmet=_interopRequire(require("emmet"));require("emmet/bundles/snippets");require("emmet/bundles/caniuse");module.exports=emmet},{emmet:39,"emmet/bundles/caniuse":3,"emmet/bundles/snippets":4}],3:[function(require,module,exports){var ciu=require("../lib/assets/caniuse"),db=require("../lib/caniuse.json");ciu.load(db,!0)},{"../lib/assets/caniuse":23,"../lib/caniuse.json":35}],4:[function(require,module,exports){var res=require("../lib/assets/resources"),snippets=require("../lib/snippets.json");res.setVocabulary(snippets,"system")},{"../lib/assets/resources":31,"../lib/snippets.json":68}],5:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function last(arr){return arr[arr.length-1]}function balanceHTML(editor,direction){var info=editorUtils.outputInfo(editor),content=info.content,sel=range(editor.getSelectionRange());lastMatch&&!lastMatch.range.equal(sel)&&(lastMatch=null);if(lastMatch&&sel.length())if("in"==direction){if("tag"==lastMatch.type&&!lastMatch.close)return!1;if(lastMatch.range.equal(lastMatch.outerRange))lastMatch.range=lastMatch.innerRange;else{var narrowed=utils.narrowToNonSpace(content,lastMatch.innerRange);lastMatch=htmlMatcher.find(content,narrowed.start+1);lastMatch&&lastMatch.range.equal(sel)&&lastMatch.outerRange.equal(sel)&&(lastMatch.range=lastMatch.innerRange)}}else if(!lastMatch.innerRange.equal(lastMatch.outerRange)&&lastMatch.range.equal(lastMatch.innerRange)&&sel.equal(lastMatch.range))lastMatch.range=lastMatch.outerRange;else{lastMatch=htmlMatcher.find(content,sel.start);lastMatch&&lastMatch.range.equal(sel)&&lastMatch.innerRange.equal(sel)&&(lastMatch.range=lastMatch.outerRange)}else lastMatch=htmlMatcher.find(content,sel.start);if(lastMatch){lastMatch.innerRange.equal(sel)&&(lastMatch.range=lastMatch.outerRange);if(!lastMatch.range.equal(sel)){editor.createSelection(lastMatch.range.start,lastMatch.range.end);return!0}}lastMatch=null;return!1}function rangesForCSSRule(rule,pos){var ranges=[rule.range(!0)];ranges.push(rule.valueRange(!0));var nestedSections=cssSections.nestedSectionsInRule(rule),items=rule.list();if(items.length||nestedSections.length){var start=Number.POSITIVE_INFINITY,end=-1;if(items.length){start=items[0].namePosition(!0);end=last(items).range(!0).end}if(nestedSections.length){nestedSections[0].start<start&&(start=nestedSections[0].start);last(nestedSections).end>end&&(end=last(nestedSections).end)}ranges.push(range.create2(start,end))}ranges=ranges.concat(nestedSections);var prop=cssEditTree.propertyFromPosition(rule,pos)||items[0];if(prop){ranges.push(prop.range(!0));var valueRange=prop.valueRange(!0);prop.end()||(valueRange._unterminated=!0);ranges.push(valueRange)}return ranges}function getCSSRanges(content,pos){var rule;if("string"==typeof content){var ruleRange=cssSections.matchEnclosingRule(content,pos);ruleRange&&(rule=cssEditTree.parse(ruleRange.substring(content),{offset:ruleRange.start}))}else rule=content;if(!rule)return null;var ranges=rangesForCSSRule(rule,pos);ranges=ranges.filter(function(item){return!!item.length});return utils.unique(ranges,function(item){return item.valueOf()})}function balanceCSS(editor,direction){var info=editorUtils.outputInfo(editor),content=info.content,sel=range(editor.getSelectionRange()),ranges=getCSSRanges(info.content,sel.start);if(!ranges&&sel.length())try{var rule=cssEditTree.parse(sel.substring(info.content),{offset:sel.start});ranges=getCSSRanges(rule,sel.start)}catch(e){}if(!ranges)return!1;ranges=range.sort(ranges,!0);var bestMatch=utils.find(ranges,function(r){return r.equal(sel)});bestMatch||(bestMatch=utils.find(ranges,function(r){return r._unterminated?r.include(sel.start):r.inside(sel.start)}));if(!bestMatch)return!1;var bestMatchIx=ranges.indexOf(bestMatch);bestMatch.equal(sel)&&(bestMatchIx+="out"==direction?1:-1);if(bestMatchIx<0||bestMatchIx>=ranges.length)if(bestMatchIx>=ranges.length&&"out"==direction){pos=bestMatch.start-1;var outerRanges=getCSSRanges(content,pos);outerRanges&&(bestMatch=last(outerRanges.filter(function(r){return r.inside(pos)})))}else bestMatch=null;else bestMatch=ranges[bestMatchIx];if(bestMatch){editor.createSelection(bestMatch.start,bestMatch.end);return!0}return!1}var htmlMatcher=require("../assets/htmlMatcher"),utils=require("../utils/common"),editorUtils=require("../utils/editor"),actionUtils=require("../utils/action"),range=require("../assets/range"),cssEditTree=require("../editTree/css"),cssSections=require("../utils/cssSections"),lastMatch=null;return{balance:function(editor,direction){direction=String((direction||"out").toLowerCase());var info=editorUtils.outputInfo(editor);return actionUtils.isSupportedCSS(info.syntax)?balanceCSS(editor,direction):balanceHTML(editor,direction)},balanceInwardAction:function(editor){return this.balance(editor,"in")},balanceOutwardAction:function(editor){return this.balance(editor,"out")},goToMatchingPairAction:function(editor){var content=String(editor.getContent()),caretPos=editor.getCaretPos();"<"==content.charAt(caretPos)&&caretPos++;var tag=htmlMatcher.tag(content,caretPos);if(tag&&tag.close){tag.open.range.inside(caretPos)?editor.setCaretPos(tag.close.range.start):editor.setCaretPos(tag.open.range.start);return!0}return!1}}})},{"../assets/htmlMatcher":26,"../assets/range":30,"../editTree/css":37,"../utils/action":70,"../utils/common":73,"../utils/cssSections":74,"../utils/editor":75}],6:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function startsWith(token,text,pos){pos=pos||0;return text.charAt(pos)==token.charAt(0)&&text.substr(pos,token.length)==token}function encodeToBase64(editor,imgPath,pos){var editorFile=editor.getFilePath(),defaultMimeType="application/octet-stream";if(null===editorFile)throw"You should save your file before using this action";var realImgPath=file.locateFile(editorFile,imgPath);if(null===realImgPath)throw"Can't find "+imgPath+" file";file.read(realImgPath,function(err,content){if(err)throw"Unable to read "+realImgPath+": "+err;var b64=base64.encode(String(content));if(!b64)throw"Can't encode file content to base64";b64="data:"+(actionUtils.mimeTypes[String(file.getExt(realImgPath))]||defaultMimeType)+";base64,"+b64;editor.replaceContent("$0"+b64,pos,pos+imgPath.length)});return!0}function decodeFromBase64(editor,data,pos){var filePath=String(editor.prompt("Enter path to file (absolute or relative)"));if(!filePath)return!1;var absPath=file.createPath(editor.getFilePath(),filePath);if(!absPath)throw"Can't save file";file.save(absPath,base64.decode(data.replace(/^data\:.+?;.+?,/,"")));editor.replaceContent("$0"+filePath,pos,pos+data.length);return!0}var file=require("../plugin/file"),base64=require("../utils/base64"),actionUtils=require("../utils/action"),editorUtils=require("../utils/editor");return{encodeDecodeDataUrlAction:function(editor){var data=String(editor.getSelection()),caretPos=editor.getCaretPos(),info=editorUtils.outputInfo(editor);if(!data)for(var m,text=info.content;caretPos-- >=0;){if(startsWith("src=",text,caretPos)){if(m=text.substr(caretPos).match(/^(src=(["'])?)([^'"<>\s]+)\1?/)){data=m[3];caretPos+=m[1].length}break}if(startsWith("url(",text,caretPos)){if(m=text.substr(caretPos).match(/^(url\((['"])?)([^'"\)\s]+)\1?/)){data=m[3];caretPos+=m[1].length}break}}return!!data&&(startsWith("data:",data)?decodeFromBase64(editor,data,caretPos):encodeToBase64(editor,data,caretPos))}}})},{"../plugin/file":63,"../utils/action":70,"../utils/base64":71,"../utils/editor":75}],7:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function findNewEditPoint(editor,inc,offset){function getLine(ix){for(var start=ix;start>=0;){var c=content.charAt(start);if("\n"==c||"\r"==c)break;start--}return content.substring(start,ix)}inc=inc||1;offset=offset||0;for(var curPoint=editor.getCaretPos()+offset,content=String(editor.getContent()),maxLen=content.length,nextPoint=-1,reEmptyLine=/^\s+$/;curPoint<=maxLen&&curPoint>=0;){curPoint+=inc;var curChar=content.charAt(curPoint),nextChar=content.charAt(curPoint+1),prevChar=content.charAt(curPoint-1);switch(curChar){case'"':case"'":nextChar==curChar&&"="==prevChar&&(nextPoint=curPoint+1);break;case">":"<"==nextChar&&(nextPoint=curPoint+1);break;case"\n":case"\r":reEmptyLine.test(getLine(curPoint-1))&&(nextPoint=curPoint)}if(nextPoint!=-1)break}return nextPoint}return{previousEditPointAction:function(editor,syntax,profile){var curPos=editor.getCaretPos(),newPoint=findNewEditPoint(editor,-1);newPoint==curPos&&(newPoint=findNewEditPoint(editor,-1,-2));if(newPoint!=-1){editor.setCaretPos(newPoint);return!0}return!1},nextEditPointAction:function(editor,syntax,profile){var newPoint=findNewEditPoint(editor,1);if(newPoint!=-1){editor.setCaretPos(newPoint);return!0}return!1}}})},{}],8:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){var actionUtils=require("../utils/action"),utils=require("../utils/common"),math=require("../utils/math"),range=require("../assets/range");return{evaluateMathAction:function(editor){var content=editor.getContent(),chars=".+-*/\\",sel=range(editor.getSelectionRange());sel.length()||(sel=actionUtils.findExpressionBounds(editor,function(ch){return utils.isNumeric(ch)||chars.indexOf(ch)!=-1}));if(sel&&sel.length()){var expr=sel.substring(content);expr=expr.replace(/([\d\.\-]+)\\([\d\.\-]+)/g,"round($1/$2)");try{var result=utils.prettifyNumber(math.evaluate(expr));editor.replaceContent(result,sel.start,sel.end);editor.setCaretPos(sel.start+result.length);return!0}catch(e){}}return!1}}})},{"../assets/range":30,"../utils/action":70,"../utils/common":73,"../utils/math":76}],9:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function findAbbreviation(editor){var r=range(editor.getSelectionRange()),content=String(editor.getContent());if(r.length())return r.substring(content);var curLine=editor.getCurrentLineRange();return actionUtils.extractAbbreviation(content.substring(curLine.start,r.start))}var handlerList=require("../assets/handlerList"),range=require("../assets/range"),prefs=require("../assets/preferences"),utils=require("../utils/common"),editorUtils=require("../utils/editor"),actionUtils=require("../utils/action"),cssGradient=require("../resolver/cssGradient"),parser=require("../parser/abbreviation"),handlers=handlerList.create();handlers.add(function(editor,syntax,profile){var caretPos=editor.getSelectionRange().end,abbr=findAbbreviation(editor);if(abbr){var content=parser.expand(abbr,{syntax:syntax,profile:profile,contextNode:actionUtils.captureContext(editor)});if(content){var replaceFrom=caretPos-abbr.length,replaceTo=caretPos,cssSyntaxes=prefs.getArray("css.syntaxes");if(cssSyntaxes&&~cssSyntaxes.indexOf(syntax)){var curContent=editor.getContent();";"==curContent.charAt(caretPos)&&";"==content.charAt(content.length-1)&&replaceTo++}editor.replaceContent(content,replaceFrom,replaceTo);return!0}}return!1},{order:-1});handlers.add(cssGradient.expandAbbreviationHandler.bind(cssGradient));return{expandAbbreviationAction:function(editor,syntax,profile){var args=utils.toArray(arguments),info=editorUtils.outputInfo(editor,syntax,profile);args[1]=info.syntax;args[2]=info.profile;return handlers.exec(!1,args)},expandAbbreviationWithTabAction:function(editor,syntax,profile){var sel=editor.getSelection(),indent="\t";if(sel){var selRange=range(editor.getSelectionRange()),content=utils.padString(sel,indent);editor.replaceContent(indent+"${0}",editor.getCaretPos());var replaceRange=range(editor.getCaretPos(),selRange.length());editor.replaceContent(content,replaceRange.start,replaceRange.end,!0);editor.createSelection(replaceRange.start,replaceRange.start+content.length);return!0}this.expandAbbreviationAction(editor,syntax,profile)||editor.replaceContent(indent,editor.getCaretPos());return!0},_defaultHandler:function(editor,syntax,profile){var caretPos=editor.getSelectionRange().end,abbr=this.findAbbreviation(editor);if(abbr){var ctx=actionUtils.captureContext(editor),content=parser.expand(abbr,syntax,profile,ctx);if(content){editor.replaceContent(content,caretPos-abbr.length,caretPos);return!0}}return!1},addHandler:function(fn,options){handlers.add(fn,options)},removeHandler:function(fn){handlers.remove(fn)},findAbbreviation:findAbbreviation}})},{"../assets/handlerList":25,"../assets/preferences":28,"../assets/range":30,"../parser/abbreviation":55,"../resolver/cssGradient":65,"../utils/action":70,"../utils/common":73,"../utils/editor":75}],10:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function intLength(num){num=num.replace(/^\-/,"");return~num.indexOf(".")?num.split(".")[0].length:num.length}var utils=require("../utils/common"),actionUtils=require("../utils/action");return{increment01Action:function(editor){return this.incrementNumber(editor,.1)},increment1Action:function(editor){return this.incrementNumber(editor,1)},increment10Action:function(editor){return this.incrementNumber(editor,10)},decrement01Action:function(editor){return this.incrementNumber(editor,-.1)},decrement1Action:function(editor){return this.incrementNumber(editor,-1)},decrement10Action:function(editor){return this.incrementNumber(editor,-10)},incrementNumber:function(editor,step){var hasSign=!1,hasDecimal=!1,r=actionUtils.findExpressionBounds(editor,function(ch,pos,content){return!!utils.isNumeric(ch)||("."==ch?!!utils.isNumeric(content.charAt(pos+1))&&(!hasDecimal&&(hasDecimal=!0)):"-"==ch&&(!hasSign&&(hasSign=!0)))});if(r&&r.length()){var strNum=r.substring(String(editor.getContent())),num=parseFloat(strNum);if(!isNaN(num)){num=utils.prettifyNumber(num+step);if(/^(\-?)0+[1-9]/.test(strNum)){var minus="";if(RegExp.$1){minus="-";num=num.substring(1)}var parts=num.split(".");parts[0]=utils.zeroPadString(parts[0],intLength(strNum));num=minus+parts.join(".")}editor.replaceContent(num,r.start,r.end);editor.createSelection(r.start,r.start+num.length);return!0}}return!1}}})},{"../utils/action":70,"../utils/common":73}],11:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){var prefs=require("../assets/preferences"),utils=require("../utils/common"),htmlMatcher=(require("../assets/resources"),require("../assets/htmlMatcher")),editorUtils=require("../utils/editor"),xmlSyntaxes=["html","xml","xsl"];prefs.define("css.closeBraceIndentation","\n","Indentation before closing brace of CSS rule. Some users prefere indented closing brace of CSS rule for better readability. This preference’s value will be automatically inserted before closing brace when user adds newline in newly created CSS rule (e.g. when “Insert formatted linebreak” action will be performed in CSS file). If you’re such user, you may want to write put a value like <code>\\n\\t</code> in this preference.");return{insertLineBreakAction:function(editor){if(!this.insertLineBreakOnlyAction(editor)){for(var ch,curPadding=editorUtils.getCurrentLinePadding(editor),content=String(editor.getContent()),caretPos=editor.getCaretPos(),len=content.length,nl="\n",lineRange=editor.getCurrentLineRange(),nextPadding="",i=lineRange.end+1;i<len;i++){ch=content.charAt(i);if(" "!=ch&&"\t"!=ch)break;nextPadding+=ch}nextPadding.length>curPadding.length?editor.replaceContent(nl+nextPadding,caretPos,caretPos,!0):editor.replaceContent(nl,caretPos)}return!0},insertLineBreakOnlyAction:function(editor){var info=editorUtils.outputInfo(editor),caretPos=editor.getCaretPos(),nl="\n",pad="\t";if(~xmlSyntaxes.indexOf(info.syntax)){var tag=htmlMatcher.tag(info.content,caretPos);if(tag&&!tag.innerRange.length()){editor.replaceContent(nl+pad+utils.getCaretPlaceholder()+nl,caretPos);return!0}}else if("css"==info.syntax){var content=info.content;if(caretPos&&"{"==content.charAt(caretPos-1)){var append=prefs.get("css.closeBraceIndentation"),hasCloseBrace="}"==content.charAt(caretPos);if(!hasCloseBrace)for(var ch,i=caretPos,il=content.length;i<il;i++){ch=content.charAt(i);if("{"==ch)break;if("}"==ch){append="";hasCloseBrace=!0;break}}hasCloseBrace||(append+="}");var insValue=nl+pad+utils.getCaretPlaceholder()+append;editor.replaceContent(insValue,caretPos);return!0}}return!1}}})},{"../assets/htmlMatcher":26,"../assets/preferences":28,"../assets/resources":31,"../utils/common":73,"../utils/editor":75}],12:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function addAction(name,fn,options){name=name.toLowerCase();options=options||{};"string"==typeof options&&(options={label:options});options.label||(options.label=humanizeActionName(name));actions[name]={name:name,fn:fn,options:options}}function humanizeActionName(name){return utils.trim(name.charAt(0).toUpperCase()+name.substring(1).replace(/_[a-z]/g,function(str){return" "+str.charAt(1).toUpperCase()}))}var utils=require("../utils/common"),actions={},actionModules={base64:require("./base64"),editPoints:require("./editPoints"),evaluateMath:require("./evaluateMath"),expandAbbreviation:require("./expandAbbreviation"),incrementDecrement:require("./incrementDecrement"),lineBreaks:require("./lineBreaks"),balance:require("./balance"),mergeLines:require("./mergeLines"),reflectCSSValue:require("./reflectCSSValue"),removeTag:require("./removeTag"),selectItem:require("./selectItem"),selectLine:require("./selectLine"),splitJoinTag:require("./splitJoinTag"),toggleComment:require("./toggleComment"),updateImageSize:require("./updateImageSize"),wrapWithAbbreviation:require("./wrapWithAbbreviation"),updateTag:require("./updateTag")},bind=function(name,method){var m=actionModules[name];return m[method].bind(m)};addAction("encode_decode_data_url",bind("base64","encodeDecodeDataUrlAction"),"Encode\\Decode data:URL image");addAction("prev_edit_point",bind("editPoints","previousEditPointAction"),"Previous Edit Point");addAction("next_edit_point",bind("editPoints","nextEditPointAction"),"Next Edit Point");addAction("evaluate_math_expression",bind("evaluateMath","evaluateMathAction"),"Numbers/Evaluate Math Expression");addAction("expand_abbreviation_with_tab",bind("expandAbbreviation","expandAbbreviationWithTabAction"),{hidden:!0});addAction("expand_abbreviation",bind("expandAbbreviation","expandAbbreviationAction"),"Expand Abbreviation");addAction("insert_formatted_line_break_only",bind("lineBreaks","insertLineBreakOnlyAction"),{hidden:!0});addAction("insert_formatted_line_break",bind("lineBreaks","insertLineBreakAction"),{hidden:!0});addAction("balance_inward",bind("balance","balanceInwardAction"),"Balance (inward)");addAction("balance_outward",bind("balance","balanceOutwardAction"),"Balance (outward)");addAction("matching_pair",bind("balance","goToMatchingPairAction"),"HTML/Go To Matching Tag Pair");addAction("merge_lines",bind("mergeLines","mergeLinesAction"),"Merge Lines");addAction("reflect_css_value",bind("reflectCSSValue","reflectCSSValueAction"),"CSS/Reflect Value");addAction("remove_tag",bind("removeTag","removeTagAction"),"HTML/Remove Tag");addAction("select_next_item",bind("selectItem","selectNextItemAction"),"Select Next Item");addAction("select_previous_item",bind("selectItem","selectPreviousItemAction"),"Select Previous Item");addAction("split_join_tag",bind("splitJoinTag","splitJoinTagAction"),"HTML/Split\\Join Tag Declaration");addAction("toggle_comment",bind("toggleComment","toggleCommentAction"),"Toggle Comment");addAction("update_image_size",bind("updateImageSize","updateImageSizeAction"),"Update Image Size");addAction("wrap_with_abbreviation",bind("wrapWithAbbreviation","wrapWithAbbreviationAction"),"Wrap With Abbreviation");addAction("update_tag",bind("updateTag","updateTagAction"),"HTML/Update Tag");[1,-1,10,-10,.1,-.1].forEach(function(num){var prefix=num>0?"increment":"decrement",suffix=String(Math.abs(num)).replace(".","").substring(0,2),actionId=prefix+"_number_by_"+suffix,actionMethod=prefix+suffix+"Action",actionLabel="Numbers/"+prefix.charAt(0).toUpperCase()+prefix.substring(1)+" number by "+Math.abs(num);addAction(actionId,bind("incrementDecrement",actionMethod),actionLabel)});return{add:addAction,get:function(name){return actions[name.toLowerCase()]},run:function(name,args){Array.isArray(args)||(args=utils.toArray(arguments,1));var action=this.get(name);if(!action)throw new Error('Action "'+name+'" is not defined');return action.fn.apply(action,args)},getAll:function(){return actions},getList:function(){var all=this.getAll();return Object.keys(all).map(function(key){return all[key]})},getMenu:function(skipActions){var result=[];skipActions=skipActions||[];this.getList().forEach(function(action){if(!action.options.hidden&&!~skipActions.indexOf(action.name)){var actionName=humanizeActionName(action.name),ctx=result;if(action.options.label){var parts=action.options.label.split("/");actionName=parts.pop();for(var menuName,submenu;menuName=parts.shift();){submenu=utils.find(ctx,function(item){return"submenu"==item.type&&item.name==menuName});if(!submenu){submenu={name:menuName,type:"submenu",items:[]};ctx.push(submenu)}ctx=submenu.items}}ctx.push({type:"action",name:action.name,label:actionName})}});return result},getActionNameForMenuTitle:function(title,menu){return utils.find(menu||this.getMenu(),function(val){return"action"!=val.type?this.getActionNameForMenuTitle(title,val.items):val.label==title||val.name==title?val.name:void 0},this)}}})},{"../utils/common":73,"./balance":5,"./base64":6,"./editPoints":7,"./evaluateMath":8,"./expandAbbreviation":9,"./incrementDecrement":10,"./lineBreaks":11,"./mergeLines":13,"./reflectCSSValue":14,"./removeTag":15,"./selectItem":16,"./selectLine":17,"./splitJoinTag":18,"./toggleComment":19,"./updateImageSize":20,"./updateTag":21,"./wrapWithAbbreviation":22}],13:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){var htmlMatcher=require("../assets/htmlMatcher"),utils=require("../utils/common"),editorUtils=require("../utils/editor"),range=require("../assets/range");return{mergeLinesAction:function(editor){var info=editorUtils.outputInfo(editor),selection=range(editor.getSelectionRange());if(!selection.length()){var pair=htmlMatcher.find(info.content,editor.getCaretPos());pair&&(selection=pair.outerRange)}if(selection.length()){for(var text=selection.substring(info.content),lines=utils.splitByLines(text),i=1;i<lines.length;i++)lines[i]=lines[i].replace(/^\s+/,"");text=lines.join("").replace(/\s{2,}/," ");var textLen=text.length;text=utils.escapeText(text);editor.replaceContent(text,selection.start,selection.end);editor.createSelection(selection.start,selection.start+textLen);return!0}return!1}}})},{"../assets/htmlMatcher":26,"../assets/range":30,"../utils/common":73,"../utils/editor":75}],14:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function doCSSReflection(editor){var outputInfo=editorUtils.outputInfo(editor),caretPos=editor.getCaretPos(),cssRule=cssEditTree.parseFromPosition(outputInfo.content,caretPos);if(cssRule){var property=cssRule.itemFromPosition(caretPos,!0);if(property){var oldRule=cssRule.source,offset=cssRule.options.offset,caretDelta=caretPos-offset-property.range().start;handlers.exec(!1,[property]);return oldRule!==cssRule.source?{data:cssRule.source,start:offset,end:offset+oldRule.length,caret:offset+property.range().start+caretDelta}:void 0}}}function getReflectedCSSName(name){name=cssEditTree.baseName(name);var m,vendorPrefix="^(?:\\-\\w+\\-)?";return"opacity"!=name&&"filter"!=name||!prefs.get("css.reflect.oldIEOpacity")?(m=name.match(/^border-radius-(top|bottom)(left|right)/))?new RegExp(vendorPrefix+"(?:"+name+"|border-"+m[1]+"-"+m[2]+"-radius)$"):(m=name.match(/^border-(top|bottom)-(left|right)-radius/))?new RegExp(vendorPrefix+"(?:"+name+"|border-radius-"+m[1]+m[2]+")$"):new RegExp(vendorPrefix+name+"$"):new RegExp(vendorPrefix+"(?:opacity|filter)$")}function reflectValueParts(name,value){var reVendor=/^\-(\w+)\-/,propPrefix=reVendor.test(name)?RegExp.$1.toLowerCase():"",parts=cssEditTree.findParts(value);parts.reverse();parts.forEach(function(part){var partValue=part.substring(value).replace(reVendor,""),prefixes=cssResolver.vendorPrefixes(partValue);if(prefixes){propPrefix&&~prefixes.indexOf(propPrefix)&&(partValue="-"+propPrefix+"-"+partValue);value=utils.replaceSubstring(value,partValue,part)}});return value}function reflectValue(donor,receiver){var value=getReflectedValue(donor.name(),donor.value(),receiver.name(),receiver.value());value=reflectValueParts(receiver.name(),value);receiver.value(value)}function getReflectedValue(curName,curValue,refName,refValue){curName=cssEditTree.baseName(curName);refName=cssEditTree.baseName(refName);if("opacity"==curName&&"filter"==refName)return refValue.replace(/opacity=[^)]*/i,"opacity="+Math.floor(100*parseFloat(curValue)));if("filter"==curName&&"opacity"==refName){var m=curValue.match(/opacity=([^)]*)/i);return m?utils.prettifyNumber(parseInt(m[1],10)/100):refValue}return curValue}var handlerList=require("../assets/handlerList"),prefs=require("../assets/preferences"),cssResolver=require("../resolver/css"),cssEditTree=require("../editTree/css"),utils=require("../utils/common"),actionUtils=require("../utils/action"),editorUtils=require("../utils/editor"),cssGradient=require("../resolver/cssGradient");prefs.define("css.reflect.oldIEOpacity",!1,"Support IE6/7/8 opacity notation, e.g. <code>filter:alpha(opacity=...)</code>.\t\tNote that CSS3 and SVG also provides <code>filter</code> property so this option is disabled by default.");
2
+ var handlers=handlerList.create();module=module||{};module.exports={reflectCSSValueAction:function(editor){return"css"==editor.getSyntax()&&actionUtils.compoundUpdate(editor,doCSSReflection(editor))},_defaultHandler:function(property){var reName=getReflectedCSSName(property.name());property.parent.list().forEach(function(p){reName.test(p.name())&&reflectValue(property,p)})},addHandler:function(fn,options){handlers.add(fn,options)},removeHandler:function(fn){handlers.remove(fn)}};handlers.add(module.exports._defaultHandler.bind(module.exports),{order:-1});handlers.add(cssGradient.reflectValueHandler.bind(cssGradient));return module.exports})},{"../assets/handlerList":25,"../assets/preferences":28,"../editTree/css":37,"../resolver/css":64,"../resolver/cssGradient":65,"../utils/action":70,"../utils/common":73,"../utils/editor":75}],15:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){var utils=require("../utils/common"),editorUtils=require("../utils/editor"),htmlMatcher=require("../assets/htmlMatcher");return{removeTagAction:function(editor){var info=editorUtils.outputInfo(editor),tag=htmlMatcher.tag(info.content,editor.getCaretPos());if(tag){if(tag.close){var tagContentRange=utils.narrowToNonSpace(info.content,tag.innerRange),startLineBounds=utils.findNewlineBounds(info.content,tagContentRange.start),startLinePad=utils.getLinePadding(startLineBounds.substring(info.content)),tagContent=tagContentRange.substring(info.content);tagContent=utils.unindentString(tagContent,startLinePad);editor.replaceContent(utils.getCaretPlaceholder()+utils.escapeText(tagContent),tag.outerRange.start,tag.outerRange.end)}else editor.replaceContent(utils.getCaretPlaceholder(),tag.range.start,tag.range.end);return!0}return!1}}})},{"../assets/htmlMatcher":26,"../utils/common":73,"../utils/editor":75}],16:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function findItem(editor,isBackward,extractFn,rangeFn){for(var itemRange,rng,content=editorUtils.outputInfo(editor).content,contentLength=content.length,prevRange=range(-1,0),sel=range(editor.getSelectionRange()),searchPos=sel.start,loop=1e5;searchPos>=0&&searchPos<contentLength&&--loop>0;){if(itemRange=extractFn(content,searchPos,isBackward)){if(prevRange.equal(itemRange))break;prevRange=itemRange.clone();rng=rangeFn(itemRange.substring(content),itemRange.start,sel.clone());if(rng){editor.createSelection(rng.start,rng.end);return!0}searchPos=isBackward?itemRange.start:itemRange.end-1}searchPos+=isBackward?-1:1}return!1}function findNextHTMLItem(editor){var isFirst=!0;return findItem(editor,!1,function(content,searchPos){if(isFirst){isFirst=!1;return findOpeningTagFromPosition(content,searchPos)}return getOpeningTagFromPosition(content,searchPos)},function(tag,offset,selRange){return getRangeForHTMLItem(tag,offset,selRange,!1)})}function findPrevHTMLItem(editor){return findItem(editor,!0,getOpeningTagFromPosition,function(tag,offset,selRange){return getRangeForHTMLItem(tag,offset,selRange,!0)})}function makePossibleRangesHTML(source,tokens,offset){offset=offset||0;var attrValueRange,tagName,result=[],attrStart=-1,attrName="",attrValue="";tokens.forEach(function(tok){switch(tok.type){case"tag":tagName=source.substring(tok.start,tok.end);/^<[\w\:\-]/.test(tagName)&&result.push(range({start:tok.start+1,end:tok.end}));break;case"attribute":attrStart=tok.start;attrName=source.substring(tok.start,tok.end);break;case"string":result.push(range(attrStart,tok.end-attrStart));attrValueRange=range(tok);attrValue=attrValueRange.substring(source);isQuote(attrValue.charAt(0))&&attrValueRange.start++;isQuote(attrValue.charAt(attrValue.length-1))&&attrValueRange.end--;result.push(attrValueRange);"class"==attrName&&(result=result.concat(classNameRanges(attrValueRange.substring(source),attrValueRange.start)))}});result=result.filter(function(item){if(item.length()){item.shift(offset);return!0}});return utils.unique(result,function(item){return item.toString()})}function classNameRanges(className,offset){offset=offset||0;var result=[],stream=stringStream.create(className);stream.eatSpace();stream.start=stream.pos;for(var ch;ch=stream.next();)if(/[\s\u00a0]/.test(ch)){result.push(range(stream.start+offset,stream.pos-stream.start-1));stream.eatSpace();stream.start=stream.pos}result.push(range(stream.start+offset,stream.pos-stream.start));return result}function getRangeForHTMLItem(tag,offset,selRange,isBackward){var ranges=makePossibleRangesHTML(tag,xmlParser.parse(tag),offset);isBackward&&ranges.reverse();var curRange=utils.find(ranges,function(r){return r.equal(selRange)});if(curRange){var ix=ranges.indexOf(curRange);return ix<ranges.length-1?ranges[ix+1]:null}if(isBackward)return utils.find(ranges,function(r){return r.start<selRange.start});if(!curRange){var matchedRanges=ranges.filter(function(r){return r.inside(selRange.end)});if(matchedRanges.length>1)return matchedRanges[1]}return utils.find(ranges,function(r){return r.end>selRange.end})}function findOpeningTagFromPosition(html,pos){for(var tag;pos>=0;){if(tag=getOpeningTagFromPosition(html,pos))return tag;pos--}return null}function getOpeningTagFromPosition(html,pos){var m;if("<"==html.charAt(pos)&&(m=html.substring(pos,html.length).match(startTag)))return range(pos,m[0])}function isQuote(ch){return'"'==ch||"'"==ch}function findInnerRanges(rule){var ranges=[rule.nameRange(!0)],nestedSections=cssSections.nestedSectionsInRule(rule);nestedSections.forEach(function(section){ranges.push(range.create2(section.start,section._selectorEnd))});rule.list().forEach(function(property){ranges=ranges.concat(makePossibleRangesCSS(property))});ranges=range.sort(ranges);ranges=ranges.filter(function(item){return!!item.length()});return utils.unique(ranges,function(item){return item.toString()})}function makePossibleRangesCSS(property){var valueRange=property.valueRange(!0),result=[property.range(!0),valueRange],value=property.value();property.valueParts().forEach(function(r){var clone=r.clone();result.push(clone.shift(valueRange.start));var stream=stringStream.create(r.substring(value));if(stream.match(/^[\w\-]+\(/,!0)){stream.start=stream.pos;stream.backUp(1);stream.skipToPair("(",")");stream.backUp(1);var fnBody=stream.current();result.push(range(clone.start+stream.start,fnBody));cssEditTree.findParts(fnBody).forEach(function(part){result.push(range(clone.start+stream.start+part.start,part.substring(fnBody)))})}});return result}function matchedRangeForCSSProperty(rule,selRange,isBackward){var ranges=findInnerRanges(rule);isBackward&&ranges.reverse();var r=utils.find(ranges,function(item){return item.equal(selRange)});if(r)return ranges[ranges.indexOf(r)+1];var nested=ranges.filter(function(item){return item.inside(selRange.end)});if(nested.length)return nested.sort(function(a,b){return a.length()-b.length()})[0];r=utils.find(ranges,isBackward?function(item){return item.end<selRange.start}:function(item){return item.end>selRange.start});r||(r=ranges[0]);return r}function findNextCSSItem(editor){return findItem(editor,!1,cssSections.locateRule.bind(cssSections),getRangeForNextItemInCSS)}function findPrevCSSItem(editor){return findItem(editor,!0,cssSections.locateRule.bind(cssSections),getRangeForPrevItemInCSS)}function getRangeForNextItemInCSS(rule,offset,selRange){var tree=cssEditTree.parse(rule,{offset:offset});return matchedRangeForCSSProperty(tree,selRange,!1)}function getRangeForPrevItemInCSS(rule,offset,selRange){var tree=cssEditTree.parse(rule,{offset:offset});return matchedRangeForCSSProperty(tree,selRange,!0)}var range=require("../assets/range"),utils=require("../utils/common"),editorUtils=require("../utils/editor"),actionUtils=require("../utils/action"),stringStream=require("../assets/stringStream"),xmlParser=require("../parser/xml"),cssEditTree=require("../editTree/css"),cssSections=require("../utils/cssSections"),startTag=/^<([\w\:\-]+)((?:\s+[\w\-:]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/;return{selectNextItemAction:function(editor){return actionUtils.isSupportedCSS(editor.getSyntax())?findNextCSSItem(editor):findNextHTMLItem(editor)},selectPreviousItemAction:function(editor){return actionUtils.isSupportedCSS(editor.getSyntax())?findPrevCSSItem(editor):findPrevHTMLItem(editor)}}})},{"../assets/range":30,"../assets/stringStream":32,"../editTree/css":37,"../parser/xml":62,"../utils/action":70,"../utils/common":73,"../utils/cssSections":74,"../utils/editor":75}],17:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){return{selectLineAction:function(editor){var range=editor.getCurrentLineRange();editor.createSelection(range.start,range.end);return!0}}})},{}],18:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function joinTag(editor,profile,tag){var slash=profile.selfClosing()||" /",content=tag.open.range.substring(tag.source).replace(/\s*>$/,slash+">"),caretPos=editor.getCaretPos();content.length+tag.outerRange.start<caretPos&&(caretPos=content.length+tag.outerRange.start);content=utils.escapeText(content);editor.replaceContent(content,tag.outerRange.start,tag.outerRange.end);editor.setCaretPos(caretPos);return!0}function splitTag(editor,profile,tag){var caretPos=editor.getCaretPos(),tagContent=profile.tag_nl===!0?"\n\t\n":"",content=tag.outerContent().replace(/\s*\/>$/,">");caretPos=tag.outerRange.start+content.length;content+=tagContent+"</"+tag.open.name+">";content=utils.escapeText(content);editor.replaceContent(content,tag.outerRange.start,tag.outerRange.end);editor.setCaretPos(caretPos);return!0}var utils=require("../utils/common"),matcher=(require("../assets/resources"),require("../assets/htmlMatcher")),editorUtils=require("../utils/editor"),profile=require("../assets/profile");return{splitJoinTagAction:function(editor,profileName){var info=editorUtils.outputInfo(editor,null,profileName),curProfile=profile.get(info.profile),tag=matcher.tag(info.content,editor.getCaretPos());return!!tag&&(tag.close?joinTag(editor,curProfile,tag):splitTag(editor,curProfile,tag))}}})},{"../assets/htmlMatcher":26,"../assets/profile":29,"../assets/resources":31,"../utils/common":73,"../utils/editor":75}],19:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function toggleHTMLComment(editor){var r=range(editor.getSelectionRange()),info=editorUtils.outputInfo(editor);if(!r.length()){var tag=htmlMatcher.tag(info.content,editor.getCaretPos());tag&&(r=tag.outerRange)}return genericCommentToggle(editor,"<!--","-->",r)}function toggleCSSComment(editor){var rng=range(editor.getSelectionRange()),info=editorUtils.outputInfo(editor);if(!rng.length()){var rule=cssEditTree.parseFromPosition(info.content,editor.getCaretPos());if(rule){var property=cssItemFromPosition(rule,editor.getCaretPos());rng=property?property.range(!0):range(rule.nameRange(!0).start,rule.source)}}if(!rng.length()){rng=range(editor.getCurrentLineRange());utils.narrowToNonSpace(info.content,rng)}return genericCommentToggle(editor,"/*","*/",rng)}function cssItemFromPosition(rule,absPos){var relPos=absPos-(rule.options.offset||0),reSafeChar=/^[\s\n\r]/;return utils.find(rule.list(),function(item){return item.range().end===relPos?reSafeChar.test(rule.source.charAt(relPos)):item.range().inside(relPos)})}function searchComment(text,from,startToken,endToken){for(var commentStart=-1,commentEnd=-1,hasMatch=function(str,start){return text.substr(start,str.length)==str};from--;)if(hasMatch(startToken,from)){commentStart=from;break}if(commentStart!=-1){from=commentStart;for(var contentLen=text.length;contentLen>=from++;)if(hasMatch(endToken,from)){commentEnd=from+endToken.length;break}}return commentStart!=-1&&commentEnd!=-1?range(commentStart,commentEnd-commentStart):null}function genericCommentToggle(editor,commentStart,commentEnd,range){function removeComment(str){return str.replace(new RegExp("^"+utils.escapeForRegexp(commentStart)+"\\s*"),function(str){caretPos-=str.length;return""}).replace(new RegExp("\\s*"+utils.escapeForRegexp(commentEnd)+"$"),"")}var content=editorUtils.outputInfo(editor).content,caretPos=editor.getCaretPos(),newContent=null,commentRange=searchComment(content,caretPos,commentStart,commentEnd);if(commentRange&&commentRange.overlap(range)){range=commentRange;newContent=removeComment(range.substring(content))}else{newContent=commentStart+" "+range.substring(content).replace(new RegExp(utils.escapeForRegexp(commentStart)+"\\s*|\\s*"+utils.escapeForRegexp(commentEnd),"g"),"")+" "+commentEnd;caretPos+=commentStart.length+1}if(null!==newContent){newContent=utils.escapeText(newContent);editor.setCaretPos(range.start);editor.replaceContent(editorUtils.unindent(editor,newContent),range.start,range.end);editor.setCaretPos(caretPos);return!0}return!1}var prefs=require("../assets/preferences"),range=require("../assets/range"),utils=require("../utils/common"),actionUtils=require("../utils/action"),editorUtils=require("../utils/editor"),htmlMatcher=require("../assets/htmlMatcher"),cssEditTree=require("../editTree/css");return{toggleCommentAction:function(editor){var info=editorUtils.outputInfo(editor);if(actionUtils.isSupportedCSS(info.syntax)){var caretPos=editor.getCaretPos(),tag=htmlMatcher.tag(info.content,caretPos);tag&&tag.open.range.inside(caretPos)&&(info.syntax="html")}var cssSyntaxes=prefs.getArray("css.syntaxes");return~cssSyntaxes.indexOf(info.syntax)?toggleCSSComment(editor):toggleHTMLComment(editor)}}})},{"../assets/htmlMatcher":26,"../assets/preferences":28,"../assets/range":30,"../editTree/css":37,"../utils/action":70,"../utils/common":73,"../utils/editor":75}],20:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function updateImageSizeHTML(editor){var offset=editor.getCaretPos(),info=editorUtils.outputInfo(editor),xmlElem=xmlEditTree.parseFromPosition(info.content,offset,!0);xmlElem&&"img"==(xmlElem.name()||"").toLowerCase()&&getImageSizeForSource(editor,xmlElem.value("src"),function(size){if(size){var compoundData=xmlElem.range(!0);xmlElem.value("width",size.width);xmlElem.value("height",size.height,xmlElem.indexOf("width")+1);actionUtils.compoundUpdate(editor,utils.extend(compoundData,{data:xmlElem.toString(),caret:offset}))}})}function updateImageSizeCSS(editor){var offset=editor.getCaretPos(),info=editorUtils.outputInfo(editor),cssRule=cssEditTree.parseFromPosition(info.content,offset,!0);if(cssRule){var m,prop=cssRule.itemFromPosition(offset,!0);prop&&(m=/url\((["']?)(.+?)\1\)/i.exec(prop.value()||""))&&getImageSizeForSource(editor,m[2],function(size){if(size){var compoundData=cssRule.range(!0);cssRule.value("width",size.width+"px");cssRule.value("height",size.height+"px",cssRule.indexOf("width")+1);actionUtils.compoundUpdate(editor,utils.extend(compoundData,{data:cssRule.toString(),caret:offset}))}})}}function getImageSizeForSource(editor,src,callback){var fileContent;if(src){if(/^data:/.test(src)){fileContent=base64.decode(src.replace(/^data\:.+?;.+?,/,""));return callback(actionUtils.getImageSize(fileContent))}var absPath=file.locateFile(editor.getFilePath(),src);if(null===absPath)throw"Can't find "+src+" file";file.read(absPath,function(err,content){if(err)throw"Unable to read "+absPath+": "+err;content=String(content);callback(actionUtils.getImageSize(content))})}}var utils=require("../utils/common"),editorUtils=require("../utils/editor"),actionUtils=require("../utils/action"),xmlEditTree=require("../editTree/xml"),cssEditTree=require("../editTree/css"),base64=require("../utils/base64"),file=require("../plugin/file");return{updateImageSizeAction:function(editor){actionUtils.isSupportedCSS(editor.getSyntax())?updateImageSizeCSS(editor):updateImageSizeHTML(editor);return!0}}})},{"../editTree/css":37,"../editTree/xml":38,"../plugin/file":63,"../utils/action":70,"../utils/base64":71,"../utils/common":73,"../utils/editor":75}],21:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function updateAttributes(tag,abbrNode,ix){var classNames=(abbrNode.attribute("class")||"").split(/\s+/g);ix&&classNames.push("+"+abbrNode.name());var r=function(str){return utils.replaceCounter(str,abbrNode.counter)};classNames.forEach(function(className){if(className){className=r(className);var ch=className.charAt(0);"+"==ch?tag.addClass(className.substr(1)):"-"==ch?tag.removeClass(className.substr(1)):tag.value("class",className)}});abbrNode.attributeList().forEach(function(attr){if("class"!=attr.name.toLowerCase()){var ch=attr.name.charAt(0);if("+"==ch){var attrName=attr.name.substr(1),tagAttr=tag.get(attrName);tagAttr?tagAttr.value(tagAttr.value()+r(attr.value)):tag.value(attrName,r(attr.value))}else"-"==ch?tag.remove(attr.name.substr(1)):tag.value(attr.name,r(attr.value))}})}var xmlEditTree=require("../editTree/xml"),actionUtils=(require("../utils/editor"),require("../utils/action")),utils=require("../utils/common"),parser=require("../parser/abbreviation");return{updateTagAction:function(editor,abbr){abbr=abbr||editor.prompt("Enter abbreviation");if(!abbr)return!1;var content=editor.getContent(),ctx=actionUtils.captureContext(editor),tag=this.getUpdatedTag(abbr,ctx,content);if(!tag)return!1;tag.name()!=ctx.name&&ctx.match.close&&editor.replaceContent("</"+tag.name()+">",ctx.match.close.range.start,ctx.match.close.range.end,!0);editor.replaceContent(tag.source,ctx.match.open.range.start,ctx.match.open.range.end,!0);return!0},getUpdatedTag:function(abbr,ctx,content,options){if(!ctx)return null;var tree=parser.parse(abbr,options||{}),tag=xmlEditTree.parse(ctx.match.open.range.substring(content),{offset:ctx.match.outerRange.start});tree.children.forEach(function(node,i){updateAttributes(tag,node,i)});var el=tree.children[0];el.data("nameResolved")||tag.name(el.name());return tag}}})},{"../editTree/xml":38,"../parser/abbreviation":55,"../utils/action":70,"../utils/common":73,"../utils/editor":75}],22:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){var range=require("../assets/range"),htmlMatcher=require("../assets/htmlMatcher"),utils=require("../utils/common"),editorUtils=require("../utils/editor"),actionUtils=require("../utils/action"),parser=require("../parser/abbreviation");return{wrapWithAbbreviationAction:function(editor,abbr,syntax,profile){var info=editorUtils.outputInfo(editor,syntax,profile);abbr=abbr||editor.prompt("Enter abbreviation");if(!abbr)return null;abbr=String(abbr);var r=range(editor.getSelectionRange());if(!r.length()){var match=htmlMatcher.tag(info.content,r.start);if(!match)return!1;r=utils.narrowToNonSpace(info.content,match.range)}var newContent=utils.escapeText(r.substring(info.content)),result=parser.expand(abbr,{pastedContent:editorUtils.unindent(editor,newContent),syntax:info.syntax,profile:info.profile,contextNode:actionUtils.captureContext(editor)});if(result){editor.replaceContent(result,r.start,r.end);return!0}return!1}}})},{"../assets/htmlMatcher":26,"../assets/range":30,"../parser/abbreviation":55,"../utils/action":70,"../utils/common":73,"../utils/editor":75}],23:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function intersection(arr1,arr2){var result=[],smaller=arr1,larger=arr2;if(smaller.length>larger.length){smaller=arr2;larger=arr1}larger.forEach(function(item){~smaller.indexOf(item)&&result.push(item)});return result}function parseDB(data,optimized){"string"==typeof data&&(data=JSON.parse(data));optimized||(data=optimize(data));vendorsDB=data.vendors;cssDB=data.css;erasDB=data.era}function optimize(data){"string"==typeof data&&(data=JSON.parse(data));return{vendors:parseVendors(data),css:parseCSS(data),era:parseEra(data)}}function parseVendors(data){var out={};Object.keys(data.agents).forEach(function(name){var agent=data.agents[name];out[name]={prefix:agent.prefix,versions:agent.versions}});return out}function parseCSS(data){var out={};data.cats.CSS;Object.keys(data.data).forEach(function(name){var section=data.data[name];name in cssSections&&cssSections[name].forEach(function(kw){out[kw]=section.stats})});return out}function parseEra(data){return Object.keys(data.eras).sort(function(a,b){return parseInt(a.substr(1))-parseInt(b.substr(1))})}function getVendorsList(){var allVendors=Object.keys(vendorsDB),vendors=prefs.getArray("caniuse.vendors");return vendors&&"all"!=vendors[0]?intersection(allVendors,vendors):allVendors}function getVersionSlice(){var era=prefs.get("caniuse.era"),ix=erasDB.indexOf(era);~ix||(ix=erasDB.indexOf("e-2"));return ix}var prefs=require("./preferences"),utils=require("../utils/common");prefs.define("caniuse.enabled",!0,"Enable support of Can I Use database. When enabled,\t\tCSS abbreviation resolver will look at Can I Use database first before detecting\t\tCSS properties that should be resolved");prefs.define("caniuse.vendors","all","A comma-separated list vendor identifiers\t\t(as described in Can I Use database) that should be supported\t\twhen resolving vendor-prefixed properties. Set value to <code>all</code>\t\tto support all available properties");prefs.define("caniuse.era","e-2","Browser era, as defined in Can I Use database.\t\tExamples: <code>e0</code> (current version), <code>e1</code> (near future)\t\t<code>e-2</code> (2 versions back) and so on.");var cssSections={"border-image":["border-image"],"css-boxshadow":["box-shadow"],"css3-boxsizing":["box-sizing"],multicolumn:["column-width","column-count","columns","column-gap","column-rule-color","column-rule-style","column-rule-width","column-rule","column-span","column-fill"],"border-radius":["border-radius","border-top-left-radius","border-top-right-radius","border-bottom-right-radius","border-bottom-left-radius"],transforms2d:["transform"],"css-hyphens":["hyphens"],"css-transitions":["transition","transition-property","transition-duration","transition-timing-function","transition-delay"],"font-feature":["font-feature-settings"],"css-animation":["animation","animation-name","animation-duration","animation-timing-function","animation-iteration-count","animation-direction","animation-play-state","animation-delay","animation-fill-mode","@keyframes"],"css-gradients":["linear-gradient"],"css-masks":["mask-image","mask-source-type","mask-repeat","mask-position","mask-clip","mask-origin","mask-size","mask","mask-type","mask-box-image-source","mask-box-image-slice","mask-box-image-width","mask-box-image-outset","mask-box-image-repeat","mask-box-image","clip-path","clip-rule"],"css-featurequeries":["@supports"],flexbox:["flex","inline-flex","flex-direction","flex-wrap","flex-flow","order","flex"],calc:["calc"],"object-fit":["object-fit","object-position"],"css-grid":["grid","inline-grid","grid-template-rows","grid-template-columns","grid-template-areas","grid-template","grid-auto-rows","grid-auto-columns"," grid-auto-flow","grid-auto-position","grid"," grid-row-start","grid-column-start","grid-row-end","grid-column-end","grid-column","grid-row","grid-area","justify-self","justify-items","align-self","align-items"],"css-repeating-gradients":["repeating-linear-gradient"],"css-filters":["filter"],"user-select-none":["user-select"],"intrinsic-width":["min-content","max-content","fit-content","fill-available"],"css3-tabsize":["tab-size"]},cssDB=null,vendorsDB=null,erasDB=null,db=null;!function(r){if("undefined"==typeof define||!define.amd)try{var fs=r("fs"),path=r("path");db=fs.readFileSync(path.join(__dirname,"../caniuse.json"),{encoding:"utf8"})}catch(e){}}(require);db&&parseDB(db);return{load:parseDB,optimize:optimize,resolvePrefixes:function(property){if(!(prefs.get("caniuse.enabled")&&cssDB&&property in cssDB))return null;var prefixes=[],propStats=cssDB[property],versions=getVersionSlice();getVendorsList().forEach(function(vendor){for(var v,vendorVesions=vendorsDB[vendor].versions.slice(versions),i=0;i<vendorVesions.length;i++){v=vendorVesions[i];if(v&&~propStats[vendor][v].indexOf("x")){prefixes.push(vendorsDB[vendor].prefix);break}}});return utils.unique(prefixes).sort(function(a,b){return b.length-a.length})}}})},{"../utils/common":73,"./preferences":28}],24:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function commonFactory(value){return{data:value}}var factories={},reAttrs=/([@\!]?)([\w\-:]+)\s*=\s*(['"])(.*?)\3/g;module=module||{};module.exports={add:function(name,factory){var that=this;factories[name]=function(){var elem=factory.apply(that,arguments);elem&&(elem.type=name);return elem}},get:function(name){return factories[name]},create:function(name){var args=[].slice.call(arguments,1),factory=this.get(name);return factory?factory.apply(this,args):null},is:function(elem,type){return this.type(elem)===type},type:function(elem){return elem&&elem.type}};module.exports.add("element",function(elementName,attrs,isEmpty){var ret={name:elementName,is_empty:!!isEmpty};if(attrs){ret.attributes=[];if(Array.isArray(attrs))ret.attributes=attrs;else if("string"==typeof attrs)for(var m;m=reAttrs.exec(attrs);)ret.attributes.push({name:m[2],value:m[4],isDefault:"@"==m[1],isImplied:"!"==m[1]});else ret.attributes=Object.keys(attrs).map(function(name){return{name:name,value:attrs[name]}})}return ret});module.exports.add("snippet",commonFactory);module.exports.add("reference",commonFactory);module.exports.add("empty",function(){return{}});return module.exports})},{}],25:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function HandlerList(){this._list=[]}var utils=require("../utils/common");HandlerList.prototype={add:function(fn,options){var order=this._list.length;options&&"order"in options&&(order=1e4*options.order);this._list.push(utils.extend({},options,{order:order,fn:fn}))},remove:function(fn){var item=utils.find(this._list,function(item){return item.fn===fn});item&&this._list.splice(this._list.indexOf(item),1)},list:function(){return this._list.sort(function(a,b){return b.order-a.order})},listFn:function(){return this.list().map(function(item){return item.fn})},exec:function(skipValue,args){args=args||[];var result=null;utils.find(this.list(),function(h){result=h.fn.apply(h,args);if(result!==skipValue)return!0});return result}};return{create:function(){return new HandlerList}}})},{"../utils/common":73}],26:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function openTag(i,match){return{name:match[1],selfClose:!!match[3],range:range(i,match[0]),type:"open"}}function closeTag(i,match){return{name:match[1],range:range(i,match[0]),type:"close"}}function comment(i,match){return{range:range(i,"number"==typeof match?match-i:match[0]),type:"comment"}}function createMatcher(text){var m,memo={};return{open:function(i){var m=this.matches(i);return m&&"open"==m.type?m:null},close:function(i){var m=this.matches(i);return m&&"close"==m.type?m:null},matches:function(i){var key="p"+i;if(!(key in memo)){memo[key]=!1;if("<"==text.charAt(i)){var substr=text.slice(i);(m=substr.match(reOpenTag))?memo[key]=openTag(i,m):(m=substr.match(reCloseTag))&&(memo[key]=closeTag(i,m))}}return memo[key]},text:function(){return text},clean:function(){memo=text=m=null}}}function matches(text,pos,pattern){return text.substring(pos,pos+pattern.length)==pattern}function findClosingPair(open,matcher){for(var stack=[],tag=null,text=matcher.text(),pos=open.range.end,len=text.length;pos<len;pos++){if(matches(text,pos,"<!--"))for(var j=pos;j<len;j++)if(matches(text,j,"-->")){pos=j+3;break}if(tag=matcher.matches(pos)){if("open"!=tag.type||tag.selfClose){if("close"==tag.type){if(!stack.length)return tag.name==open.name?tag:null;if(stack[stack.length-1]==tag.name)stack.pop();else{for(var found=!1;stack.length&&!found;){var last=stack.pop();last==tag.name&&(found=!0)}if(!stack.length&&!found)return tag.name==open.name?tag:null}}}else stack.push(tag.name);pos=tag.range.end-1}}}var range=require("./range"),reOpenTag=/^<([\w\:\-]+)((?:\s+[\w\-:]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/,reCloseTag=/^<\/([\w\:\-]+)[^>]*>/;return{find:function(text,pos){for(var j,jl,matcher=createMatcher(text),open=null,close=null,i=pos;i>=0;i--)if(open=matcher.open(i)){if(open.selfClose){if(open.range.cmp(pos,"lt","gt"))break;continue}close=findClosingPair(open,matcher);if(close){var r=range.create2(open.range.start,close.range.end);if(r.contains(pos))break}else if(open.range.contains(pos))break;open=null}else if(matches(text,i,"-->")){for(j=i-1;j>=0&&!matches(text,j,"-->");j--)if(matches(text,j,"<!--")){i=j;break}}else if(matches(text,i,"<!--")){for(j=i+4,jl=text.length;j<jl;j++)if(matches(text,j,"-->")){j+=3;break}open=comment(i,j);break}matcher.clean();if(open){var outerRange=null,innerRange=null;if(close){outerRange=range.create2(open.range.start,close.range.end);innerRange=range.create2(open.range.end,close.range.start)}else outerRange=innerRange=range.create2(open.range.start,open.range.end);if("comment"==open.type){var _c=outerRange.substring(text);innerRange.start+=_c.length-_c.replace(/^<\!--\s*/,"").length;innerRange.end-=_c.length-_c.replace(/\s*-->$/,"").length}return{open:open,close:close,type:"comment"==open.type?"comment":"tag",innerRange:innerRange,innerContent:function(){return this.innerRange.substring(text)},outerRange:outerRange,outerContent:function(){return this.outerRange.substring(text)},range:innerRange.length()&&innerRange.cmp(pos,"lte","gte")?innerRange:outerRange,content:function(){return this.range.substring(text)},source:text}}},tag:function(text,pos){var result=this.find(text,pos);if(result&&"tag"==result.type)return result}}})},{"./range":30}],27:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){return{log:function(){"undefined"!=typeof console&&console.log&&console.log.apply(console,arguments)}}})},{}],28:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function toBoolean(val){if("string"==typeof val){val=val.toLowerCase();return"yes"==val||"true"==val||"1"==val}return!!val}function isValueObj(obj){return"object"==typeof obj&&!Array.isArray(obj)&&"value"in obj&&Object.keys(obj).length<3}var utils=require("../utils/common"),preferences={},defaults={},_dbgDefaults=null,_dbgPreferences=null;return{define:function(name,value,description){var prefs=name;if("string"==typeof name){prefs={};prefs[name]={value:value,description:description}}Object.keys(prefs).forEach(function(k){
3
+ var v=prefs[k];defaults[k]=isValueObj(v)?v:{value:v}})},set:function(name,value){var prefs=name;if("string"==typeof name){prefs={};prefs[name]=value}Object.keys(prefs).forEach(function(k){var v=prefs[k];if(!(k in defaults))throw new Error('Property "'+k+'" is not defined. You should define it first with `define` method of current module');if(v!==defaults[k].value){switch(typeof defaults[k].value){case"boolean":v=toBoolean(v);break;case"number":v=parseInt(v+"",10)||0;break;default:null!==v&&(v+="")}preferences[k]=v}else k in preferences&&delete preferences[k]})},get:function(name){return name in preferences?preferences[name]:name in defaults?defaults[name].value:void 0},getArray:function(name){var val=this.get(name);if("undefined"==typeof val||null===val||""===val)return null;val=val.split(",").map(utils.trim);return val.length?val:null},getDict:function(name){var result={};this.getArray(name).forEach(function(val){var parts=val.split(":");result[parts[0]]=parts[1]});return result},description:function(name){return name in defaults?defaults[name].description:void 0},remove:function(name){Array.isArray(name)||(name=[name]);name.forEach(function(key){key in preferences&&delete preferences[key];key in defaults&&delete defaults[key]})},list:function(){return Object.keys(defaults).sort().map(function(key){return{name:key,value:this.get(key),type:typeof defaults[key].value,description:defaults[key].description}},this)},load:function(json){Object.keys(json).forEach(function(key){this.set(key,json[key])},this)},exportModified:function(){return utils.extend({},preferences)},reset:function(){preferences={}},_startTest:function(){_dbgDefaults=defaults;_dbgPreferences=preferences;defaults={};preferences={}},_stopTest:function(){defaults=_dbgDefaults;preferences=_dbgPreferences}}})},{"../utils/common":73}],29:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function OutputProfile(options){utils.extend(this,defaultProfile,options)}function stringCase(str,caseValue){switch(String(caseValue||"").toLowerCase()){case"lower":return str.toLowerCase();case"upper":return str.toUpperCase()}return str}function createProfile(name,options){return profiles[name.toLowerCase()]=new OutputProfile(options)}function createDefaultProfiles(){createProfile("xhtml");createProfile("html",{self_closing_tag:!1,compact_bool:!0});createProfile("xml",{self_closing_tag:!0,tag_nl:!0});createProfile("plain",{tag_nl:!1,indent:!1,place_cursor:!1});createProfile("line",{tag_nl:!1,indent:!1,extraFilters:"s"});createProfile("css",{tag_nl:!0});createProfile("css_line",{tag_nl:!1})}var utils=require("../utils/common"),resources=require("./resources"),prefs=require("./preferences");prefs.define("profile.allowCompactBoolean",!0,'This option can be used to globally disable compact form of boolean attribues (attributes where name and value are equal). With compactform enabled, HTML tags can be outputted as <code>&lt;div contenteditable&gt;</code> instead of <code>&lt;div contenteditable="contenteditable"&gt;</code>');prefs.define("profile.booleanAttributes","^contenteditable|seamless$","A regular expression for attributes that should be boolean by default.If attribute name matches this expression, you don’t have to write dot after attribute name in Emmet abbreviation to mark it as boolean.");var profiles={},defaultProfile={tag_case:"asis",attr_case:"asis",attr_quotes:"double",tag_nl:"decide",tag_nl_leaf:!1,place_cursor:!0,indent:!0,inline_break:3,compact_bool:!1,self_closing_tag:"xhtml",filters:"",extraFilters:""};OutputProfile.prototype={tagName:function(name){return stringCase(name,this.tag_case)},attributeName:function(name){return stringCase(name,this.attr_case)},attributeQuote:function(){return"single"==this.attr_quotes?"'":'"'},selfClosing:function(){return"xhtml"==this.self_closing_tag?" /":this.self_closing_tag===!0?"/":""},cursor:function(){return this.place_cursor?utils.getCaretPlaceholder():""},isBoolean:function(name,value){if(name==value)return!0;var boolAttrs=prefs.get("profile.booleanAttributes");if(!value&&boolAttrs){boolAttrs=new RegExp(boolAttrs,"i");return boolAttrs.test(name)}return!1},allowCompactBoolean:function(){return this.compact_bool&&prefs.get("profile.allowCompactBoolean")}};createDefaultProfiles();return{create:function(name,options){return 2==arguments.length?createProfile(name,options):new OutputProfile(utils.defaults(name||{},defaultProfile))},get:function(name,syntax){if(!name&&syntax){var profile=resources.findItem(syntax,"profile");profile&&(name=profile)}return name?name instanceof OutputProfile?name:"string"==typeof name&&name.toLowerCase()in profiles?profiles[name.toLowerCase()]:this.create(name):profiles.plain},remove:function(name){name=(name||"").toLowerCase();name in profiles&&delete profiles[name]},reset:function(){profiles={};createDefaultProfiles()},stringCase:stringCase}})},{"../utils/common":73,"./preferences":28,"./resources":31}],30:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function cmp(a,b,op){switch(op){case"eq":case"==":return a===b;case"lt":case"<":return a<b;case"lte":case"<=":return a<=b;case"gt":case">":return a>b;case"gte":case">=":return a>=b}}function Range(start,len){if("object"==typeof start&&"start"in start){this.start=Math.min(start.start,start.end);this.end=Math.max(start.start,start.end)}else if(Array.isArray(start)){this.start=start[0];this.end=start[1]}else{len="string"==typeof len?len.length:+len;this.start=start;this.end=start+len}}Range.prototype={length:function(){return Math.abs(this.end-this.start)},equal:function(range){return this.cmp(range,"eq","eq")},shift:function(delta){this.start+=delta;this.end+=delta;return this},overlap:function(range){return range.start<=this.end&&range.end>=this.start},intersection:function(range){if(this.overlap(range)){var start=Math.max(range.start,this.start),end=Math.min(range.end,this.end);return new Range(start,end-start)}return null},union:function(range){if(this.overlap(range)){var start=Math.min(range.start,this.start),end=Math.max(range.end,this.end);return new Range(start,end-start)}return null},inside:function(loc){return this.cmp(loc,"lte","gt")},contains:function(loc){return this.cmp(loc,"lt","gt")},include:function(r){return this.cmp(r,"lte","gte")},cmp:function(loc,left,right){var a,b;if(loc instanceof Range){a=loc.start;b=loc.end}else a=b=loc;return cmp(this.start,a,left||"<=")&&cmp(this.end,b,right||">")},substring:function(str){return this.length()>0?str.substring(this.start,this.end):""},clone:function(){return new Range(this.start,this.length())},toArray:function(){return[this.start,this.end]},toString:function(){return this.valueOf()},valueOf:function(){return"{"+this.start+", "+this.length()+"}"}};module.exports=function(start,len){if("undefined"==typeof start||null===start)return null;if(start instanceof Range)return start;if("object"==typeof start&&"start"in start&&"end"in start){len=start.end-start.start;start=start.start}return new Range(start,len)};module.exports.create=module.exports;module.exports.isRange=function(val){return val instanceof Range};module.exports.create2=function(start,end){"number"==typeof start&&"number"==typeof end&&(end-=start);return this.create(start,end)};module.exports.sort=function(ranges,reverse){ranges=ranges.sort(function(a,b){return a.start===b.start?b.end-a.end:a.start-b.start});reverse&&ranges.reverse();return ranges};return module.exports})},{}],31:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function each(obj,fn){obj&&Object.keys(obj).forEach(function(key){fn(obj[key],key)})}function normalizeCaretPlaceholder(text){return utils.replaceUnescapedSymbol(text,"|",utils.getCaretPlaceholder())}function parseItem(name,value,type){value=normalizeCaretPlaceholder(value);return"snippets"==type?elements.create("snippet",value):"abbreviations"==type?parseAbbreviation(name,value):void 0}function parseAbbreviation(key,value){key=utils.trim(key);var m;return(m=reTag.exec(value))?elements.create("element",m[1],m[2],"/"==m[4]):elements.create("reference",value)}function normalizeName(str){return str.replace(/:$/,"").replace(/:/g,"-")}function expandSnippetsDefinition(snippets){var out={};each(snippets,function(val,key){for(var items=key.split("|"),i=items.length-1;i>=0;i--)out[items[i]]=val});return out}var handlerList=require("./handlerList"),utils=require("../utils/common"),elements=require("./elements"),stringScore=(require("../assets/logger"),require("../vendor/stringScore")),cssResolver=require("../resolver/css"),VOC_SYSTEM="system",VOC_USER="user",cache={},reTag=/^<(\w+\:?[\w\-]*)((?:\s+[@\!]?[\w\:\-]+\s*=\s*(['"]).*?\3)*)\s*(\/?)>/,systemSettings={},userSettings={},resolvers=handlerList.create();utils.extend(exports,{setVocabulary:function(data,type){cache={};var voc={};each(data,function(section,syntax){var _section={};each(section,function(subsection,name){"abbreviations"!=name&&"snippets"!=name||(subsection=expandSnippetsDefinition(subsection));_section[name]=subsection});voc[syntax]=_section});type==VOC_SYSTEM?systemSettings=voc:userSettings=voc},getVocabulary:function(name){return name==VOC_SYSTEM?systemSettings:userSettings},getMatchedResource:function(node,syntax){return resolvers.exec(null,utils.toArray(arguments))||this.findSnippet(syntax,node.name())},getVariable:function(name){return(this.getSection("variables")||{})[name]},setVariable:function(name,value){var voc=this.getVocabulary("user")||{};"variables"in voc||(voc.variables={});voc.variables[name]=value;this.setVocabulary(voc,"user")},hasSyntax:function(syntax){return syntax in this.getVocabulary(VOC_USER)||syntax in this.getVocabulary(VOC_SYSTEM)},addResolver:function(fn,options){resolvers.add(fn,options)},removeResolver:function(fn){resolvers.remove(fn)},getSection:function(name){if(!name)return null;name in cache||(cache[name]=utils.deepMerge({},systemSettings[name],userSettings[name]));for(var key,data=cache[name],subsections=utils.toArray(arguments,1);data&&(key=subsections.shift());){if(!(key in data))return null;data=data[key]}return data},findItem:function(topSection,subsection){for(var data=this.getSection(topSection);data;){if(subsection in data)return data[subsection];data=this.getSection(data["extends"])}},findSnippet:function(syntax,name,memo){if(!syntax||!name)return null;memo=memo||[];var names=[name];~name.indexOf("-")&&names.push(name.replace(/\-/g,":"));var data=this.getSection(syntax),matchedItem=null;["snippets","abbreviations"].some(function(sectionName){var data=this.getSection(syntax,sectionName);if(data)return names.some(function(n){if(data[n])return matchedItem=parseItem(n,data[n],sectionName)})},this);memo.push(syntax);return matchedItem||!data["extends"]||~memo.indexOf(data["extends"])?matchedItem:this.findSnippet(data["extends"],name,memo)},fuzzyFindSnippet:function(syntax,name,minScore){var result=this.fuzzyFindMatches(syntax,name,minScore)[0];if(result)return result.value.parsedValue},fuzzyFindMatches:function(syntax,name,minScore){minScore=minScore||.3;name=normalizeName(name);var snippets=this.getAllSnippets(syntax);return Object.keys(snippets).map(function(key){var value=snippets[key];return{key:key,score:stringScore.score(value.nk,name,.1),value:value}}).filter(function(item){return item.score>=minScore}).sort(function(a,b){return a.score-b.score}).reverse()},getAllSnippets:function(syntax){var cacheKey="all-"+syntax;if(!cache[cacheKey]){var stack=[],sectionKey=syntax,memo=[];do{var section=this.getSection(sectionKey);if(!section)break;["snippets","abbreviations"].forEach(function(sectionName){var stackItem={};each(section[sectionName]||null,function(v,k){stackItem[k]={nk:normalizeName(k),value:v,parsedValue:parseItem(k,v,sectionName),type:sectionName}});stack.push(stackItem)});memo.push(sectionKey);sectionKey=section["extends"]}while(sectionKey&&!~memo.indexOf(sectionKey));cache[cacheKey]=utils.extend.apply(utils,stack.reverse())}return cache[cacheKey]},getNewline:function(){var nl=this.getVariable("newline");return"string"==typeof nl?nl:"\n"},setNewline:function(str){this.setVariable("newline",str);this.setVariable("nl",str)}});exports.addResolver(cssResolver.resolve.bind(cssResolver));!function(r){if("undefined"==typeof define||!define.amd)try{var fs=r("fs"),path=r("path"),defaultSnippets=fs.readFileSync(path.join(__dirname,"../snippets.json"),{encoding:"utf8"});exports.setVocabulary(JSON.parse(defaultSnippets),VOC_SYSTEM)}catch(e){}}(require);return exports})},{"../assets/logger":27,"../resolver/css":64,"../utils/common":73,"../vendor/stringScore":79,"./elements":24,"./handlerList":25}],32:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function StringStream(string){this.pos=this.start=0;this.string=string;this._length=string.length}StringStream.prototype={eol:function(){return this.pos>=this._length},sol:function(){return 0===this.pos},peek:function(){return this.string.charAt(this.pos)},next:function(){if(this.pos<this._length)return this.string.charAt(this.pos++)},eat:function(match){var ok,ch=this.string.charAt(this.pos);ok="string"==typeof match?ch==match:ch&&(match.test?match.test(ch):match(ch));if(ok){++this.pos;return ch}},eatWhile:function(match){for(var start=this.pos;this.eat(match););return this.pos>start},eatSpace:function(){for(var start=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>start},skipToEnd:function(){this.pos=this._length},skipTo:function(ch){var found=this.string.indexOf(ch,this.pos);if(found>-1){this.pos=found;return!0}},skipToPair:function(open,close,skipString){for(var ch,braceCount=0,pos=this.pos,len=this._length;pos<len;){ch=this.string.charAt(pos++);if(ch==open)braceCount++;else if(ch==close){braceCount--;if(braceCount<1){this.pos=pos;return!0}}else!skipString||'"'!=ch&&"'"!=ch||this.skipString(ch)}return!1},skipQuoted:function(noBackup){var ch=this.string.charAt(noBackup?this.pos:this.pos-1);if('"'===ch||"'"===ch){noBackup&&this.pos++;return this.skipString(ch)}},skipString:function(quote){for(var ch,pos=this.pos,len=this._length;pos<len;){ch=this.string.charAt(pos++);if("\\"!=ch&&ch==quote){this.pos=pos;return!0}}return!1},backUp:function(n){this.pos-=n},match:function(pattern,consume,caseInsensitive){if("string"!=typeof pattern){var match=this.string.slice(this.pos).match(pattern);match&&consume!==!1&&(this.pos+=match[0].length);return match}var cased=caseInsensitive?function(str){return str.toLowerCase()}:function(str){return str};if(cased(this.string).indexOf(cased(pattern),this.pos)==this.pos){consume!==!1&&(this.pos+=pattern.length);return!0}},current:function(backUp){return this.string.slice(this.start,this.pos-(backUp?1:0))}};module.exports=function(string){return new StringStream(string)};module.exports.create=module.exports;return module.exports})},{}],33:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){var utils=require("../utils/common"),stringStream=require("./stringStream"),resources=require("./resources"),startPlaceholderNum=100,tabstopIndex=0,defaultOptions={replaceCarets:!1,escape:function(ch){return"\\"+ch},tabstop:function(data){return data.token},variable:function(data){return data.token}};return{extract:function(text,options){var placeholders={carets:""},marks=[];options=utils.extend({},defaultOptions,options,{tabstop:function(data){var token=data.token,ret="";if("cursor"==data.placeholder)marks.push({start:data.start,end:data.start+token.length,group:"carets",value:""});else{"placeholder"in data&&(placeholders[data.group]=data.placeholder);data.group in placeholders&&(ret=placeholders[data.group]);marks.push({start:data.start,end:data.start+token.length,group:data.group,value:ret})}return token}});options.replaceCarets&&(text=text.replace(new RegExp(utils.escapeForRegexp(utils.getCaretPlaceholder()),"g"),"${0:cursor}"));text=this.processText(text,options);var buf="",lastIx=0,tabStops=marks.map(function(mark){buf+=text.substring(lastIx,mark.start);var pos=buf.length,ph=placeholders[mark.group]||"";buf+=ph;lastIx=mark.end;return{group:mark.group,start:pos,end:pos+ph.length}});buf+=text.substring(lastIx);return{text:buf,tabstops:tabStops.sort(function(a,b){return a.start-b.start})}},processText:function(text,options){options=utils.extend({},defaultOptions,options);for(var ch,m,a,buf="",stream=stringStream.create(text);ch=stream.next();)if("\\"!=ch||stream.eol()){a=ch;if("$"==ch){stream.start=stream.pos-1;if(m=stream.match(/^[0-9]+/))a=options.tabstop({start:buf.length,group:stream.current().substr(1),token:stream.current()});else if(m=stream.match(/^\{([a-z_\-][\w\-]*)\}/))a=options.variable({start:buf.length,name:m[1],token:stream.current()});else if(m=stream.match(/^\{([0-9]+)(:.+?)?\}/,!1)){stream.skipToPair("{","}");var obj={start:buf.length,group:m[1],token:stream.current()},placeholder=obj.token.substring(obj.group.length+2,obj.token.length-1);placeholder&&(obj.placeholder=placeholder.substr(1));a=options.tabstop(obj)}}buf+=a}else buf+=options.escape(stream.next());return buf},upgrade:function(node,offset){var maxNum=0,options={tabstop:function(data){var group=parseInt(data.group,10);group>maxNum&&(maxNum=group);return data.placeholder?"${"+(group+offset)+":"+data.placeholder+"}":"${"+(group+offset)+"}"}};["start","end","content"].forEach(function(p){node[p]=this.processText(node[p],options)},this);return maxNum},variablesResolver:function(node){var placeholderMemo={};return function(str,varName){if("child"==varName)return str;if("cursor"==varName)return utils.getCaretPlaceholder();var attr=node.attribute(varName);if("undefined"!=typeof attr&&attr!==str)return attr;var varValue=resources.getVariable(varName);if(varValue)return varValue;placeholderMemo[varName]||(placeholderMemo[varName]=startPlaceholderNum++);return"${"+placeholderMemo[varName]+":"+varName+"}"}},replaceVariables:function(str,vars){vars=vars||{};var resolver="function"==typeof vars?vars:function(str,p1){return p1 in vars?vars[p1]:null};return this.processText(str,{variable:function(data){var newValue=resolver(data.token,data.name,data);null===newValue&&(newValue=resources.getVariable(data.name));null!==newValue&&"undefined"!=typeof newValue||(newValue=data.token);return newValue}})},resetTabstopIndex:function(){tabstopIndex=0;startPlaceholderNum=100},abbrOutputProcessor:function(text,node,type){var maxNum=0,that=this,tsOptions={tabstop:function(data){var group=parseInt(data.group,10);if(0===group)return"${0}";group>maxNum&&(maxNum=group);if(data.placeholder){var ix=group+tabstopIndex,placeholder=that.processText(data.placeholder,tsOptions);return"${"+ix+":"+placeholder+"}"}return"${"+(group+tabstopIndex)+"}"}};text=this.processText(text,tsOptions);text=this.replaceVariables(text,this.variablesResolver(node));tabstopIndex+=maxNum+1;return text}}})},{"../utils/common":73,"./resources":31,"./stringStream":32}],34:[function(require,module,exports){if("object"==typeof module&&"function"!=typeof define)var define=function(factory){module.exports=factory(require,exports,module)};define(function(require,exports,module){function TokenIterator(tokens){this.tokens=tokens;this._position=0;this.reset()}TokenIterator.prototype={next:function(){if(this.hasNext()){var token=this.tokens[++this._i];this._position=token.start;return token}this._i=this._il;return null},current:function(){return this.tokens[this._i]},peek:function(){return this.tokens[this._i+i]},position:function(){return this._position},hasNext:function(){return this._i<this._il-1},reset:function(){this._i=0;this._il=this.tokens.length},item:function(){return this.tokens[this._i]},itemNext:function(){return this.tokens[this._i+1]},itemPrev:function(){return this.tokens[this._i-1]},nextUntil:function(type,callback){for(var token,test="string"==typeof type?function(t){return t.type==type}:type;token=this.next();){callback&&callback.call(this,token);if(test.call(this,token))break}}};return{create:function(tokens){return new TokenIterator(tokens)}}})},{}],35:[function(require,module,exports){module.exports={eras:{"e-26":"26 versions back","e-25":"25 versions back","e-24":"24 versions back","e-23":"23 versions back","e-22":"22 versions back","e-21":"21 versions back","e-20":"20 versions back","e-19":"19 versions back","e-18":"18 versions back","e-17":"17 versions back","e-16":"16 versions back","e-15":"15 versions back","e-14":"14 versions back","e-13":"13 versions back","e-12":"12 versions back","e-11":"11 versions back","e-10":"10 versions back","e-9":"9 versions back","e-8":"8 versions back","e-7":"7 versions back","e-6":"6 versions back","e-5":"5 versions back","e-4":"4 versions back","e-3":"3 versions back","e-2":"2 versions back","e-1":"Previous version",e0:"Current",e1:"Near future",e2:"Farther future"},agents:{ie:{browser:"IE",abbr:"IE",prefix:"ms",type:"desktop",usage_global:{10:10.7866,11:.114751,5.5:.009298,6:.204912,7:.508182,8:8.31124,9:5.21297},versions:[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"5.5","6","7","8","9","10","11",null,null],current_version:""},firefox:{browser:"Firefox",abbr:"FF",prefix:"moz",type:"desktop",usage_global:{10:.112406,11:.088319,12:.208754,13:.096348,14:.096348,15:.136493,16:.264957,17:.192696,18:.112406,19:.128464,2:.016058,20:.16058,21:.216783,22:.256928,23:.907277,24:11.0318,25:.529914,26:.016058,27:.016058,3:.088319,3.5:.040145,3.6:.305102,4:.072261,5:.048174,6:.048174,7:.040145,8:.072261,9:.056203},versions:[null,"2","3","3.5","3.6","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27"],current_version:""},chrome:{browser:"Chrome",abbr:"Chr.",prefix:"webkit",type:"desktop",usage_global:{10:.048174,11:.112406,12:.064232,13:.056203,14:.056203,15:.072261,16:.048174,17:.040145,18:.08029,19:.040145,20:.040145,21:.48174,22:.248899,23:.216783,24:.200725,25:.361305,26:.353276,27:.369334,28:.610204,29:5.08236,30:24.6089,31:.16058,32:.064232,4:.024087,5:.024087,6:.032116,7:.024087,8:.032116,9:.024087},versions:["4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32"],current_version:""},safari:{browser:"Safari",abbr:"Saf.",prefix:"webkit",type:"desktop",usage_global:{3.1:0,3.2:.008692,4:.104377,5:.305102,5.1:1.28464,6:2.04739,6.1:.064232,7:.16058},versions:[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"3.1","3.2","4","5","5.1","6","6.1","7",null,null],current_version:""},opera:{browser:"Opera",abbr:"Op.",prefix:"o",type:"desktop",usage_global:{"10.0-10.1":.016058,10.5:.008392,10.6:.008029,11:.008219,11.1:.008219,11.5:.016058,11.6:.032116,12:.040145,12.1:.48174,15:.032116,16:.104377,17:.16058,18:0,"9.5-9.6":.008219},versions:[null,null,null,null,null,null,null,null,null,null,null,null,null,null,"9.5-9.6","10.0-10.1","10.5","10.6","11","11.1","11.5","11.6","12","12.1","15","16","17","18",null],current_version:"",prefix_exceptions:{15:"webkit",16:"webkit",17:"webkit",18:"webkit"}},ios_saf:{browser:"iOS Safari",abbr:"iOS",prefix:"webkit",type:"mobile",usage_global:{3.2:.00400113,"4.0-4.1":.00800226,"4.2-4.3":.0280079,"5.0-5.1":.28408,"6.0-6.1":1.15633,"7.0":2.52071},versions:[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"3.2","4.0-4.1","4.2-4.3","5.0-5.1","6.0-6.1","7.0",null,null],current_version:""},op_mini:{browser:"Opera Mini",abbr:"O.Mini",prefix:"o",type:"mobile",usage_global:{"5.0-7.0":4.58374},versions:[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"5.0-7.0",null,null],current_version:""},android:{browser:"Android Browser",abbr:"And.",prefix:"webkit",type:"mobile",usage_global:{2.1:.0251229,2.2:.0854178,2.3:1.32146,3:.00502458,4:.994867,4.1:1.87417,"4.2-4.3":.743638,4.4:0},versions:[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"2.1","2.2","2.3","3","4","4.1","4.2-4.3","4.4",null],current_version:""},op_mob:{browser:"Opera Mobile",abbr:"O.Mob",prefix:"o",type:"mobile",usage_global:{0:0,10:0,11.5:.00726525,12:.0363263,12.1:.101714},versions:[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"10",null,null,"11.5","12","12.1","0",null,null],current_version:"16",prefix_exceptions:{0:"webkit"}},bb:{browser:"Blackberry Browser",abbr:"BB",prefix:"webkit",type:"mobile",usage_global:{10:0,7:.141419},versions:[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"7","10",null,null],current_version:""},and_chr:{browser:"Chrome for Android",abbr:"Chr/And.",prefix:"webkit",type:"mobile",usage_global:{0:1.38176},versions:[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"0",null,null],current_version:"30"},and_ff:{browser:"Firefox for Android",abbr:"FF/And.",prefix:"moz",type:"mobile",usage_global:{0:.070956},versions:[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"0",null,null],current_version:"25"},ie_mob:{browser:"IE Mobile",abbr:"IE.Mob",prefix:"ms",type:"mobile",usage_global:{10:.205595},versions:[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,"10",null,null],current_version:""}},statuses:{rec:"Recommendation",pr:"Proposed Recommendation",cr:"Candidate Recommendation",wd:"Working Draft",other:"Other",unoff:"Unofficial / Note"},cats:{CSS:["CSS","CSS2","CSS3"],HTML5:["Canvas","HTML5"],"JS API":["JS API"],Other:["PNG","Other","DOM"],SVG:["SVG"]},updated:1383587152,data:{"png-alpha":{title:"PNG alpha transparency",description:"Semi-transparent areas in PNG files",spec:"http://www.w3.org/TR/PNG/",status:"rec",links:[{url:"http://dillerdesign.com/experiment/DD_belatedPNG/",title:"Workaround for IE6"},{url:"http://en.wikipedia.org/wiki/Portable_Network_Graphics",title:"Wikipedia"}],categories:["PNG"],stats:{ie:{5.5:"n",6:"p",7:"y",8:"y",9:"y",10:"y",11:"y"},firefox:{2:"y",3:"y",3.5:"y",3.6:"y",4:"y",5:"y",6:"y",7:"y",8:"y",9:"y",10:"y",11:"y",12:"y",13:"y",14:"y",15:"y",16:"y",17:"y",18:"y",19:"y",20:"y",21:"y",22:"y",23:"y",24:"y",25:"y",26:"y",27:"y"},chrome:{4:"y",5:"y",6:"y",7:"y",8:"y",9:"y",10:"y",11:"y",12:"y",13:"y",14:"y",15:"y",16:"y",17:"y",18:"y",19:"y",20:"y",21:"y",22:"y",23:"y",24:"y",25:"y",26:"y",27:"y",28:"y",29:"y",30:"y",31:"y",32:"y"},safari:{3.1:"y",3.2:"y",4:"y",5:"y",5.1:"y",6:"y",6.1:"y",7:"y"},opera:{9:"y","9.5-9.6":"y","10.0-10.1":"y",10.5:"y",10.6:"y",11:"y",11.1:"y",11.5:"y",11.6:"y",12:"y",12.1:"y",15:"y",16:"y",17:"y",18:"y"},ios_saf:{3.2:"y","4.0-4.1":"y","4.2-4.3":"y","5.0-5.1":"y","6.0-6.1":"y","7.0":"y"},op_mini:{"5.0-7.0":"y"},android:{2.1:"y",2.2:"y",2.3:"y",3:"y",4:"y",4.1:"y","4.2-4.3":"y",4.4:"y"},bb:{7:"y",10:"y"},op_mob:{10:"y",11:"y",11.1:"y",11.5:"y",12:"y",12.1:"y",0:"y"},and_chr:{0:"y"},and_ff:{0:"y"},ie_mob:{10:"y"}},notes:"IE6 does support full transparency in 8-bit PNGs, which can sometimes be an alternative to 24-bit PNGs.",usage_perc_y:94.36,usage_perc_a:0,ucprefix:!1,parent:"",keywords:""},apng:{title:"Animated PNG (APNG)",description:"Like animated GIFs, but allowing 24-bit colors and alpha transparency",spec:"https://wiki.mozilla.org/APNG_Specification",status:"unoff",links:[{url:"http://en.wikipedia.org/wiki/APNG",title:"Wikipedia"},{url:"https://github.com/davidmz/apng-canvas",title:"Polyfill using canvas"},{url:"https://chrome.google.com/webstore/detail/ehkepjiconegkhpodgoaeamnpckdbblp",title:"Chrome extension providing support"},{url:"http://www.truekolor.net/learn-how-to-create-an-animated-png/",title:"APNG tutorial"}],categories:["PNG"],stats:{ie:{5.5:"n",6:"n",7:"n",8:"n",9:"n",10:"n",11:"n"},firefox:{2:"n",3:"y",3.5:"y",3.6:"y",4:"y",5:"y",6:"y",7:"y",8:"y",9:"y",10:"y",11:"y",12:"y",13:"y",14:"y",15:"y",16:"y",17:"y",18:"y",19:"y",20:"y",21:"y",22:"y",23:"y",24:"y",25:"y",26:"y",27:"y"},chrome:{4:"n",5:"n",6:"n",7:"n",8:"n",9:"n",10:"n",11:"n",12:"n",13:"n",14:"n",15:"n",16:"n",17:"n",18:"n",19:"n",20:"n",21:"n",22:"n",23:"n",24:"n",25:"n",26:"n",27:"n",28:"n",29:"n",30:"n",31:"n",32:"n"},safari:{3.1:"n",3.2:"n",4:"n",5:"n",5.1:"n",6:"n",6.1:"n",7:"n"},opera:{9:"n","9.5-9.6":"y","10.0-10.1":"y",10.5:"y",10.6:"y",11:"y",11.1:"y",11.5:"y",11.6:"y",12:"y",12.1:"y",15:"n",16:"n",17:"n",18:"n"},ios_saf:{3.2:"n","4.0-4.1":"n","4.2-4.3":"n","5.0-5.1":"n","6.0-6.1":"n","7.0":"n"},op_mini:{"5.0-7.0":"n"},android:{2.1:"n",2.2:"n",2.3:"n",3:"n",4:"n",4.1:"n","4.2-4.3":"n",4.4:"n"},bb:{7:"n",10:"n"},op_mob:{10:"y",11:"y",11.1:"y",11.5:"y",12:"y",12.1:"y",0:"n"},and_chr:{0:"n"},and_ff:{0:"y"},ie_mob:{10:"n"}},notes:"Where support for APNG is missing, only the first frame is displayed",usage_perc_y:16.19,usage_perc_a:0,ucprefix:!1,parent:"",keywords:""},video:{title:"Video element",description:"Method of playing videos on webpages (without requiring a plug-in)",spec:"http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#video",status:"wd",links:[{url:"https://raw.github.com/phiggins42/has.js/master/detect/video.js#video",title:"has.js test"},{url:"http://webmproject.org",title:"WebM format information"},{url:"http://docs.webplatform.org/wiki/html/elements/video",title:"WebPlatform Docs"},{url:"http://camendesign.co.uk/code/video_for_everybody",title:"Video for Everybody"},{url:"http