openrat-cms

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs

commit 0dfbaff17a0b100c933986d26c32b9331ca67f46
parent feba1e0bf3d0a798224ed7f7e4460a8c3e7ce8d3
Author: Jan Dankert <devnull@localhost>
Date:   Tue, 22 May 2018 22:39:54 +0200

Fix für PHP 7.2: 'Object' darf nun nicht mehr als Klassennamen verwendet werden. AUCH NICHT IN EINEM NAMESPACE! WTF, wozu habe ich das in einen verfickten Namespace gepackt? Wozu soll der sonst da sein??? Amateure. Daher nun notgedrungen unbenannt in 'BaseObject'.

Diffstat:
dav/Logger.class.php | 2+-
editor/markitup/markitup/jquery.markitup.min.js | 593+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/cms-core/action/Action.class.php | 3++-
modules/cms-core/action/ImageAction.class.php | 2+-
modules/cms-core/action/LoginAction.class.php | 16++++++++--------
modules/cms-core/model/Folder.class.php | 18+++++++++---------
modules/cms-core/model/ObjectFactory.php | 2+-
modules/cms-macros/macro/BlockMenu.class.php | 6+++---
modules/cms-macros/macro/Link.class.php | 4++--
modules/cms-macros/macro/MainMenu.class.php | 4++--
modules/cms-ui/themes/default/html/views/file/edit.php | 22++++++++++++++++++++++
modules/cms-ui/themes/default/html/views/file/structure.php | 8++++++++
modules/cms-ui/themes/default/html/views/folder/createpage.php | 38++++++++++++++++++++++++++++++++++++++
modules/cms-ui/themes/default/html/views/folder/preview.php | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/cms-ui/themes/default/html/views/folder/pub.php | 130+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/cms-ui/themes/default/html/views/language/advanced.php | 28++++++++++++++++++++++++++++
modules/cms-ui/themes/default/html/views/language/structure.php | 8++++++++
modules/cms-ui/themes/default/html/views/login/register.php | 48++++++++++++++++++++++++++++++++++++++++++++++++
modules/cms-ui/themes/default/html/views/page/changetemplate.tpl.src.xml | 3+++
modules/cms-ui/themes/default/html/views/pageelement/prop.php | 122+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/cms-ui/themes/default/html/views/profile/pw.php | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/cms-ui/themes/default/html/views/project/maintenance.php | 30++++++++++++++++++++++++++++++
modules/cms-ui/themes/default/html/views/template/edit.php | 2+-
modules/cms-ui/themes/default/html/views/template/edit.tpl.src.xml | 2+-
modules/cms-ui/themes/default/html/views/template/info.php | 35+++++++++++++++++++++++++++++++++++
modules/cms-ui/themes/default/html/views/template/src.tpl.src.xml | 5++---
modules/cms-ui/themes/default/html/views/user/info.php | 47+++++++++++++++++++++++++++++++++++++++++++++++
modules/cms-ui/themes/default/html/views/user/memberships.php | 50++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/.editorconfig | 7+++++++
modules/editor/codemirror/.npmignore | 11+++++++++++
modules/editor/codemirror/addon/comment/continuecomment.min.js | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/edit/trailingspace.js | 27+++++++++++++++++++++++++++
modules/editor/codemirror/addon/edit/trailingspace.min.js | 27+++++++++++++++++++++++++++
modules/editor/codemirror/addon/fold/comment-fold.js | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/fold/foldgutter.min.js | 146+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/fold/indent-fold.min.js | 48++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/fold/xml-fold.min.js | 182+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/hint/anyword-hint.js | 41+++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/hint/javascript-hint.js | 155+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/hint/show-hint.css | 36++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/lint/css-lint.min.js | 40++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/lint/html-lint.js | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/lint/javascript-lint.min.js | 141+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/lint/json-lint.js | 37+++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/mode/overlay.js | 90+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/runmode/colorize.js | 40++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/runmode/runmode-standalone.min.js | 158+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/scroll/annotatescrollbar.min.js | 122+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/scroll/simplescrollbars.js | 152+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/search/jump-to-line.min.js | 49+++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/search/match-highlighter.js | 165+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/search/searchcursor.min.js | 289++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/tern/worker.js | 44++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/bin/authors.sh | 6++++++
modules/editor/codemirror/demo/activeline.html | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/demo/folding.html | 133+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/demo/matchtags.html | 48++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/demo/mustache.html | 69+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/demo/runmode.html | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/demo/tern.html | 133+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/demo/widget.html | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/doc/docs.css | 271+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/doc/logo.png | 0
modules/editor/codemirror/doc/manual.html | 3527+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/keymap/sublime.js | 704+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/keymap/sublime.min.js | 704+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/apl/apl.min.js | 174+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/asterisk/asterisk.min.js | 196+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/clike/clike.min.js | 790+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/clike/test.min.js | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/coffeescript/coffeescript.min.js | 359+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/css/test.min.js | 206+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/cypher/cypher.min.js | 150+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/cypher/test.min.js | 37+++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/django/django.min.js | 356+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/erlang/erlang.min.js | 619+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/gfm/test.min.js | 198+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/gherkin/gherkin.min.js | 178+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/go/go.min.js | 187+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/groovy/groovy.min.js | 230+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/htmlembedded/htmlembedded.min.js | 28++++++++++++++++++++++++++++
modules/editor/codemirror/mode/livescript/livescript.min.js | 280+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/lua/lua.min.js | 159+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/mathematica/mathematica.min.js | 176+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/mirc/mirc.min.js | 193+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/modelica/modelica.min.js | 245+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/mscgen/mscgen.min.js | 175+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/mscgen/mscgen_test.min.js | 83+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/mumps/mumps.min.js | 148+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/pig/pig.min.js | 178+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/properties/properties.min.js | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/pug/pug.min.js | 591+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/r/r.min.js | 183+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/ruby/test.min.js | 16++++++++++++++++
modules/editor/codemirror/mode/sas/sas.min.js | 303+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/sass/sass.min.js | 454+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/slim/slim.min.js | 575+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/solr/solr.min.js | 104+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/stylus/stylus.min.js | 771+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/tiki/tiki.min.js | 312+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/verilog/test.min.js | 273+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/vhdl/vhdl.min.js | 189+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/yacas/yacas.min.js | 204+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/modes.txt | 152+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/package.json | 49+++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/display/gutters.js | 34++++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/display/mode_state.js | 22++++++++++++++++++++++
modules/editor/codemirror/src/display/operations.min.js | 205+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/display/scrollbars.min.js | 192+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/display/scrolling.js | 184+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/display/selection.js | 158+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/display/update_display.min.js | 260+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/display/update_lines.js | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/edit/key_events.min.js | 159+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/edit/utils.min.js | 7+++++++
modules/editor/codemirror/src/input/ContentEditableInput.js | 517+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/input/indent.min.js | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/input/input.min.js | 135+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/input/keymap.min.js | 145+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/input/keynames.js | 17+++++++++++++++++
modules/editor/codemirror/src/line/highlight.min.js | 284+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/line/saw_special_spans.min.js | 10++++++++++
modules/editor/codemirror/src/model/change_measurement.min.js | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/model/mark_text.min.js | 292+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/util/browser.js | 33+++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/util/event.min.js | 103+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/util/feature_detection.min.js | 84+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/test/contenteditable_test.js | 110+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/test/contenteditable_test.min.js | 110+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/test/doc_test.js | 371+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/test/emacs_test.min.js | 149+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/test/mode_test.js | 193+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/test/run.js | 31+++++++++++++++++++++++++++++++
modules/editor/codemirror/test/scroll_test.min.js | 126+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/test/search_test.js | 85+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/test/test.js | 2550+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/test/vim_test.js | 4238+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/theme/3024-day.css | 41+++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/theme/ambiance-mobile.css | 5+++++
modules/editor/codemirror/theme/cobalt.css | 25+++++++++++++++++++++++++
modules/editor/codemirror/theme/eclipse.css | 23+++++++++++++++++++++++
modules/editor/codemirror/theme/elegant.css | 13+++++++++++++
modules/editor/codemirror/theme/erlang-dark.css | 34++++++++++++++++++++++++++++++++++
modules/editor/codemirror/theme/hopscotch.css | 34++++++++++++++++++++++++++++++++++
modules/editor/codemirror/theme/liquibyte.css | 95+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/theme/material.css | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/theme/night.css | 27+++++++++++++++++++++++++++
modules/editor/codemirror/theme/railscasts.css | 34++++++++++++++++++++++++++++++++++
modules/editor/codemirror/theme/ttcn.css | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/theme/xq-dark.css | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/template-engine/components/components.ini | 43+++++++++++++++++++++++++++++++++++++++++++
modules/util/ProjectTree.class.php | 6+++---
modules/util/Transformer.class.php | 4++--
153 files changed, 30557 insertions(+), 38 deletions(-)

diff --git a/dav/Logger.class.php b/dav/Logger.class.php @@ -67,7 +67,7 @@ class Logger function info( $message ) { if ( DAV_LOG_LEVEL >= DAV_LOG_LEVEL_INFO ) - Logger::doLog( 'info',$message ); + Logger::doLog( 'TemplateEngineInfo',$message ); } diff --git a/editor/markitup/markitup/jquery.markitup.min.js b/editor/markitup/markitup/jquery.markitup.min.js @@ -0,0 +1,593 @@ +// ---------------------------------------------------------------------------- +// markItUp! Universal MarkUp Engine, JQuery plugin +// v 1.1.x +// Dual licensed under the MIT and GPL licenses. +// ---------------------------------------------------------------------------- +// Copyright (C) 2007-2011 Jay Salvat +// http://markitup.jaysalvat.com/ +// ---------------------------------------------------------------------------- +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// ---------------------------------------------------------------------------- +(function($) { + $.fn.markItUp = function(settings, extraSettings) { + var options, ctrlKey, shiftKey, altKey; + ctrlKey = shiftKey = altKey = false; + + options = { id: '', + nameSpace: '', + root: '', + previewInWindow: '', // 'width=800, height=600, resizable=yes, scrollbars=yes' + previewAutoRefresh: true, + previewPosition: 'after', + previewTemplatePath: '~/templates/preview.html', + previewParser: false, + previewParserPath: '', + previewParserVar: 'data', + resizeHandle: true, + beforeInsert: '', + afterInsert: '', + onEnter: {}, + onShiftEnter: {}, + onCtrlEnter: {}, + onTab: {}, + markupSet: [ { /* set */ } ] + }; + $.extend(options, settings, extraSettings); + + // compute markItUp! path + if (!options.root) { + $('script').each(function(a, tag) { + miuScript = $(tag).get(0).src.match(/(.*)jquery\.markitup(\.pack)?\.js$/); + if (miuScript !== null) { + options.root = miuScript[1]; + } + }); + } + + return this.each(function() { + var $$, textarea, levels, scrollPosition, caretPosition, caretOffset, + clicked, hash, header, footer, previewWindow, template, iFrame, abort; + $$ = $(this); + textarea = this; + levels = []; + abort = false; + scrollPosition = caretPosition = 0; + caretOffset = -1; + + options.previewParserPath = localize(options.previewParserPath); + options.previewTemplatePath = localize(options.previewTemplatePath); + + // apply the computed path to ~/ + function localize(data, inText) { + if (inText) { + return data.replace(/("|')~\//g, "$1"+options.root); + } + return data.replace(/^~\//, options.root); + } + + // init and build editor + function init() { + id = ''; nameSpace = ''; + if (options.id) { + id = 'id="'+options.id+'"'; + } else if ($$.attr("id")) { + id = 'id="markItUp'+($$.attr("id").substr(0, 1).toUpperCase())+($$.attr("id").substr(1))+'"'; + + } + if (options.nameSpace) { + nameSpace = 'class="'+options.nameSpace+'"'; + } + $$.wrap('<div '+nameSpace+'></div>'); + $$.wrap('<div '+id+' class="markItUp"></div>'); + $$.wrap('<div class="markItUpContainer"></div>'); + $$.addClass("markItUpEditor"); + + // add the header before the textarea + header = $('<div class="markItUpHeader"></div>').insertBefore($$); + $(dropMenus(options.markupSet)).appendTo(header); + + // add the footer after the textarea + footer = $('<div class="markItUpFooter"></div>').insertAfter($$); + + // add the resize handle after textarea + if (options.resizeHandle === true && $.browser.safari !== true) { + resizeHandle = $('<div class="markItUpResizeHandle"></div>') + .insertAfter($$) + .bind("mousedown", function(e) { + var h = $$.height(), y = e.clientY, mouseMove, mouseUp; + mouseMove = function(e) { + $$.css("height", Math.max(20, e.clientY+h-y)+"px"); + return false; + }; + mouseUp = function(e) { + $("html").unbind("mousemove", mouseMove).unbind("mouseup", mouseUp); + return false; + }; + $("html").bind("mousemove", mouseMove).bind("mouseup", mouseUp); + }); + footer.append(resizeHandle); + } + + // listen key events + $$.keydown(keyPressed).keyup(keyPressed); + + // bind an event to catch external calls + $$.bind("insertion", function(e, settings) { + if (settings.target !== false) { + get(); + } + if (textarea === $.markItUp.focused) { + markup(settings); + } + }); + + // remember the last focus + $$.focus(function() { + $.markItUp.focused = this; + }); + } + + // recursively build header with dropMenus from markupset + function dropMenus(markupSet) { + var ul = $('<ul></ul>'), i = 0; + $('li:hover > ul', ul).css('display', 'block'); + $.each(markupSet, function() { + var button = this, t = '', title, li, j; + title = (button.key) ? (button.name||'')+' [Ctrl+'+button.key+']' : (button.name||''); + key = (button.key) ? 'accesskey="'+button.key+'"' : ''; + if (button.separator) { + li = $('<li class="markItUpSeparator">'+(button.separator||'')+'</li>').appendTo(ul); + } else { + i++; + for (j = levels.length -1; j >= 0; j--) { + t += levels[j]+"-"; + } + li = $('<li class="markItUpButton markItUpButton'+t+(i)+' '+(button.className||'')+'"><a href="" '+key+' title="'+title+'">'+(button.name||'')+'</a></li>') + .bind("contextmenu", function() { // prevent contextmenu on mac and allow ctrl+click + return false; + }).click(function() { + return false; + }).bind("focusin", function(){ + $$.focus(); + }).mouseup(function() { + if (button.call) { + eval(button.call)(); + } + setTimeout(function() { markup(button) },1); + return false; + }).hover(function() { + $('> ul', this).show(); + $(document).one('click', function() { // close dropmenu if click outside + $('ul ul', header).hide(); + } + ); + }, function() { + $('> ul', this).hide(); + } + ).appendTo(ul); + if (button.dropMenu) { + levels.push(i); + $(li).addClass('markItUpDropMenu').append(dropMenus(button.dropMenu)); + } + } + }); + levels.pop(); + return ul; + } + + // markItUp! markups + function magicMarkups(string) { + if (string) { + string = string.toString(); + string = string.replace(/\(\!\(([\s\S]*?)\)\!\)/g, + function(x, a) { + var b = a.split('|!|'); + if (altKey === true) { + return (b[1] !== undefined) ? b[1] : b[0]; + } else { + return (b[1] === undefined) ? "" : b[0]; + } + } + ); + // [![prompt]!], [![prompt:!:value]!] + string = string.replace(/\[\!\[([\s\S]*?)\]\!\]/g, + function(x, a) { + var b = a.split(':!:'); + if (abort === true) { + return false; + } + value = prompt(b[0], (b[1]) ? b[1] : ''); + if (value === null) { + abort = true; + } + return value; + } + ); + return string; + } + return ""; + } + + // prepare action + function prepare(action) { + if ($.isFunction(action)) { + action = action(hash); + } + return magicMarkups(action); + } + + // build block to insert + function build(string) { + var openWith = prepare(clicked.openWith); + var placeHolder = prepare(clicked.placeHolder); + var replaceWith = prepare(clicked.replaceWith); + var closeWith = prepare(clicked.closeWith); + var openBlockWith = prepare(clicked.openBlockWith); + var closeBlockWith = prepare(clicked.closeBlockWith); + var multiline = clicked.multiline; + + if (replaceWith !== "") { + block = openWith + replaceWith + closeWith; + } else if (selection === '' && placeHolder !== '') { + block = openWith + placeHolder + closeWith; + } else { + string = string || selection; + + var lines = selection.split(/\r?\n/), blocks = []; + + for (var l=0; l < lines.length; l++) { + line = lines[l]; + var trailingSpaces; + if (trailingSpaces = line.match(/ *$/)) { + blocks.push(openWith + line.replace(/ *$/g, '') + closeWith + trailingSpaces); + } else { + blocks.push(openWith + line + closeWith); + } + } + + block = blocks.join("\n"); + } + + block = openBlockWith + block + closeBlockWith; + + return { block:block, + openWith:openWith, + replaceWith:replaceWith, + placeHolder:placeHolder, + closeWith:closeWith + }; + } + + // define markup to insert + function markup(button) { + var len, j, n, i; + hash = clicked = button; + get(); + $.extend(hash, { line:"", + root:options.root, + textarea:textarea, + selection:(selection||''), + caretPosition:caretPosition, + ctrlKey:ctrlKey, + shiftKey:shiftKey, + altKey:altKey + } + ); + // callbacks before insertion + prepare(options.beforeInsert); + prepare(clicked.beforeInsert); + if ((ctrlKey === true && shiftKey === true) || button.multiline === true) { + prepare(clicked.beforeMultiInsert); + } + $.extend(hash, { line:1 }); + + if ((ctrlKey === true && shiftKey === true)) { + lines = selection.split(/\r?\n/); + for (j = 0, n = lines.length, i = 0; i < n; i++) { + if ($.trim(lines[i]) !== '') { + $.extend(hash, { line:++j, selection:lines[i] } ); + lines[i] = build(lines[i]).block; + } else { + lines[i] = ""; + } + } + string = { block:lines.join('\n')}; + start = caretPosition; + len = string.block.length + (($.browser.opera) ? n-1 : 0); + } else if (ctrlKey === true) { + string = build(selection); + start = caretPosition + string.openWith.length; + len = string.block.length - string.openWith.length - string.closeWith.length; + len = len - (string.block.match(/ $/) ? 1 : 0); + len -= fixIeBug(string.block); + } else if (shiftKey === true) { + string = build(selection); + start = caretPosition; + len = string.block.length; + len -= fixIeBug(string.block); + } else { + string = build(selection); + start = caretPosition + string.block.length ; + len = 0; + start -= fixIeBug(string.block); + } + if ((selection === '' && string.replaceWith === '')) { + caretOffset += fixOperaBug(string.block); + + start = caretPosition + string.openWith.length; + len = string.block.length - string.openWith.length - string.closeWith.length; + + caretOffset = $$.val().substring(caretPosition, $$.val().length).length; + caretOffset -= fixOperaBug($$.val().substring(0, caretPosition)); + } + $.extend(hash, { caretPosition:caretPosition, scrollPosition:scrollPosition } ); + + if (string.block !== selection && abort === false) { + insert(string.block); + set(start, len); + } else { + caretOffset = -1; + } + get(); + + $.extend(hash, { line:'', selection:selection }); + + // callbacks after insertion + if ((ctrlKey === true && shiftKey === true) || button.multiline === true) { + prepare(clicked.afterMultiInsert); + } + prepare(clicked.afterInsert); + prepare(options.afterInsert); + + // refresh preview if opened + if (previewWindow && options.previewAutoRefresh) { + refreshPreview(); + } + + // reinit keyevent + shiftKey = altKey = ctrlKey = abort = false; + } + + // Substract linefeed in Opera + function fixOperaBug(string) { + if ($.browser.opera) { + return string.length - string.replace(/\n*/g, '').length; + } + return 0; + } + // Substract linefeed in IE + function fixIeBug(string) { + if ($.browser.msie) { + return string.length - string.replace(/\r*/g, '').length; + } + return 0; + } + + // add markup + function insert(block) { + if (document.selection) { + var newSelection = document.selection.createRange(); + newSelection.text = block; + } else { + textarea.value = textarea.value.substring(0, caretPosition) + block + textarea.value.substring(caretPosition + selection.length, textarea.value.length); + } + } + + // set a selection + function set(start, len) { + if (textarea.createTextRange){ + // quick fix to make it work on Opera 9.5 + if ($.browser.opera && $.browser.version >= 9.5 && len == 0) { + return false; + } + range = textarea.createTextRange(); + range.collapse(true); + range.moveStart('character', start); + range.moveEnd('character', len); + range.select(); + } else if (textarea.setSelectionRange ){ + textarea.setSelectionRange(start, start + len); + } + textarea.scrollTop = scrollPosition; + textarea.focus(); + } + + // get the selection + function get() { + textarea.focus(); + + scrollPosition = textarea.scrollTop; + if (document.selection) { + selection = document.selection.createRange().text; + if ($.browser.msie) { // ie + var range = document.selection.createRange(), rangeCopy = range.duplicate(); + rangeCopy.moveToElementText(textarea); + caretPosition = -1; + while(rangeCopy.inRange(range)) { + rangeCopy.moveStart('character'); + caretPosition ++; + } + } else { // opera + caretPosition = textarea.selectionStart; + } + } else { // gecko & webkit + caretPosition = textarea.selectionStart; + + selection = textarea.value.substring(caretPosition, textarea.selectionEnd); + } + return selection; + } + + // open preview window + function preview() { + if (!previewWindow || previewWindow.closed) { + if (options.previewInWindow) { + previewWindow = window.open('', 'preview', options.previewInWindow); + $(window).unload(function() { + previewWindow.close(); + }); + } else { + iFrame = $('<iframe class="markItUpPreviewFrame"></iframe>'); + if (options.previewPosition == 'after') { + iFrame.insertAfter(footer); + } else { + iFrame.insertBefore(header); + } + previewWindow = iFrame[iFrame.length - 1].contentWindow || frame[iFrame.length - 1]; + } + } else if (altKey === true) { + if (iFrame) { + iFrame.remove(); + } else { + previewWindow.close(); + } + previewWindow = iFrame = false; + } + if (!options.previewAutoRefresh) { + refreshPreview(); + } + if (options.previewInWindow) { + previewWindow.focus(); + } + } + + // refresh Preview window + function refreshPreview() { + renderPreview(); + } + + function renderPreview() { + var phtml; + if (options.previewParser && typeof options.previewParser === 'function') { + var data = options.previewParser( $$.val() ); + writeInPreview( localize(data, 1) ); + } else if (options.previewParserPath !== '') { + $.ajax({ + type: 'POST', + dataType: 'text', + global: false, + url: options.previewParserPath, + data: options.previewParserVar+'='+encodeURIComponent($$.val()), + success: function(data) { + writeInPreview( localize(data, 1) ); + } + }); + } else { + if (!template) { + $.ajax({ + url: options.previewTemplatePath, + dataType: 'text', + global: false, + success: function(data) { + writeInPreview( localize(data, 1).replace(/<!-- content -->/g, $$.val()) ); + } + }); + } + } + return false; + } + + function writeInPreview(data) { + if (previewWindow.document) { + try { + sp = previewWindow.document.documentElement.scrollTop + } catch(e) { + sp = 0; + } + previewWindow.document.open(); + previewWindow.document.write(data); + previewWindow.document.close(); + previewWindow.document.documentElement.scrollTop = sp; + } + } + + // set keys pressed + function keyPressed(e) { + shiftKey = e.shiftKey; + altKey = e.altKey; + ctrlKey = (!(e.altKey && e.ctrlKey)) ? (e.ctrlKey || e.metaKey) : false; + + if (e.type === 'keydown') { + if (ctrlKey === true) { + li = $('a[accesskey="'+String.fromCharCode(e.keyCode)+'"]', header).parent('li'); + if (li.length !== 0) { + ctrlKey = false; + setTimeout(function() { + li.triggerHandler('mouseup'); + },1); + return false; + } + } + if (e.keyCode === 13 || e.keyCode === 10) { // Enter key + if (ctrlKey === true) { // Enter + Ctrl + ctrlKey = false; + markup(options.onCtrlEnter); + return options.onCtrlEnter.keepDefault; + } else if (shiftKey === true) { // Enter + Shift + shiftKey = false; + markup(options.onShiftEnter); + return options.onShiftEnter.keepDefault; + } else { // only Enter + markup(options.onEnter); + return options.onEnter.keepDefault; + } + } + if (e.keyCode === 9) { // Tab key + if (shiftKey == true || ctrlKey == true || altKey == true) { + return false; + } + if (caretOffset !== -1) { + get(); + caretOffset = $$.val().length - caretOffset; + set(caretOffset, 0); + caretOffset = -1; + return false; + } else { + markup(options.onTab); + return options.onTab.keepDefault; + } + } + } + } + + init(); + }); + }; + + $.fn.markItUpRemove = function() { + return this.each(function() { + var $$ = $(this).unbind().removeClass('markItUpEditor'); + $$.parent('div').parent('div.markItUp').parent('div').replaceWith($$); + } + ); + }; + + $.markItUp = function(settings) { + var options = { target:false }; + $.extend(options, settings); + if (options.target) { + return $(options.target).each(function() { + $(this).focus(); + $(this).trigger('insertion', [options]); + }); + } else { + $('textarea').trigger('insertion', [options]); + } + }; +})(jQuery); diff --git a/modules/cms-core/action/Action.class.php b/modules/cms-core/action/Action.class.php @@ -351,7 +351,8 @@ namespace cms\action { * Gefunden auf: * @see http://simon.incutio.com/archive/2003/04/23/conditionalGet * - * @param Timestamp Letztes Aenderungsdatum des Objektes + * @param $time int Letztes Aenderungsdatum des Objektes + * @param $expirationDuration int Gültigkeitsdauer */ protected function lastModified($time, $expirationDuration = 0) { diff --git a/modules/cms-core/action/ImageAction.class.php b/modules/cms-core/action/ImageAction.class.php @@ -4,7 +4,7 @@ namespace cms\action; use cms\model\Folder; use cms\model\Image; -use cms\model\Object; +use cms\model\BaseObject; use cms\model\File; use Http; diff --git a/modules/cms-core/action/LoginAction.class.php b/modules/cms-core/action/LoginAction.class.php @@ -9,7 +9,7 @@ use cms\model\Group; use cms\model\Value; use cms\model\Element; use cms\model\Page; -use cms\model\Object; +use cms\model\BaseObject; use cms\model\Language; use cms\model\Model; @@ -1089,9 +1089,9 @@ class LoginAction extends Action if ( !is_object($object) && @$conf['login']['start']['start_lastchanged_object'] ) { $objectid = Value::getLastChangedObjectByUserId($user->userid); - if ( Object::available($objectid)) + if ( BaseObject::available($objectid)) { - $object = new Object($objectid); + $object = new BaseObject($objectid); $object->load(); Session::setObject($object); @@ -1146,11 +1146,11 @@ class LoginAction extends Action { $user = Session::getUser(); $objectid = Value::getLastChangedObjectByUserId($user->userid); - if ( Object::available($objectid)) + if ( BaseObject::available($objectid)) { // Das Projekt des zuletzt geänderten Objekts ermitteln // und dieses Projekt starten. - $o = new Object( $objectid ); + $o = new BaseObject( $objectid ); $o->load(); $project = new Project($o->projectid); @@ -1429,9 +1429,9 @@ class LoginAction extends Action } - if ( isset($vars[REQ_PARAM_OBJECT_ID]) && Object::available($vars[REQ_PARAM_OBJECT_ID]) ) + if ( isset($vars[REQ_PARAM_OBJECT_ID]) && BaseObject::available($vars[REQ_PARAM_OBJECT_ID]) ) { - $object = new Object( $vars[REQ_PARAM_OBJECT_ID] ); + $object = new BaseObject( $vars[REQ_PARAM_OBJECT_ID] ); $object->objectLoadRaw(); Session::setObject( $object ); @@ -1660,7 +1660,7 @@ class LoginAction extends Action } elseif ( $objectid != 0 ) { - $object = new Object( $objectid ); + $object = new BaseObject( $objectid ); $object->objectLoad(); Session::setObject($object); } diff --git a/modules/cms-core/model/Folder.class.php b/modules/cms-core/model/Folder.class.php @@ -25,7 +25,7 @@ namespace cms\model; * @author $Author$ * @package openrat.objects */ -class Folder extends Object +class Folder extends BaseObject { var $folderid; var $projectid; @@ -201,7 +201,7 @@ class Folder extends Object $res = $sql->getAll(); foreach( $res as $row ) { - $o = new Object( $row['id'] ); + $o = new BaseObject( $row['id'] ); $o->setDatabaseRow( $row ); $liste[] = $o; } @@ -263,7 +263,7 @@ class Folder extends Object foreach( $this->getObjectIds() as $oid ) { - $o = new Object( $oid ); + $o = new BaseObject( $oid ); $o->objectLoadRaw(); if ( $o->isPage && $withPages ) @@ -435,7 +435,7 @@ class Folder extends Object /** * Ermittelt die erste Seite oder Verkn�pfung in diesem Ordner. * - * @return Object Objekt + * @return BaseObject Objekt */ public function getFirstPage() { @@ -450,7 +450,7 @@ class Folder extends Object $oid = intval($sql->getOne()); if ( $oid != 0 ) - $o = new Object($oid); + $o = new BaseObject($oid); else $o = null; @@ -461,7 +461,7 @@ class Folder extends Object /** * Ermittelt die erste Seite oder Verkn�pfung in diesem Ordner. * - * @return Object Objekt + * @return BaseObject Objekt */ function getFirstPageOrLink() { @@ -476,7 +476,7 @@ class Folder extends Object $oid = intval($sql->getOne()); if ( $oid != 0 ) - $o = new Object($oid); + $o = new BaseObject($oid); else $o = null; @@ -497,7 +497,7 @@ class Folder extends Object $oid = intval($sql->getOne()); if ( $oid != 0 ) - $o = new Object($oid); + $o = new BaseObject($oid); else $o = null; @@ -833,7 +833,7 @@ SQL // diesem Ordner foreach( $this->getObjectIds() as $oid ) { - $object = new Object( $oid ); + $object = new BaseObject( $oid ); { $object->load(); diff --git a/modules/cms-core/model/ObjectFactory.php b/modules/cms-core/model/ObjectFactory.php @@ -21,7 +21,7 @@ class ObjectFactory { function create( $objectid ) { - $o = new Object( $objectid ); + $o = new BaseObject( $objectid ); switch( $o->getType() ) { diff --git a/modules/cms-macros/macro/BlockMenu.class.php b/modules/cms-macros/macro/BlockMenu.class.php @@ -28,7 +28,7 @@ // // --------------------------------------------------------------------------- use cms\model\Folder; -use cms\model\Object; +use cms\model\BaseObject; /** @@ -67,7 +67,7 @@ class BlockMenu extends Macro // Schleife ueber alle Inhalte des Root-Ordners foreach( $folder->getObjectIds() as $id ) { - $o = new Object( $id ); + $o = new BaseObject( $id ); $o->languageid = $this->page->languageid; $o->load(); if ( $o->isFolder ) // Nur wenn Ordner @@ -96,7 +96,7 @@ class BlockMenu extends Macro // Schleife ber alle Objekte im aktuellen Ordner foreach( $f->getObjectIds() as $xid ) { - $o = new Object( $xid ); + $o = new BaseObject( $xid ); $o->languageid = $this->page->languageid; $o->load(); diff --git a/modules/cms-macros/macro/Link.class.php b/modules/cms-macros/macro/Link.class.php @@ -27,7 +27,7 @@ // Beispiele fuer dynamische Templateelemente // // --------------------------------------------------------------------------- -use cms\model\Object; +use cms\model\BaseObject; /** @@ -45,7 +45,7 @@ class NextPage extends Macro function execute() { // Lesen des Ordners - $o = new Object( $this->targetid ); + $o = new BaseObject( $this->targetid ); $o->load(); if ( empty($this->name ) ) $this->name = $o->name; diff --git a/modules/cms-macros/macro/MainMenu.class.php b/modules/cms-macros/macro/MainMenu.class.php @@ -28,7 +28,7 @@ // // --------------------------------------------------------------------------- use cms\model\Folder; -use cms\model\Object; +use cms\model\BaseObject; /** @@ -64,7 +64,7 @@ class MainMenu extends Macro // Schleife ueber alle Inhalte des Root-Ordners foreach( $folder->getObjectIds() as $id ) { - $o = new Object( $id ); + $o = new BaseObject( $id ); $o->languageid = $this->page->languageid; $o->load(); if ( $o->isFolder ) // Nur wenn Ordner diff --git a/modules/cms-ui/themes/default/html/views/file/edit.php b/modules/cms-ui/themes/default/html/views/file/edit.php @@ -0,0 +1,21 @@ + + + <form name="" target="_self" action="<?php echo OR_ACTION ?>" data-method="<?php echo OR_METHOD ?>" data-action="<?php echo OR_ACTION ?>" data-id="<?php echo OR_ID ?>" method="POST" enctype="application/x-www-form-urlencoded" class="<?php echo OR_ACTION ?>" data-async="" data-autosave=""><input type="submit" class="invisible" /><input type="hidden" name="<?php echo REQ_PARAM_TOKEN ?>" value="<?php echo token() ?>" /><input type="hidden" name="<?php echo REQ_PARAM_ACTION ?>" value="<?php echo OR_ACTION ?>" /><input type="hidden" name="<?php echo REQ_PARAM_SUBACTION ?>" value="<?php echo OR_METHOD ?>" /><input type="hidden" name="<?php echo REQ_PARAM_ID ?>" value="<?php echo OR_ID ?>" /> + <div class="headermenu"><div class="toolbar-icon clickable"><a href="javascript:void(0);" title="<?php echo lang('MENU_VALUE') ?>" data-type="dialog" data-name="<?php echo lang('MENU_VALUE') ?>" data-method="value"><img src="./themes/default/images/icon/action/value.svg" title="<?php echo lang('MENU_value_DESC') ?>" /><?php echo lang('MENU_value') ?></a></div></div> + + <div class="label"> + </div> + <div class="line"> + <div class="input"> + <br/> + + <input size="40" id="req15206330032028550038_file" type="file" name="file" class="upload" /> + + <br/> + + <br/> + + </div> + </div> + <div class="bottom"><div class="command "><input type="button" class="submit ok" value="OK" /></div></div></form> + + \ No newline at end of file diff --git a/modules/cms-ui/themes/default/html/views/file/structure.php b/modules/cms-ui/themes/default/html/views/file/structure.php @@ -0,0 +1,7 @@ + + + <div class="structure tree"> + <?php include_once( 'modules/template-engine/components/html/tree/component-tree.php') ?><?php component_tree($outline) ?> + + </div> + + \ No newline at end of file diff --git a/modules/cms-ui/themes/default/html/views/folder/createpage.php b/modules/cms-ui/themes/default/html/views/folder/createpage.php @@ -0,0 +1,37 @@ + + + + + <form name="" target="_self" action="<?php echo OR_ACTION ?>" data-method="<?php echo OR_METHOD ?>" data-action="<?php echo OR_ACTION ?>" data-id="<?php echo OR_ID ?>" method="POST" enctype="application/x-www-form-urlencoded" class="<?php echo OR_ACTION ?>" data-async="" data-autosave=""><input type="submit" class="invisible" /><input type="hidden" name="<?php echo REQ_PARAM_TOKEN ?>" value="<?php echo token() ?>" /><input type="hidden" name="<?php echo REQ_PARAM_ACTION ?>" value="<?php echo OR_ACTION ?>" /><input type="hidden" name="<?php echo REQ_PARAM_SUBACTION ?>" value="<?php echo OR_METHOD ?>" /><input type="hidden" name="<?php echo REQ_PARAM_ID ?>" value="<?php echo OR_ID ?>" /> + <div class="line"> + <div class="label"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('global_TEMPLATE')))); ?></span> + + </div> + <div class="input"> + <div class="inputholder"><select id="<?php echo REQUEST_ID ?>_templateid" name="templateid" title="" class=""<?php if (count($templates)<=1) echo ' disabled="disabled"'; ?> size=1"><?php include_once( 'modules/template-engine/components/html/selectbox/component-select-box.php') ?><?php component_select_option_list($templates,'',0,0) ?><?php if (count($templates)==0) { ?><input type="hidden" name="templateid" value="" /><?php } ?><?php if (count($templates)==1) { ?><input type="hidden" name="templateid" value="<?php echo array_keys($templates)[0] ?>" /><?php } ?> + </select></div> + </div> + </div> + <div class="line"> + <div class="label"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('global_NAME')))); ?></span> + + </div> + <div class="input"> + <div class="inputholder"><input<?php if ('') echo ' disabled="true"' ?> id="<?php echo REQUEST_ID ?>_name" name="name<?php if ('') echo '_disabled' ?>" type="text" maxlength="256" class="focus,name" value="<?php echo Text::encodeHtml(@$name) ?>" /><?php if ('') { ?><input type="hidden" name="name" value="<?php $name ?>"/><?php } ?></div> + + </div> + </div> + <div class="line"> + <div class="label"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('global_DESCRIPTION')))); ?></span> + + </div> + <div class="input"> + <div class="inputholder"><textarea class="inputarea" name="description"><?php echo Text::encodeHtml('') ?></textarea></div> + + </div> + </div> + <div class="bottom"><div class="command "><input type="button" class="submit ok" value="OK" /></div></div></form> + + \ No newline at end of file diff --git a/modules/cms-ui/themes/default/html/views/folder/preview.php b/modules/cms-ui/themes/default/html/views/folder/preview.php @@ -0,0 +1,57 @@ + + + <table width="100%"> + <tr class="headline"> + <td class="help"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang(''.'GLOBAL_TYPE'.'')))); ?></span> + + <span class="text"><?php echo nl2br('&nbsp;/&nbsp;'); ?></span> + + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang(''.'GLOBAL_NAME'.'')))); ?></span> + + </td> + <td class="help"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang(''.'GLOBAL_LASTCHANGE'.'')))); ?></span> + + </td> + </tr> + <?php $if3=(!empty($up_url)); if($if3){?> + <tr class="data"> + <td> + <img class="" title="" src="./modules/cms-ui/themes/default/images/icon_folder_up.png" /> + + <span class="text"><?php echo nl2br('..'); ?></span> + + </td> + <td> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(''))); ?></span> + + </td> + </tr> + <?php } ?> + <?php foreach($object as $list_key=>$list_value){ ?><?php extract($list_value) ?> + <tr class="data"> + <td title="<?php echo $desc ?>" data-name="<?php echo $name ?>" data-action="<?php echo $type ?>" data-id="<?php echo $id ?>" class="clickable <?php echo $class ?>"> + <img class="" title="" src="./modules/cms-ui/themes/default/images/icon_<?php echo $icon ?>.png" /> + + <span class="text"><?php echo nl2br(encodeHtml(htmlentities($name))); ?></span> + + <span class="text"><?php echo nl2br('&nbsp;'); ?></span> + + </td> + <td> + <?php include_once( 'modules/template-engine/components/html/date/component-date.php') ?><?php component_date($date) ?> + + </td> + </tr> + <?php } ?> + <?php $if3=(empty($object)); if($if3){?> + <tr> + <td colspan="2"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('GLOBAL_NOT_FOUND')))); ?></span> + + </td> + </tr> + <?php } ?> + </table> + + \ No newline at end of file diff --git a/modules/cms-ui/themes/default/html/views/folder/pub.php b/modules/cms-ui/themes/default/html/views/folder/pub.php @@ -0,0 +1,129 @@ + + + <?php $if2=(config('security','nopublish')); if($if2){?> + <div class="message warn"> + <span class="help"><?php echo nl2br(encodeHtml(htmlentities(lang(''.'GLOBAL_NOPUBLISH_DESC'.'')))); ?></span> + + </div> + <?php } ?> + <form name="" target="_self" action="<?php echo OR_ACTION ?>" data-method="<?php echo OR_METHOD ?>" data-action="<?php echo OR_ACTION ?>" data-id="<?php echo OR_ID ?>" method="POST" enctype="application/x-www-form-urlencoded" class="<?php echo OR_ACTION ?>" data-async="1" data-autosave=""><input type="submit" class="invisible" /><input type="hidden" name="<?php echo REQ_PARAM_TOKEN ?>" value="<?php echo token() ?>" /><input type="hidden" name="<?php echo REQ_PARAM_ACTION ?>" value="<?php echo OR_ACTION ?>" /><input type="hidden" name="<?php echo REQ_PARAM_SUBACTION ?>" value="<?php echo OR_METHOD ?>" /><input type="hidden" name="<?php echo REQ_PARAM_ID ?>" value="<?php echo OR_ID ?>" /> + <?php $if3=(!empty($pages)); if($if3){?> + <?php $if4=(!empty($subdirs)); if($if4){?> + <div class="line"> + <div class="label"> + </div> + <div class="input"> + <?php { $tmpname = 'pages';$default = '';$readonly = ''; + if ( isset($$tmpname) ) + $checked = $$tmpname; + else + $checked = $default; + + ?><input class="checkbox" type="checkbox" id="<?php echo REQUEST_ID ?>_<?php echo $tmpname ?>" name="<?php echo $tmpname ?>" <?php if ($readonly) echo ' disabled="disabled"' ?> value="1" <?php if( $checked ) echo 'checked="checked"' ?> /><?php + + if ( $readonly && $checked ) + { + ?><input type="hidden" name="<?php echo $tmpname ?>" value="1" /><?php + } + } ?> + + <label for="<?php echo REQUEST_ID ?>_pages" class="label"> + <span class="text"><?php echo nl2br('&nbsp;'); ?></span> + + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('global_pages')))); ?></span> + + </label> + </div> + </div> + <?php } ?> + <?php } ?> + <?php $if3=(!empty($files)); if($if3){?> + <?php $if4=($subdirs); if($if4){?> + <div class="line"> + <div class="label"> + </div> + <div class="input"> + <?php { $tmpname = 'files';$default = '';$readonly = ''; + if ( isset($$tmpname) ) + $checked = $$tmpname; + else + $checked = $default; + + ?><input class="checkbox" type="checkbox" id="<?php echo REQUEST_ID ?>_<?php echo $tmpname ?>" name="<?php echo $tmpname ?>" <?php if ($readonly) echo ' disabled="disabled"' ?> value="1" <?php if( $checked ) echo 'checked="checked"' ?> /><?php + + if ( $readonly && $checked ) + { + ?><input type="hidden" name="<?php echo $tmpname ?>" value="1" /><?php + } + } ?> + + <label for="<?php echo REQUEST_ID ?>_files" class="label"> + <span class="text"><?php echo nl2br('&nbsp;'); ?></span> + + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('global_files')))); ?></span> + + </label> + </div> + </div> + <?php } ?> + <?php } ?> + <fieldset class="<?php echo '1'?" open":"" ?><?php echo '1'?" show":"" ?>"><legend><div class="arrow-right closed" /><div class="arrow-down open" /><?php echo lang('options') ?></legend><div> + <?php $if4=(!empty($subdirs)); if($if4){?> + <div class="line"> + <div class="label"> + </div> + <div class="input"> + <?php { $tmpname = 'subdirs';$default = '';$readonly = ''; + if ( isset($$tmpname) ) + $checked = $$tmpname; + else + $checked = $default; + + ?><input class="checkbox" type="checkbox" id="<?php echo REQUEST_ID ?>_<?php echo $tmpname ?>" name="<?php echo $tmpname ?>" <?php if ($readonly) echo ' disabled="disabled"' ?> value="1" <?php if( $checked ) echo 'checked="checked"' ?> /><?php + + if ( $readonly && $checked ) + { + ?><input type="hidden" name="<?php echo $tmpname ?>" value="1" /><?php + } + } ?> + + <label for="<?php echo REQUEST_ID ?>_subdirs" class="label"> + <span class="text"><?php echo nl2br('&nbsp;'); ?></span> + + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('GLOBAL_PUBLISH_WITH_SUBDIRS')))); ?></span> + + </label> + </div> + </div> + <?php } ?> + <?php $if4=(!empty($clean)); if($if4){?> + <div class="line"> + <div class="label"> + </div> + <div class="input"> + <?php { $tmpname = 'clean';$default = '';$readonly = ''; + if ( isset($$tmpname) ) + $checked = $$tmpname; + else + $checked = $default; + + ?><input class="checkbox" type="checkbox" id="<?php echo REQUEST_ID ?>_<?php echo $tmpname ?>" name="<?php echo $tmpname ?>" <?php if ($readonly) echo ' disabled="disabled"' ?> value="1" <?php if( $checked ) echo 'checked="checked"' ?> /><?php + + if ( $readonly && $checked ) + { + ?><input type="hidden" name="<?php echo $tmpname ?>" value="1" /><?php + } + } ?> + + <label for="<?php echo REQUEST_ID ?>_clean" class="label"> + <span class="text"><?php echo nl2br('&nbsp;'); ?></span> + + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('global_CLEAN_AFTER_PUBLISH')))); ?></span> + + </label> + </div> + </div> + <?php } ?> + </div></fieldset> + <div class="bottom"><div class="command 1"><input type="button" class="submit ok" value="<?php echo lang('publish') ?>" /></div></div></form> + + \ No newline at end of file diff --git a/modules/cms-ui/themes/default/html/views/language/advanced.php b/modules/cms-ui/themes/default/html/views/language/advanced.php @@ -0,0 +1,27 @@ + + + + + <form name="" target="_self" action="<?php echo OR_ACTION ?>" data-method="<?php echo OR_METHOD ?>" data-action="<?php echo OR_ACTION ?>" data-id="<?php echo OR_ID ?>" method="post" enctype="application/x-www-form-urlencoded" class="<?php echo OR_ACTION ?>" data-async="" data-autosave=""><input type="submit" class="invisible" /><input type="hidden" name="<?php echo REQ_PARAM_TOKEN ?>" value="<?php echo token() ?>" /><input type="hidden" name="<?php echo REQ_PARAM_ACTION ?>" value="<?php echo OR_ACTION ?>" /><input type="hidden" name="<?php echo REQ_PARAM_SUBACTION ?>" value="<?php echo OR_METHOD ?>" /><input type="hidden" name="<?php echo REQ_PARAM_ID ?>" value="<?php echo OR_ID ?>" /> + <div class="line"> + <div class="label"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('GLOBAL_NAME')))); ?></span> + + </div> + <div class="input"> + <div class="inputholder"><input<?php if ('') echo ' disabled="true"' ?> id="<?php echo REQUEST_ID ?>_name" name="name<?php if ('') echo '_disabled' ?>" type="text" maxlength="256" class="focus" value="<?php echo Text::encodeHtml(@$name) ?>" /><?php if ('') { ?><input type="hidden" name="name" value="<?php $name ?>"/><?php } ?></div> + + </div> + </div> + <div class="line"> + <div class="label"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('LANGUAGE_ISOCODE')))); ?></span> + + </div> + <div class="input"> + <div class="inputholder"><input<?php if ('') echo ' disabled="true"' ?> id="<?php echo REQUEST_ID ?>_isocode" name="isocode<?php if ('') echo '_disabled' ?>" type="text" maxlength="256" class="text" value="<?php echo Text::encodeHtml(@$isocode) ?>" /><?php if ('') { ?><input type="hidden" name="isocode" value="<?php $isocode ?>"/><?php } ?></div> + + </div> + </div> + <div class="bottom"><div class="command "><input type="button" class="submit ok" value="OK" /></div></div></form> + + \ No newline at end of file diff --git a/modules/cms-ui/themes/default/html/views/language/structure.php b/modules/cms-ui/themes/default/html/views/language/structure.php @@ -0,0 +1,7 @@ + + + <div class="structure tree"> + <?php include_once( 'modules/template-engine/components/html/tree/component-tree.php') ?><?php component_tree($outline) ?> + + </div> + + \ No newline at end of file diff --git a/modules/cms-ui/themes/default/html/views/login/register.php b/modules/cms-ui/themes/default/html/views/login/register.php @@ -0,0 +1,47 @@ + + + <?php $if2=(config('login','register')); if($if2){?> + <form name="" target="_self" action="<?php echo OR_ACTION ?>" data-method="<?php echo OR_METHOD ?>" data-action="<?php echo OR_ACTION ?>" data-id="<?php echo OR_ID ?>" method="POST" enctype="application/x-www-form-urlencoded" class="<?php echo OR_ACTION ?>" data-async="" data-autosave=""><input type="submit" class="invisible" /><input type="hidden" name="<?php echo REQ_PARAM_TOKEN ?>" value="<?php echo token() ?>" /><input type="hidden" name="<?php echo REQ_PARAM_ACTION ?>" value="<?php echo OR_ACTION ?>" /><input type="hidden" name="<?php echo REQ_PARAM_SUBACTION ?>" value="<?php echo OR_METHOD ?>" /><input type="hidden" name="<?php echo REQ_PARAM_ID ?>" value="<?php echo OR_ID ?>" /> + <div class="line logo"> + <div class="label"> + <img src="themes/default/images/logo_register.png ?>" + border="0" /> + </div> + <div class="input"> + <h2> + <?php echo langHtml('logo_register') ?> + </h2> + <p> + <?php echo langHtml('logo_register_text') ?> + </p> + + </div> +</div> + </div> + <div class="line"> + <div class="label"> + <label for="<?php echo REQUEST_ID ?>_mail" class="label"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('USER_MAIL')))); ?></span> + + </label> + </div> + <div class="input"> + <div class="inputholder"><input<?php if ('') echo ' disabled="true"' ?> id="<?php echo REQUEST_ID ?>_mail" name="mail<?php if ('') echo '_disabled' ?>" type="text" maxlength="256" class="focus" value="<?php echo Text::encodeHtml('') ?>" /><?php if ('') { ?><input type="hidden" name="mail" value="<?php '' ?>"/><?php } ?></div> + + </div> + </div> + <div class="line"> + <div class="label"> + </div> + <div class="input"> + </div> + </div> + <div class="bottom"><div class="command "><input type="button" class="submit ok" value="OK" /></div></div></form> + <?php } ?> + <?php if(!$if2){?> + <div class="message error"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang(''.'REGISTER_NOT_ENABLED'.'')))); ?></span> + + </div> + <?php } ?> + + \ No newline at end of file diff --git a/modules/cms-ui/themes/default/html/views/page/changetemplate.tpl.src.xml b/modules/cms-ui/themes/default/html/views/page/changetemplate.tpl.src.xml @@ -1,6 +1,9 @@ <output xmlns="http://www.openrat.de/template" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.openrat.de/template ../template.xsd"> <form method="get" subaction="changetemplateselectelements" visible="true" cancel="true" label="message:BUTTON_NEXT"> + <hidden name="templateid" /> + <hidden name="modelid" /> + <part class="line"> <part class="label"> <text text="page_template_old"></text> diff --git a/modules/cms-ui/themes/default/html/views/pageelement/prop.php b/modules/cms-ui/themes/default/html/views/pageelement/prop.php @@ -0,0 +1,121 @@ + + + <form name="" target="_self" action="<?php echo OR_ACTION ?>" data-method="<?php echo OR_METHOD ?>" data-action="<?php echo OR_ACTION ?>" data-id="<?php echo OR_ID ?>" method="POST" enctype="application/x-www-form-urlencoded" class="<?php echo OR_ACTION ?>" data-async="" data-autosave=""><input type="submit" class="invisible" /><input type="hidden" name="<?php echo REQ_PARAM_TOKEN ?>" value="<?php echo token() ?>" /><input type="hidden" name="<?php echo REQ_PARAM_ACTION ?>" value="<?php echo OR_ACTION ?>" /><input type="hidden" name="<?php echo REQ_PARAM_SUBACTION ?>" value="<?php echo OR_METHOD ?>" /><input type="hidden" name="<?php echo REQ_PARAM_ID ?>" value="<?php echo OR_ID ?>" /> + <table width="100%"> + <tr> + <td> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('name')))); ?></span> + + </td> + <td class="name"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities($name))); ?></span> + + </td> + </tr> + <tr> + <td> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('description')))); ?></span> + + </td> + <td> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities($description))); ?></span> + + </td> + </tr> + <tr> + <td> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('type')))); ?></span> + + </td> + <td class="filename"> + <img class="image-icon image-icon--element" title="" src="./modules/cms-ui/themes/default/images/icon/element/<?php echo $element_type ?>.svg" /> + + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang(''.'el_'.$element_type.''.'')))); ?></span> + + </td> + </tr> + <tr> + <td colspan="2"> + <fieldset class="<?php echo '1'?" open":"" ?><?php echo '1'?" show":"" ?>"><legend><div class="arrow-right closed" /><div class="arrow-down open" /><?php echo lang('additional_info') ?></legend><div> + </div></fieldset> + </td> + </tr> + <tr> + <td> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang(''.'template'.'')))); ?></span> + + </td> + <td> + <?php $if6=(!empty($template_url)); if($if6){?> + <a target="_self" data-url="<?php echo $template_url ?>" data-action="" data-method="<?php echo OR_METHOD ?>" data-id="<?php echo OR_ID ?>" href="javascript:void(0);"> + <img class="" title="" src="./modules/cms-ui/themes/default/images/icon/icon_template.png" /> + + <span class="text"><?php echo nl2br(encodeHtml(htmlentities($template_name))); ?></span> + + </a> + + <?php } ?> + <?php $if6=(empty($template_url)); if($if6){?> + <img class="" title="" src="./modules/cms-ui/themes/default/images/icon/icon_template.png" /> + + <span class="text"><?php echo nl2br(encodeHtml(htmlentities($template_name))); ?></span> + + <?php } ?> + </td> + </tr> + <tr> + <td> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang(''.'element'.'')))); ?></span> + + </td> + <td> + <?php $if6=(!empty($element_url)); if($if6){?> + <a target="_self" data-url="<?php echo $element_url ?>" data-action="" data-method="<?php echo OR_METHOD ?>" data-id="<?php echo OR_ID ?>" href="javascript:void(0);"> + <img class="image-icon image-icon--element" title="" src="./modules/cms-ui/themes/default/images/icon/element/<?php echo $element_type ?>.svg" /> + + <span class="text"><?php echo nl2br(encodeHtml(htmlentities($element_name))); ?></span> + + </a> + + <?php } ?> + <?php $if6=(empty($element_url)); if($if6){?> + <img class="" title="" src="./modules/cms-ui/themes/default/images/icon/element.png" /> + + <span class="text"><?php echo nl2br(encodeHtml(htmlentities($element_name))); ?></span> + + <?php } ?> + </td> + </tr> + <tr> + <td colspan="2"> + <fieldset class="<?php echo '1'?" open":"" ?><?php echo '1'?" show":"" ?>"><legend><div class="arrow-right closed" /><div class="arrow-down open" /><?php echo lang('prop_userinfo') ?></legend><div> + </div></fieldset> + </td> + </tr> + <tr> + <td> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('lastchange')))); ?></span> + + </td> + <td> + <table width="100%"> + <tr> + <td> + <img class="" title="" src="./modules/cms-ui/themes/default/images/icon/el_date.png" /> + + <?php include_once( 'modules/template-engine/components/html/date/component-date.php') ?><?php component_date($lastchange_date) ?> + + </td> + <td> + <img class="" title="" src="./modules/cms-ui/themes/default/images/icon/user.png" /> + + <?php include_once( 'modules/template-engine/components/html/user/component-user.php') ?><?php component_user($lastchange_user) ?> + + </td> + </tr> + </table> + </td> + </tr> + </table> + <div class="bottom"><div class="command "><input type="button" class="submit ok" value="OK" /></div></div></form> + + \ No newline at end of file diff --git a/modules/cms-ui/themes/default/html/views/profile/pw.php b/modules/cms-ui/themes/default/html/views/profile/pw.php @@ -0,0 +1,69 @@ + + + <form name="" target="_self" action="<?php echo OR_ACTION ?>" data-method="<?php echo OR_METHOD ?>" data-action="<?php echo OR_ACTION ?>" data-id="<?php echo OR_ID ?>" method="POST" enctype="application/x-www-form-urlencoded" class="<?php echo OR_ACTION ?>" data-async="" data-autosave=""><input type="submit" class="invisible" /><input type="hidden" name="<?php echo REQ_PARAM_TOKEN ?>" value="<?php echo token() ?>" /><input type="hidden" name="<?php echo REQ_PARAM_ACTION ?>" value="<?php echo OR_ACTION ?>" /><input type="hidden" name="<?php echo REQ_PARAM_SUBACTION ?>" value="<?php echo OR_METHOD ?>" /><input type="hidden" name="<?php echo REQ_PARAM_ID ?>" value="<?php echo OR_ID ?>" /> + <?php $if3=($pwchange_enabled); if($if3){?> + <div class="line logo"> + <div class="label"> + <img src="themes/default/images/logo_changepassword.png ?>" + border="0" /> + </div> + <div class="input"> + <h2> + <?php echo langHtml('logo_changepassword') ?> + </h2> + <p> + <?php echo langHtml('logo_changepassword_text') ?> + </p> + + </div> +</div> + </div> + <fieldset class="<?php echo '1'?" open":"" ?><?php echo '1'?" show":"" ?>"><legend><div class="arrow-right closed" /><div class="arrow-down open" /><?php echo lang('user_act_password') ?></legend><div> + <div class="line"> + <div class="label"> + <label for="<?php echo REQUEST_ID ?>_act_password" class="label"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('user_password')))); ?></span> + + </label> + </div> + <div class="input"> + <div class="inputholder"><input type="password" name="act_password" id="<?php echo REQUEST_ID ?>_act_password" size="40" maxlength="256" class="focus" value="<?php echo @$act_password?>" /></div> + + </div> + </div> + </div></fieldset> + <fieldset class="<?php echo '1'?" open":"" ?><?php echo '1'?" show":"" ?>"><legend><div class="arrow-right closed" /><div class="arrow-down open" /><?php echo lang('user_new_password') ?></legend><div> + <div class="line"> + <div class="label"> + <label for="<?php echo REQUEST_ID ?>_password1" class="label"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('user_new_password')))); ?></span> + + </label> + </div> + <div class="input"> + <div class="inputholder"><input type="password" name="password1" id="<?php echo REQUEST_ID ?>_password1" size="40" maxlength="256" class="" value="<?php echo @$password1?>" /></div> + + </div> + </div> + <div class="line"> + <div class="label"> + <label for="<?php echo REQUEST_ID ?>_password2" class="label"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('user_new_password_repeat')))); ?></span> + + </label> + </div> + <div class="input"> + <div class="inputholder"><input type="password" name="password2" id="<?php echo REQUEST_ID ?>_password2" size="40" maxlength="256" class="" value="<?php echo @$password2?>" /></div> + + </div> + </div> + </div></fieldset> + <?php } ?> + <?php if(!$if3){?> + <div class="message warn"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang(''.'pwchange_not_allowed'.'')))); ?></span> + + </div> + <?php } ?> + <div class="bottom"><div class="command "><input type="button" class="submit ok" value="OK" /></div></div></form> + + \ No newline at end of file diff --git a/modules/cms-ui/themes/default/html/views/project/maintenance.php b/modules/cms-ui/themes/default/html/views/project/maintenance.php @@ -0,0 +1,29 @@ + + + + + <form name="" target="_self" action="<?php echo OR_ACTION ?>" data-method="<?php echo OR_METHOD ?>" data-action="<?php echo OR_ACTION ?>" data-id="<?php echo OR_ID ?>" method="POST" enctype="application/x-www-form-urlencoded" class="<?php echo OR_ACTION ?>" data-async="" data-autosave=""><input type="submit" class="invisible" /><input type="hidden" name="<?php echo REQ_PARAM_TOKEN ?>" value="<?php echo token() ?>" /><input type="hidden" name="<?php echo REQ_PARAM_ACTION ?>" value="<?php echo OR_ACTION ?>" /><input type="hidden" name="<?php echo REQ_PARAM_SUBACTION ?>" value="<?php echo OR_METHOD ?>" /><input type="hidden" name="<?php echo REQ_PARAM_ID ?>" value="<?php echo OR_ID ?>" /> + <fieldset class="<?php echo '1'?" open":"" ?><?php echo '1'?" show":"" ?>"><legend><div class="arrow-right closed" /><div class="arrow-down open" /><?php echo lang('options') ?></legend><div> + <div> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(''))); ?></span> + + <input class="radio" type="radio" id="<?php echo REQUEST_ID ?>_type_check_limit" name="type" value="check_limit"<?php if('check_limit'==@$type)echo ' checked="checked"' ?> /> + + <label for="<?php echo REQUEST_ID ?>_type_check_limit" class="label"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang(''.'project_check_limit'.'')))); ?></span> + + </label> + </div> + <div> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(''))); ?></span> + + <input class="radio" type="radio" id="<?php echo REQUEST_ID ?>_type_check_files" name="type" value="check_files"<?php if('check_files'==@$type)echo ' checked="checked"' ?> /> + + <label for="<?php echo REQUEST_ID ?>_type_check_files" class="label"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang(''.'project_check_files'.'')))); ?></span> + + </label> + </div> + </div></fieldset> + <div class="bottom"><div class="command "><input type="button" class="submit ok" value="OK" /></div></div></form> + + \ No newline at end of file diff --git a/modules/cms-ui/themes/default/html/views/template/edit.php b/modules/cms-ui/themes/default/html/views/template/edit.php @@ -37,7 +37,7 @@ <?php } ?> <tr class="data"> <td colspan="2" class="clickable"> - <a target="_self" data-type="view" data-action="" data-method="addel" data-id="<?php echo OR_ID ?>" href="javascript:void(0);"> + <a target="_self" data-type="view" data-action="template" data-method="addel" data-id="<?php echo $templateid ?>" href="javascript:void(0);"> <img class="" title="" src="./modules/cms-ui/themes/default/images/icon/add.png" /> <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang(''.'menu_template_addel'.'')))); ?></span> diff --git a/modules/cms-ui/themes/default/html/views/template/edit.tpl.src.xml b/modules/cms-ui/themes/default/html/views/template/edit.tpl.src.xml @@ -31,7 +31,7 @@ </if> <row class="data"> <column colspan="2" class="clickable"> - <link type="view" subaction="addel"> + <link type="view" subaction="addel" action="template" id="var:templateid"> <image icon="add" /> <text key="menu_template_addel"></text> </link> diff --git a/modules/cms-ui/themes/default/html/views/template/info.php b/modules/cms-ui/themes/default/html/views/template/info.php @@ -0,0 +1,34 @@ + + + <table width="100%"> + <tr class="data"> + <td colspan="1"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang(''.'id'.'')))); ?></span> + + </td> + <td> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities($id))); ?></span> + + </td> + </tr> + <tr class="headline"> + <td colspan="2"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang(''.'pages'.'')))); ?></span> + + </td> + </tr> + <?php foreach($pages as $pageid=>$name){ ?> + <tr class="data"> + <td colspan="2"> + <img class="" title="" src="./modules/cms-ui/themes/default/images/icon/page.png" /> + + <a target="_self" data-action="main" data-method="page" data-id="<?php echo $pageid ?>" href="javascript:void(0);"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities($name))); ?></span> + + </a> + + </td> + </tr> + <?php } ?> + </table> + + \ No newline at end of file diff --git a/modules/cms-ui/themes/default/html/views/template/src.tpl.src.xml b/modules/cms-ui/themes/default/html/views/template/src.tpl.src.xml @@ -2,9 +2,8 @@ xsi:schemaLocation="http://www.openrat.de/template ../template.xsd"> <header views="srcelement" back="true"></header> <form> - <!-- - <inputarea rows="25" cols="80" name="src" class="editor"></inputarea> - --> + <hidden name="templateid" /> + <hidden name="modelid" /> <editor type="code" name="src" mode="htmlmixed" /> </form> </output> \ No newline at end of file diff --git a/modules/cms-ui/themes/default/html/views/user/info.php b/modules/cms-ui/themes/default/html/views/user/info.php @@ -0,0 +1,46 @@ + + + + + <?php $if2=!(empty($image)); if($if2){?> + <div class="line"> + <div class="line"> + <img class="" title="" src="<?php echo $image ?>" /> + + </div> + </div> + <?php } ?> + <div class="line"> + <span class="name"><?php echo nl2br(encodeHtml(htmlentities($name))); ?></span> + + </div> + <div class="line"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities($fullname))); ?></span> + + </div> + <?php $if2=(config('security','user','show_admin_mail')); if($if2){?> + <div class="line"> + <a target="_self" data-action="<?php echo $mail ?>" data-method="<?php echo OR_METHOD ?>" data-id="<?php echo OR_ID ?>" href="javascript:void(0);"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities($mail))); ?></span> + + </a> + + </div> + <?php } ?> + <div class="line"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities($desc))); ?></span> + + </div> + <div class="line"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('user_tel')))); ?></span> + + <span class="text"><?php echo nl2br(encodeHtml(htmlentities($tel))); ?></span> + + </div> + <?php $if2=($is_admin); if($if2){?> + <div class="line"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang(''.'user_admin'.'')))); ?></span> + + </div> + <?php } ?> + + \ No newline at end of file diff --git a/modules/cms-ui/themes/default/html/views/user/memberships.php b/modules/cms-ui/themes/default/html/views/user/memberships.php @@ -0,0 +1,49 @@ + + + <form name="" target="_self" action="<?php echo OR_ACTION ?>" data-method="<?php echo OR_METHOD ?>" data-action="<?php echo OR_ACTION ?>" data-id="<?php echo OR_ID ?>" method="POST" enctype="application/x-www-form-urlencoded" class="<?php echo OR_ACTION ?>" data-async="" data-autosave="1"><input type="submit" class="invisible" /><input type="hidden" name="<?php echo REQ_PARAM_TOKEN ?>" value="<?php echo token() ?>" /><input type="hidden" name="<?php echo REQ_PARAM_ACTION ?>" value="<?php echo OR_ACTION ?>" /><input type="hidden" name="<?php echo REQ_PARAM_SUBACTION ?>" value="<?php echo OR_METHOD ?>" /><input type="hidden" name="<?php echo REQ_PARAM_ID ?>" value="<?php echo OR_ID ?>" /> + <table width="100%"> + <tr class="headline"> + <td colspan="2"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang(''.'group'.'')))); ?></span> + + </td> + </tr> + <?php foreach($memberships as $list_key=>$list_value){ ?><?php extract($list_value) ?> + <tr class="data"> + <td width="10%"> + <?php { $tmpname = $var;$default = '';$readonly = ''; + if ( isset($$tmpname) ) + $checked = $$tmpname; + else + $checked = $default; + + ?><input class="checkbox" type="checkbox" id="<?php echo REQUEST_ID ?>_<?php echo $tmpname ?>" name="<?php echo $tmpname ?>" <?php if ($readonly) echo ' disabled="disabled"' ?> value="1" <?php if( $checked ) echo 'checked="checked"' ?> /><?php + + if ( $readonly && $checked ) + { + ?><input type="hidden" name="<?php echo $tmpname ?>" value="1" /><?php + } + } ?> + + </td> + <td> + <label for="<?php echo REQUEST_ID ?>_<?php echo $var ?>" class="label"> + <img class="" title="" src="./modules/cms-ui/themes/default/images/icon/icon_group.png" /> + + <span class="text"><?php echo nl2br(encodeHtml(htmlentities($name))); ?></span> + + </label> + </td> + </tr> + <?php } ?> + <tr> + <td colspan="2" class="act"> + <div class="invisible"><input type="submit" name="ok" class="%class%" + title="Bestätigen" + value="&nbsp;&nbsp;&nbsp;&nbsp;OK&nbsp;&nbsp;&nbsp;&nbsp;" /> + </div> + </td> + </tr> + </table> + <div class="bottom"><div class="command "><input type="button" class="submit ok" value="OK" /></div></div></form> + + \ No newline at end of file diff --git a/modules/editor/codemirror/.editorconfig b/modules/editor/codemirror/.editorconfig @@ -0,0 +1,7 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +end_of_line = lf +charset = utf-8 diff --git a/modules/editor/codemirror/.npmignore b/modules/editor/codemirror/.npmignore @@ -0,0 +1,11 @@ +/node_modules +/demo +/doc +/test +/test*.html +/index.html +/mode/*/*test.js +/mode/*/*.html +/mode/index.html +.* +bin diff --git a/modules/editor/codemirror/addon/comment/continuecomment.min.js b/modules/editor/codemirror/addon/comment/continuecomment.min.js @@ -0,0 +1,78 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + function continueComment(cm) { + if (cm.getOption("disableInput")) return CodeMirror.Pass; + var ranges = cm.listSelections(), mode, inserts = []; + for (var i = 0; i < ranges.length; i++) { + var pos = ranges[i].head + if (!/\bcomment\b/.test(cm.getTokenTypeAt(pos))) return CodeMirror.Pass; + var modeHere = cm.getModeAt(pos) + if (!mode) mode = modeHere; + else if (mode != modeHere) return CodeMirror.Pass; + + var insert = null; + if (mode.blockCommentStart && mode.blockCommentContinue) { + var line = cm.getLine(pos.line).slice(0, pos.ch) + var end = line.lastIndexOf(mode.blockCommentEnd), found + if (end != -1 && end == pos.ch - mode.blockCommentEnd.length) { + // Comment ended, don't continue it + } else if ((found = line.lastIndexOf(mode.blockCommentStart)) > -1 && found > end) { + insert = line.slice(0, found) + if (/\S/.test(insert)) { + insert = "" + for (var j = 0; j < found; ++j) insert += " " + } + } else if ((found = line.indexOf(mode.blockCommentContinue)) > -1 && !/\S/.test(line.slice(0, found))) { + insert = line.slice(0, found) + } + if (insert != null) insert += mode.blockCommentContinue + } + if (insert == null && mode.lineComment && continueLineCommentEnabled(cm)) { + var line = cm.getLine(pos.line), found = line.indexOf(mode.lineComment); + if (found > -1) { + insert = line.slice(0, found); + if (/\S/.test(insert)) insert = null; + else insert += mode.lineComment + line.slice(found + mode.lineComment.length).match(/^\s*/)[0]; + } + } + if (insert == null) return CodeMirror.Pass; + inserts[i] = "\n" + insert; + } + + cm.operation(function() { + for (var i = ranges.length - 1; i >= 0; i--) + cm.replaceRange(inserts[i], ranges[i].from(), ranges[i].to(), "+insert"); + }); + } + + function continueLineCommentEnabled(cm) { + var opt = cm.getOption("continueComments"); + if (opt && typeof opt == "object") + return opt.continueLineComment !== false; + return true; + } + + CodeMirror.defineOption("continueComments", null, function(cm, val, prev) { + if (prev && prev != CodeMirror.Init) + cm.removeKeyMap("continueComment"); + if (val) { + var key = "Enter"; + if (typeof val == "string") + key = val; + else if (typeof val == "object" && val.key) + key = val.key; + var map = {name: "continueComment"}; + map[key] = continueComment; + cm.addKeyMap(map); + } + }); +}); diff --git a/modules/editor/codemirror/addon/edit/trailingspace.js b/modules/editor/codemirror/addon/edit/trailingspace.js @@ -0,0 +1,27 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + CodeMirror.defineOption("showTrailingSpace", false, function(cm, val, prev) { + if (prev == CodeMirror.Init) prev = false; + if (prev && !val) + cm.removeOverlay("trailingspace"); + else if (!prev && val) + cm.addOverlay({ + token: function(stream) { + for (var l = stream.string.length, i = l; i && /\s/.test(stream.string.charAt(i - 1)); --i) {} + if (i > stream.pos) { stream.pos = i; return null; } + stream.pos = l; + return "trailingspace"; + }, + name: "trailingspace" + }); + }); +}); diff --git a/modules/editor/codemirror/addon/edit/trailingspace.min.js b/modules/editor/codemirror/addon/edit/trailingspace.min.js @@ -0,0 +1,27 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + CodeMirror.defineOption("showTrailingSpace", false, function(cm, val, prev) { + if (prev == CodeMirror.Init) prev = false; + if (prev && !val) + cm.removeOverlay("trailingspace"); + else if (!prev && val) + cm.addOverlay({ + token: function(stream) { + for (var l = stream.string.length, i = l; i && /\s/.test(stream.string.charAt(i - 1)); --i) {} + if (i > stream.pos) { stream.pos = i; return null; } + stream.pos = l; + return "trailingspace"; + }, + name: "trailingspace" + }); + }); +}); diff --git a/modules/editor/codemirror/addon/fold/comment-fold.js b/modules/editor/codemirror/addon/fold/comment-fold.js @@ -0,0 +1,59 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.registerGlobalHelper("fold", "comment", function(mode) { + return mode.blockCommentStart && mode.blockCommentEnd; +}, function(cm, start) { + var mode = cm.getModeAt(start), startToken = mode.blockCommentStart, endToken = mode.blockCommentEnd; + if (!startToken || !endToken) return; + var line = start.line, lineText = cm.getLine(line); + + var startCh; + for (var at = start.ch, pass = 0;;) { + var found = at <= 0 ? -1 : lineText.lastIndexOf(startToken, at - 1); + if (found == -1) { + if (pass == 1) return; + pass = 1; + at = lineText.length; + continue; + } + if (pass == 1 && found < start.ch) return; + if (/comment/.test(cm.getTokenTypeAt(CodeMirror.Pos(line, found + 1))) && + (found == 0 || lineText.slice(found - endToken.length, found) == endToken || + !/comment/.test(cm.getTokenTypeAt(CodeMirror.Pos(line, found))))) { + startCh = found + startToken.length; + break; + } + at = found - 1; + } + + var depth = 1, lastLine = cm.lastLine(), end, endCh; + outer: for (var i = line; i <= lastLine; ++i) { + var text = cm.getLine(i), pos = i == line ? startCh : 0; + for (;;) { + var nextOpen = text.indexOf(startToken, pos), nextClose = text.indexOf(endToken, pos); + if (nextOpen < 0) nextOpen = text.length; + if (nextClose < 0) nextClose = text.length; + pos = Math.min(nextOpen, nextClose); + if (pos == text.length) break; + if (pos == nextOpen) ++depth; + else if (!--depth) { end = i; endCh = pos; break outer; } + ++pos; + } + } + if (end == null || line == end && endCh == startCh) return; + return {from: CodeMirror.Pos(line, startCh), + to: CodeMirror.Pos(end, endCh)}; +}); + +}); diff --git a/modules/editor/codemirror/addon/fold/foldgutter.min.js b/modules/editor/codemirror/addon/fold/foldgutter.min.js @@ -0,0 +1,146 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror"), require("./foldcode")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror", "./foldcode"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + CodeMirror.defineOption("foldGutter", false, function(cm, val, old) { + if (old && old != CodeMirror.Init) { + cm.clearGutter(cm.state.foldGutter.options.gutter); + cm.state.foldGutter = null; + cm.off("gutterClick", onGutterClick); + cm.off("change", onChange); + cm.off("viewportChange", onViewportChange); + cm.off("fold", onFold); + cm.off("unfold", onFold); + cm.off("swapDoc", onChange); + } + if (val) { + cm.state.foldGutter = new State(parseOptions(val)); + updateInViewport(cm); + cm.on("gutterClick", onGutterClick); + cm.on("change", onChange); + cm.on("viewportChange", onViewportChange); + cm.on("fold", onFold); + cm.on("unfold", onFold); + cm.on("swapDoc", onChange); + } + }); + + var Pos = CodeMirror.Pos; + + function State(options) { + this.options = options; + this.from = this.to = 0; + } + + function parseOptions(opts) { + if (opts === true) opts = {}; + if (opts.gutter == null) opts.gutter = "CodeMirror-foldgutter"; + if (opts.indicatorOpen == null) opts.indicatorOpen = "CodeMirror-foldgutter-open"; + if (opts.indicatorFolded == null) opts.indicatorFolded = "CodeMirror-foldgutter-folded"; + return opts; + } + + function isFolded(cm, line) { + var marks = cm.findMarks(Pos(line, 0), Pos(line + 1, 0)); + for (var i = 0; i < marks.length; ++i) + if (marks[i].__isFold && marks[i].find().from.line == line) return marks[i]; + } + + function marker(spec) { + if (typeof spec == "string") { + var elt = document.createElement("div"); + elt.className = spec + " CodeMirror-guttermarker-subtle"; + return elt; + } else { + return spec.cloneNode(true); + } + } + + function updateFoldInfo(cm, from, to) { + var opts = cm.state.foldGutter.options, cur = from; + var minSize = cm.foldOption(opts, "minFoldSize"); + var func = cm.foldOption(opts, "rangeFinder"); + cm.eachLine(from, to, function(line) { + var mark = null; + if (isFolded(cm, cur)) { + mark = marker(opts.indicatorFolded); + } else { + var pos = Pos(cur, 0); + var range = func && func(cm, pos); + if (range && range.to.line - range.from.line >= minSize) + mark = marker(opts.indicatorOpen); + } + cm.setGutterMarker(line, opts.gutter, mark); + ++cur; + }); + } + + function updateInViewport(cm) { + var vp = cm.getViewport(), state = cm.state.foldGutter; + if (!state) return; + cm.operation(function() { + updateFoldInfo(cm, vp.from, vp.to); + }); + state.from = vp.from; state.to = vp.to; + } + + function onGutterClick(cm, line, gutter) { + var state = cm.state.foldGutter; + if (!state) return; + var opts = state.options; + if (gutter != opts.gutter) return; + var folded = isFolded(cm, line); + if (folded) folded.clear(); + else cm.foldCode(Pos(line, 0), opts.rangeFinder); + } + + function onChange(cm) { + var state = cm.state.foldGutter; + if (!state) return; + var opts = state.options; + state.from = state.to = 0; + clearTimeout(state.changeUpdate); + state.changeUpdate = setTimeout(function() { updateInViewport(cm); }, opts.foldOnChangeTimeSpan || 600); + } + + function onViewportChange(cm) { + var state = cm.state.foldGutter; + if (!state) return; + var opts = state.options; + clearTimeout(state.changeUpdate); + state.changeUpdate = setTimeout(function() { + var vp = cm.getViewport(); + if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) { + updateInViewport(cm); + } else { + cm.operation(function() { + if (vp.from < state.from) { + updateFoldInfo(cm, vp.from, state.from); + state.from = vp.from; + } + if (vp.to > state.to) { + updateFoldInfo(cm, state.to, vp.to); + state.to = vp.to; + } + }); + } + }, opts.updateViewportTimeSpan || 400); + } + + function onFold(cm, from) { + var state = cm.state.foldGutter; + if (!state) return; + var line = from.line; + if (line >= state.from && line < state.to) + updateFoldInfo(cm, line, line + 1); + } +}); diff --git a/modules/editor/codemirror/addon/fold/indent-fold.min.js b/modules/editor/codemirror/addon/fold/indent-fold.min.js @@ -0,0 +1,48 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +function lineIndent(cm, lineNo) { + var text = cm.getLine(lineNo) + var spaceTo = text.search(/\S/) + if (spaceTo == -1 || /\bcomment\b/.test(cm.getTokenTypeAt(CodeMirror.Pos(lineNo, spaceTo + 1)))) + return -1 + return CodeMirror.countColumn(text, null, cm.getOption("tabSize")) +} + +CodeMirror.registerHelper("fold", "indent", function(cm, start) { + var myIndent = lineIndent(cm, start.line) + if (myIndent < 0) return + var lastLineInFold = null + + // Go through lines until we find a line that definitely doesn't belong in + // the block we're folding, or to the end. + for (var i = start.line + 1, end = cm.lastLine(); i <= end; ++i) { + var indent = lineIndent(cm, i) + if (indent == -1) { + } else if (indent > myIndent) { + // Lines with a greater indent are considered part of the block. + lastLineInFold = i; + } else { + // If this line has non-space, non-comment content, and is + // indented less or equal to the start line, it is the start of + // another block. + break; + } + } + if (lastLineInFold) return { + from: CodeMirror.Pos(start.line, cm.getLine(start.line).length), + to: CodeMirror.Pos(lastLineInFold, cm.getLine(lastLineInFold).length) + }; +}); + +}); diff --git a/modules/editor/codemirror/addon/fold/xml-fold.min.js b/modules/editor/codemirror/addon/fold/xml-fold.min.js @@ -0,0 +1,182 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + var Pos = CodeMirror.Pos; + function cmp(a, b) { return a.line - b.line || a.ch - b.ch; } + + var nameStartChar = "A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"; + var nameChar = nameStartChar + "\-\:\.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040"; + var xmlTagStart = new RegExp("<(/?)([" + nameStartChar + "][" + nameChar + "]*)", "g"); + + function Iter(cm, line, ch, range) { + this.line = line; this.ch = ch; + this.cm = cm; this.text = cm.getLine(line); + this.min = range ? Math.max(range.from, cm.firstLine()) : cm.firstLine(); + this.max = range ? Math.min(range.to - 1, cm.lastLine()) : cm.lastLine(); + } + + function tagAt(iter, ch) { + var type = iter.cm.getTokenTypeAt(Pos(iter.line, ch)); + return type && /\btag\b/.test(type); + } + + function nextLine(iter) { + if (iter.line >= iter.max) return; + iter.ch = 0; + iter.text = iter.cm.getLine(++iter.line); + return true; + } + function prevLine(iter) { + if (iter.line <= iter.min) return; + iter.text = iter.cm.getLine(--iter.line); + iter.ch = iter.text.length; + return true; + } + + function toTagEnd(iter) { + for (;;) { + var gt = iter.text.indexOf(">", iter.ch); + if (gt == -1) { if (nextLine(iter)) continue; else return; } + if (!tagAt(iter, gt + 1)) { iter.ch = gt + 1; continue; } + var lastSlash = iter.text.lastIndexOf("/", gt); + var selfClose = lastSlash > -1 && !/\S/.test(iter.text.slice(lastSlash + 1, gt)); + iter.ch = gt + 1; + return selfClose ? "selfClose" : "regular"; + } + } + function toTagStart(iter) { + for (;;) { + var lt = iter.ch ? iter.text.lastIndexOf("<", iter.ch - 1) : -1; + if (lt == -1) { if (prevLine(iter)) continue; else return; } + if (!tagAt(iter, lt + 1)) { iter.ch = lt; continue; } + xmlTagStart.lastIndex = lt; + iter.ch = lt; + var match = xmlTagStart.exec(iter.text); + if (match && match.index == lt) return match; + } + } + + function toNextTag(iter) { + for (;;) { + xmlTagStart.lastIndex = iter.ch; + var found = xmlTagStart.exec(iter.text); + if (!found) { if (nextLine(iter)) continue; else return; } + if (!tagAt(iter, found.index + 1)) { iter.ch = found.index + 1; continue; } + iter.ch = found.index + found[0].length; + return found; + } + } + function toPrevTag(iter) { + for (;;) { + var gt = iter.ch ? iter.text.lastIndexOf(">", iter.ch - 1) : -1; + if (gt == -1) { if (prevLine(iter)) continue; else return; } + if (!tagAt(iter, gt + 1)) { iter.ch = gt; continue; } + var lastSlash = iter.text.lastIndexOf("/", gt); + var selfClose = lastSlash > -1 && !/\S/.test(iter.text.slice(lastSlash + 1, gt)); + iter.ch = gt + 1; + return selfClose ? "selfClose" : "regular"; + } + } + + function findMatchingClose(iter, tag) { + var stack = []; + for (;;) { + var next = toNextTag(iter), end, startLine = iter.line, startCh = iter.ch - (next ? next[0].length : 0); + if (!next || !(end = toTagEnd(iter))) return; + if (end == "selfClose") continue; + if (next[1]) { // closing tag + for (var i = stack.length - 1; i >= 0; --i) if (stack[i] == next[2]) { + stack.length = i; + break; + } + if (i < 0 && (!tag || tag == next[2])) return { + tag: next[2], + from: Pos(startLine, startCh), + to: Pos(iter.line, iter.ch) + }; + } else { // opening tag + stack.push(next[2]); + } + } + } + function findMatchingOpen(iter, tag) { + var stack = []; + for (;;) { + var prev = toPrevTag(iter); + if (!prev) return; + if (prev == "selfClose") { toTagStart(iter); continue; } + var endLine = iter.line, endCh = iter.ch; + var start = toTagStart(iter); + if (!start) return; + if (start[1]) { // closing tag + stack.push(start[2]); + } else { // opening tag + for (var i = stack.length - 1; i >= 0; --i) if (stack[i] == start[2]) { + stack.length = i; + break; + } + if (i < 0 && (!tag || tag == start[2])) return { + tag: start[2], + from: Pos(iter.line, iter.ch), + to: Pos(endLine, endCh) + }; + } + } + } + + CodeMirror.registerHelper("fold", "xml", function(cm, start) { + var iter = new Iter(cm, start.line, 0); + for (;;) { + var openTag = toNextTag(iter), end; + if (!openTag || iter.line != start.line || !(end = toTagEnd(iter))) return; + if (!openTag[1] && end != "selfClose") { + var startPos = Pos(iter.line, iter.ch); + var endPos = findMatchingClose(iter, openTag[2]); + return endPos && {from: startPos, to: endPos.from}; + } + } + }); + CodeMirror.findMatchingTag = function(cm, pos, range) { + var iter = new Iter(cm, pos.line, pos.ch, range); + if (iter.text.indexOf(">") == -1 && iter.text.indexOf("<") == -1) return; + var end = toTagEnd(iter), to = end && Pos(iter.line, iter.ch); + var start = end && toTagStart(iter); + if (!end || !start || cmp(iter, pos) > 0) return; + var here = {from: Pos(iter.line, iter.ch), to: to, tag: start[2]}; + if (end == "selfClose") return {open: here, close: null, at: "open"}; + + if (start[1]) { // closing tag + return {open: findMatchingOpen(iter, start[2]), close: here, at: "close"}; + } else { // opening tag + iter = new Iter(cm, to.line, to.ch, range); + return {open: here, close: findMatchingClose(iter, start[2]), at: "open"}; + } + }; + + CodeMirror.findEnclosingTag = function(cm, pos, range, tag) { + var iter = new Iter(cm, pos.line, pos.ch, range); + for (;;) { + var open = findMatchingOpen(iter, tag); + if (!open) break; + var forward = new Iter(cm, pos.line, pos.ch, range); + var close = findMatchingClose(forward, open.tag); + if (close) return {open: open, close: close}; + } + }; + + // Used by addon/edit/closetag.js + CodeMirror.scanForClosingTag = function(cm, pos, name, end) { + var iter = new Iter(cm, pos.line, pos.ch, end ? {from: 0, to: end} : null); + return findMatchingClose(iter, name); + }; +}); diff --git a/modules/editor/codemirror/addon/hint/anyword-hint.js b/modules/editor/codemirror/addon/hint/anyword-hint.js @@ -0,0 +1,41 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + var WORD = /[\w$]+/, RANGE = 500; + + CodeMirror.registerHelper("hint", "anyword", function(editor, options) { + var word = options && options.word || WORD; + var range = options && options.range || RANGE; + var cur = editor.getCursor(), curLine = editor.getLine(cur.line); + var end = cur.ch, start = end; + while (start && word.test(curLine.charAt(start - 1))) --start; + var curWord = start != end && curLine.slice(start, end); + + var list = options && options.list || [], seen = {}; + var re = new RegExp(word.source, "g"); + for (var dir = -1; dir <= 1; dir += 2) { + var line = cur.line, endLine = Math.min(Math.max(line + dir * range, editor.firstLine()), editor.lastLine()) + dir; + for (; line != endLine; line += dir) { + var text = editor.getLine(line), m; + while (m = re.exec(text)) { + if (line == cur.line && m[0] === curWord) continue; + if ((!curWord || m[0].lastIndexOf(curWord, 0) == 0) && !Object.prototype.hasOwnProperty.call(seen, m[0])) { + seen[m[0]] = true; + list.push(m[0]); + } + } + } + } + return {list: list, from: CodeMirror.Pos(cur.line, start), to: CodeMirror.Pos(cur.line, end)}; + }); +}); diff --git a/modules/editor/codemirror/addon/hint/javascript-hint.js b/modules/editor/codemirror/addon/hint/javascript-hint.js @@ -0,0 +1,155 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + var Pos = CodeMirror.Pos; + + function forEach(arr, f) { + for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]); + } + + function arrayContains(arr, item) { + if (!Array.prototype.indexOf) { + var i = arr.length; + while (i--) { + if (arr[i] === item) { + return true; + } + } + return false; + } + return arr.indexOf(item) != -1; + } + + function scriptHint(editor, keywords, getToken, options) { + // Find the token at the cursor + var cur = editor.getCursor(), token = getToken(editor, cur); + if (/\b(?:string|comment)\b/.test(token.type)) return; + token.state = CodeMirror.innerMode(editor.getMode(), token.state).state; + + // If it's not a 'word-style' token, ignore the token. + if (!/^[\w$_]*$/.test(token.string)) { + token = {start: cur.ch, end: cur.ch, string: "", state: token.state, + type: token.string == "." ? "property" : null}; + } else if (token.end > cur.ch) { + token.end = cur.ch; + token.string = token.string.slice(0, cur.ch - token.start); + } + + var tprop = token; + // If it is a property, find out what it is a property of. + while (tprop.type == "property") { + tprop = getToken(editor, Pos(cur.line, tprop.start)); + if (tprop.string != ".") return; + tprop = getToken(editor, Pos(cur.line, tprop.start)); + if (!context) var context = []; + context.push(tprop); + } + return {list: getCompletions(token, context, keywords, options), + from: Pos(cur.line, token.start), + to: Pos(cur.line, token.end)}; + } + + function javascriptHint(editor, options) { + return scriptHint(editor, javascriptKeywords, + function (e, cur) {return e.getTokenAt(cur);}, + options); + }; + CodeMirror.registerHelper("hint", "javascript", javascriptHint); + + function getCoffeeScriptToken(editor, cur) { + // This getToken, it is for coffeescript, imitates the behavior of + // getTokenAt method in javascript.js, that is, returning "property" + // type and treat "." as indepenent token. + var token = editor.getTokenAt(cur); + if (cur.ch == token.start + 1 && token.string.charAt(0) == '.') { + token.end = token.start; + token.string = '.'; + token.type = "property"; + } + else if (/^\.[\w$_]*$/.test(token.string)) { + token.type = "property"; + token.start++; + token.string = token.string.replace(/\./, ''); + } + return token; + } + + function coffeescriptHint(editor, options) { + return scriptHint(editor, coffeescriptKeywords, getCoffeeScriptToken, options); + } + CodeMirror.registerHelper("hint", "coffeescript", coffeescriptHint); + + var stringProps = ("charAt charCodeAt indexOf lastIndexOf substring substr slice trim trimLeft trimRight " + + "toUpperCase toLowerCase split concat match replace search").split(" "); + var arrayProps = ("length concat join splice push pop shift unshift slice reverse sort indexOf " + + "lastIndexOf every some filter forEach map reduce reduceRight ").split(" "); + var funcProps = "prototype apply call bind".split(" "); + var javascriptKeywords = ("break case catch continue debugger default delete do else false finally for function " + + "if in instanceof new null return switch throw true try typeof var void while with").split(" "); + var coffeescriptKeywords = ("and break catch class continue delete do else extends false finally for " + + "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(" "); + + function forAllProps(obj, callback) { + if (!Object.getOwnPropertyNames || !Object.getPrototypeOf) { + for (var name in obj) callback(name) + } else { + for (var o = obj; o; o = Object.getPrototypeOf(o)) + Object.getOwnPropertyNames(o).forEach(callback) + } + } + + function getCompletions(token, context, keywords, options) { + var found = [], start = token.string, global = options && options.globalScope || window; + function maybeAdd(str) { + if (str.lastIndexOf(start, 0) == 0 && !arrayContains(found, str)) found.push(str); + } + function gatherCompletions(obj) { + if (typeof obj == "string") forEach(stringProps, maybeAdd); + else if (obj instanceof Array) forEach(arrayProps, maybeAdd); + else if (obj instanceof Function) forEach(funcProps, maybeAdd); + forAllProps(obj, maybeAdd) + } + + if (context && context.length) { + // If this is a property, see if it belongs to some object we can + // find in the current environment. + var obj = context.pop(), base; + if (obj.type && obj.type.indexOf("variable") === 0) { + if (options && options.additionalContext) + base = options.additionalContext[obj.string]; + if (!options || options.useGlobalScope !== false) + base = base || global[obj.string]; + } else if (obj.type == "string") { + base = ""; + } else if (obj.type == "atom") { + base = 1; + } else if (obj.type == "function") { + if (global.jQuery != null && (obj.string == '$' || obj.string == 'jQuery') && + (typeof global.jQuery == 'function')) + base = global.jQuery(); + else if (global._ != null && (obj.string == '_') && (typeof global._ == 'function')) + base = global._(); + } + while (base != null && context.length) + base = base[context.pop().string]; + if (base != null) gatherCompletions(base); + } else { + // If not, just look in the global object and any local scope + // (reading into JS mode internals to get at the local and global variables) + for (var v = token.state.localVars; v; v = v.next) maybeAdd(v.name); + for (var v = token.state.globalVars; v; v = v.next) maybeAdd(v.name); + if (!options || options.useGlobalScope !== false) + gatherCompletions(global); + forEach(keywords, maybeAdd); + } + return found; + } +}); diff --git a/modules/editor/codemirror/addon/hint/show-hint.css b/modules/editor/codemirror/addon/hint/show-hint.css @@ -0,0 +1,36 @@ +.CodeMirror-hints { + position: absolute; + z-index: 10; + overflow: hidden; + list-style: none; + + margin: 0; + padding: 2px; + + -webkit-box-shadow: 2px 3px 5px rgba(0,0,0,.2); + -moz-box-shadow: 2px 3px 5px rgba(0,0,0,.2); + box-shadow: 2px 3px 5px rgba(0,0,0,.2); + border-radius: 3px; + border: 1px solid silver; + + background: white; + font-size: 90%; + font-family: monospace; + + max-height: 20em; + overflow-y: auto; +} + +.CodeMirror-hint { + margin: 0; + padding: 0 4px; + border-radius: 2px; + white-space: pre; + color: black; + cursor: pointer; +} + +li.CodeMirror-hint-active { + background: #08f; + color: white; +} diff --git a/modules/editor/codemirror/addon/lint/css-lint.min.js b/modules/editor/codemirror/addon/lint/css-lint.min.js @@ -0,0 +1,40 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// Depends on csslint.js from https://github.com/stubbornella/csslint + +// declare global: CSSLint + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.registerHelper("lint", "css", function(text, options) { + var found = []; + if (!window.CSSLint) { + if (window.console) { + window.console.error("Error: window.CSSLint not defined, CodeMirror CSS linting cannot run."); + } + return found; + } + var results = CSSLint.verify(text, options), messages = results.messages, message = null; + for ( var i = 0; i < messages.length; i++) { + message = messages[i]; + var startLine = message.line -1, endLine = message.line -1, startCol = message.col -1, endCol = message.col; + found.push({ + from: CodeMirror.Pos(startLine, startCol), + to: CodeMirror.Pos(endLine, endCol), + message: message.message, + severity : message.type + }); + } + return found; +}); + +}); diff --git a/modules/editor/codemirror/addon/lint/html-lint.js b/modules/editor/codemirror/addon/lint/html-lint.js @@ -0,0 +1,53 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// Depends on htmlhint.js from http://htmlhint.com/js/htmlhint.js + +// declare global: HTMLHint + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror"), require("htmlhint")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror", "htmlhint"], mod); + else // Plain browser env + mod(CodeMirror, window.HTMLHint); +})(function(CodeMirror, HTMLHint) { + "use strict"; + + var defaultRules = { + "tagname-lowercase": true, + "attr-lowercase": true, + "attr-value-double-quotes": true, + "doctype-first": false, + "tag-pair": true, + "spec-char-escape": true, + "id-unique": true, + "src-not-empty": true, + "attr-no-duplication": true + }; + + CodeMirror.registerHelper("lint", "html", function(text, options) { + var found = []; + if (HTMLHint && !HTMLHint.verify) HTMLHint = HTMLHint.HTMLHint; + if (!HTMLHint) HTMLHint = window.HTMLHint; + if (!HTMLHint) { + if (window.console) { + window.console.error("Error: HTMLHint not found, not defined on window, or not available through define/require, CodeMirror HTML linting cannot run."); + } + return found; + } + var messages = HTMLHint.verify(text, options && options.rules || defaultRules); + for (var i = 0; i < messages.length; i++) { + var message = messages[i]; + var startLine = message.line - 1, endLine = message.line - 1, startCol = message.col - 1, endCol = message.col; + found.push({ + from: CodeMirror.Pos(startLine, startCol), + to: CodeMirror.Pos(endLine, endCol), + message: message.message, + severity : message.type + }); + } + return found; + }); +}); diff --git a/modules/editor/codemirror/addon/lint/javascript-lint.min.js b/modules/editor/codemirror/addon/lint/javascript-lint.min.js @@ -0,0 +1,141 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + // declare global: JSHINT + + var bogus = [ "Dangerous comment" ]; + + var warnings = [ [ "Expected '{'", + "Statement body should be inside '{ }' braces." ] ]; + + var errors = [ "Missing semicolon", "Extra comma", "Missing property name", + "Unmatched ", " and instead saw", " is not defined", + "Unclosed string", "Stopping, unable to continue" ]; + + function validator(text, options) { + if (!window.JSHINT) { + if (window.console) { + window.console.error("Error: window.JSHINT not defined, CodeMirror JavaScript linting cannot run."); + } + return []; + } + JSHINT(text, options, options.globals); + var errors = JSHINT.data().errors, result = []; + if (errors) parseErrors(errors, result); + return result; + } + + CodeMirror.registerHelper("lint", "javascript", validator); + + function cleanup(error) { + // All problems are warnings by default + fixWith(error, warnings, "warning", true); + fixWith(error, errors, "error"); + + return isBogus(error) ? null : error; + } + + function fixWith(error, fixes, severity, force) { + var description, fix, find, replace, found; + + description = error.description; + + for ( var i = 0; i < fixes.length; i++) { + fix = fixes[i]; + find = (typeof fix === "string" ? fix : fix[0]); + replace = (typeof fix === "string" ? null : fix[1]); + found = description.indexOf(find) !== -1; + + if (force || found) { + error.severity = severity; + } + if (found && replace) { + error.description = replace; + } + } + } + + function isBogus(error) { + var description = error.description; + for ( var i = 0; i < bogus.length; i++) { + if (description.indexOf(bogus[i]) !== -1) { + return true; + } + } + return false; + } + + function parseErrors(errors, output) { + for ( var i = 0; i < errors.length; i++) { + var error = errors[i]; + if (error) { + var linetabpositions, index; + + linetabpositions = []; + + // This next block is to fix a problem in jshint. Jshint + // replaces + // all tabs with spaces then performs some checks. The error + // positions (character/space) are then reported incorrectly, + // not taking the replacement step into account. Here we look + // at the evidence line and try to adjust the character position + // to the correct value. + if (error.evidence) { + // Tab positions are computed once per line and cached + var tabpositions = linetabpositions[error.line]; + if (!tabpositions) { + var evidence = error.evidence; + tabpositions = []; + // ugggh phantomjs does not like this + // forEachChar(evidence, function(item, index) { + Array.prototype.forEach.call(evidence, function(item, + index) { + if (item === '\t') { + // First col is 1 (not 0) to match error + // positions + tabpositions.push(index + 1); + } + }); + linetabpositions[error.line] = tabpositions; + } + if (tabpositions.length > 0) { + var pos = error.character; + tabpositions.forEach(function(tabposition) { + if (pos > tabposition) pos -= 1; + }); + error.character = pos; + } + } + + var start = error.character - 1, end = start + 1; + if (error.evidence) { + index = error.evidence.substring(start).search(/.\b/); + if (index > -1) { + end += index; + } + } + + // Convert to format expected by validation service + error.description = error.reason;// + "(jshint)"; + error.start = error.character; + error.end = end; + error = cleanup(error); + + if (error) + output.push({message: error.description, + severity: error.severity, + from: CodeMirror.Pos(error.line - 1, start), + to: CodeMirror.Pos(error.line - 1, end)}); + } + } + } +}); diff --git a/modules/editor/codemirror/addon/lint/json-lint.js b/modules/editor/codemirror/addon/lint/json-lint.js @@ -0,0 +1,37 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// Depends on jsonlint.js from https://github.com/zaach/jsonlint + +// declare global: jsonlint + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.registerHelper("lint", "json", function(text) { + var found = []; + if (!window.jsonlint) { + if (window.console) { + window.console.error("Error: window.jsonlint not defined, CodeMirror JSON linting cannot run."); + } + return found; + } + jsonlint.parseError = function(str, hash) { + var loc = hash.loc; + found.push({from: CodeMirror.Pos(loc.first_line - 1, loc.first_column), + to: CodeMirror.Pos(loc.last_line - 1, loc.last_column), + message: str}); + }; + try { jsonlint.parse(text); } + catch(e) {} + return found; +}); + +}); diff --git a/modules/editor/codemirror/addon/mode/overlay.js b/modules/editor/codemirror/addon/mode/overlay.js @@ -0,0 +1,90 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// Utility function that allows modes to be combined. The mode given +// as the base argument takes care of most of the normal mode +// functionality, but a second (typically simple) mode is used, which +// can override the style of text. Both modes get to parse all of the +// text, but when both assign a non-null style to a piece of code, the +// overlay wins, unless the combine argument was true and not overridden, +// or state.overlay.combineTokens was true, in which case the styles are +// combined. + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.overlayMode = function(base, overlay, combine) { + return { + startState: function() { + return { + base: CodeMirror.startState(base), + overlay: CodeMirror.startState(overlay), + basePos: 0, baseCur: null, + overlayPos: 0, overlayCur: null, + streamSeen: null + }; + }, + copyState: function(state) { + return { + base: CodeMirror.copyState(base, state.base), + overlay: CodeMirror.copyState(overlay, state.overlay), + basePos: state.basePos, baseCur: null, + overlayPos: state.overlayPos, overlayCur: null + }; + }, + + token: function(stream, state) { + if (stream != state.streamSeen || + Math.min(state.basePos, state.overlayPos) < stream.start) { + state.streamSeen = stream; + state.basePos = state.overlayPos = stream.start; + } + + if (stream.start == state.basePos) { + state.baseCur = base.token(stream, state.base); + state.basePos = stream.pos; + } + if (stream.start == state.overlayPos) { + stream.pos = stream.start; + state.overlayCur = overlay.token(stream, state.overlay); + state.overlayPos = stream.pos; + } + stream.pos = Math.min(state.basePos, state.overlayPos); + + // state.overlay.combineTokens always takes precedence over combine, + // unless set to null + if (state.overlayCur == null) return state.baseCur; + else if (state.baseCur != null && + state.overlay.combineTokens || + combine && state.overlay.combineTokens == null) + return state.baseCur + " " + state.overlayCur; + else return state.overlayCur; + }, + + indent: base.indent && function(state, textAfter) { + return base.indent(state.base, textAfter); + }, + electricChars: base.electricChars, + + innerMode: function(state) { return {state: state.base, mode: base}; }, + + blankLine: function(state) { + var baseToken, overlayToken; + if (base.blankLine) baseToken = base.blankLine(state.base); + if (overlay.blankLine) overlayToken = overlay.blankLine(state.overlay); + + return overlayToken == null ? + baseToken : + (combine && baseToken != null ? baseToken + " " + overlayToken : overlayToken); + } + }; +}; + +}); diff --git a/modules/editor/codemirror/addon/runmode/colorize.js b/modules/editor/codemirror/addon/runmode/colorize.js @@ -0,0 +1,40 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror"), require("./runmode")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror", "./runmode"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + var isBlock = /^(p|li|div|h\\d|pre|blockquote|td)$/; + + function textContent(node, out) { + if (node.nodeType == 3) return out.push(node.nodeValue); + for (var ch = node.firstChild; ch; ch = ch.nextSibling) { + textContent(ch, out); + if (isBlock.test(node.nodeType)) out.push("\n"); + } + } + + CodeMirror.colorize = function(collection, defaultMode) { + if (!collection) collection = document.body.getElementsByTagName("pre"); + + for (var i = 0; i < collection.length; ++i) { + var node = collection[i]; + var mode = node.getAttribute("data-lang") || defaultMode; + if (!mode) continue; + + var text = []; + textContent(node, text); + node.innerHTML = ""; + CodeMirror.runMode(text.join(""), mode, node); + + node.className += " cm-s-default"; + } + }; +}); diff --git a/modules/editor/codemirror/addon/runmode/runmode-standalone.min.js b/modules/editor/codemirror/addon/runmode/runmode-standalone.min.js @@ -0,0 +1,158 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +window.CodeMirror = {}; + +(function() { +"use strict"; + +function splitLines(string){ return string.split(/\r?\n|\r/); }; + +function StringStream(string) { + this.pos = this.start = 0; + this.string = string; + this.lineStart = 0; +} +StringStream.prototype = { + eol: function() {return this.pos >= this.string.length;}, + sol: function() {return this.pos == 0;}, + peek: function() {return this.string.charAt(this.pos) || null;}, + next: function() { + if (this.pos < this.string.length) + return this.string.charAt(this.pos++); + }, + eat: function(match) { + var ch = this.string.charAt(this.pos); + if (typeof match == "string") var ok = ch == match; + else var ok = ch && (match.test ? match.test(ch) : match(ch)); + if (ok) {++this.pos; return ch;} + }, + eatWhile: function(match) { + var start = this.pos; + while (this.eat(match)){} + return this.pos > start; + }, + eatSpace: function() { + var start = this.pos; + while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; + return this.pos > start; + }, + skipToEnd: function() {this.pos = this.string.length;}, + skipTo: function(ch) { + var found = this.string.indexOf(ch, this.pos); + if (found > -1) {this.pos = found; return true;} + }, + backUp: function(n) {this.pos -= n;}, + column: function() {return this.start - this.lineStart;}, + indentation: function() {return 0;}, + match: function(pattern, consume, caseInsensitive) { + if (typeof pattern == "string") { + var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;}; + var substr = this.string.substr(this.pos, pattern.length); + if (cased(substr) == cased(pattern)) { + if (consume !== false) this.pos += pattern.length; + return true; + } + } else { + var match = this.string.slice(this.pos).match(pattern); + if (match && match.index > 0) return null; + if (match && consume !== false) this.pos += match[0].length; + return match; + } + }, + current: function(){return this.string.slice(this.start, this.pos);}, + hideFirstChars: function(n, inner) { + this.lineStart += n; + try { return inner(); } + finally { this.lineStart -= n; } + }, + lookAhead: function() { return null } +}; +CodeMirror.StringStream = StringStream; + +CodeMirror.startState = function (mode, a1, a2) { + return mode.startState ? mode.startState(a1, a2) : true; +}; + +var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {}; +CodeMirror.defineMode = function (name, mode) { + if (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 (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { + spec = mimeModes[spec]; + } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { + spec = mimeModes[spec.name]; + } + if (typeof spec == "string") return {name: spec}; + else return spec || {name: "null"}; +}; +CodeMirror.getMode = function (options, spec) { + spec = CodeMirror.resolveMode(spec); + var mfactory = modes[spec.name]; + if (!mfactory) throw new Error("Unknown mode: " + spec); + return mfactory(options, spec); +}; +CodeMirror.registerHelper = CodeMirror.registerGlobalHelper = Math.min; +CodeMirror.defineMode("null", function() { + return {token: function(stream) {stream.skipToEnd();}}; +}); +CodeMirror.defineMIME("text/plain", "null"); + +CodeMirror.runMode = function (string, modespec, callback, options) { + var mode = CodeMirror.getMode({ indentUnit: 2 }, modespec); + + if (callback.nodeType == 1) { + var tabSize = (options && options.tabSize) || 4; + var node = callback, col = 0; + node.innerHTML = ""; + callback = function (text, style) { + if (text == "\n") { + node.appendChild(document.createElement("br")); + col = 0; + return; + } + var content = ""; + // replace tabs + for (var pos = 0; ;) { + var idx = text.indexOf("\t", pos); + if (idx == -1) { + content += text.slice(pos); + col += text.length - pos; + break; + } else { + col += idx - pos; + content += text.slice(pos, idx); + var size = tabSize - col % tabSize; + col += size; + for (var i = 0; i < size; ++i) content += " "; + pos = idx + 1; + } + } + + if (style) { + var sp = node.appendChild(document.createElement("span")); + sp.className = "cm-" + style.replace(/ +/g, " cm-"); + sp.appendChild(document.createTextNode(content)); + } else { + node.appendChild(document.createTextNode(content)); + } + }; + } + + var lines = splitLines(string), state = (options && options.state) || CodeMirror.startState(mode); + for (var i = 0, e = lines.length; i < e; ++i) { + if (i) callback("\n"); + var stream = new CodeMirror.StringStream(lines[i]); + if (!stream.string && mode.blankLine) mode.blankLine(state); + while (!stream.eol()) { + var style = mode.token(stream, state); + callback(stream.current(), style, i, stream.start, state); + stream.start = stream.pos; + } + } +}; +})(); diff --git a/modules/editor/codemirror/addon/scroll/annotatescrollbar.min.js b/modules/editor/codemirror/addon/scroll/annotatescrollbar.min.js @@ -0,0 +1,122 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + CodeMirror.defineExtension("annotateScrollbar", function(options) { + if (typeof options == "string") options = {className: options}; + return new Annotation(this, options); + }); + + CodeMirror.defineOption("scrollButtonHeight", 0); + + function Annotation(cm, options) { + this.cm = cm; + this.options = options; + this.buttonHeight = options.scrollButtonHeight || cm.getOption("scrollButtonHeight"); + this.annotations = []; + this.doRedraw = this.doUpdate = null; + this.div = cm.getWrapperElement().appendChild(document.createElement("div")); + this.div.style.cssText = "position: absolute; right: 0; top: 0; z-index: 7; pointer-events: none"; + this.computeScale(); + + function scheduleRedraw(delay) { + clearTimeout(self.doRedraw); + self.doRedraw = setTimeout(function() { self.redraw(); }, delay); + } + + var self = this; + cm.on("refresh", this.resizeHandler = function() { + clearTimeout(self.doUpdate); + self.doUpdate = setTimeout(function() { + if (self.computeScale()) scheduleRedraw(20); + }, 100); + }); + cm.on("markerAdded", this.resizeHandler); + cm.on("markerCleared", this.resizeHandler); + if (options.listenForChanges !== false) + cm.on("change", this.changeHandler = function() { + scheduleRedraw(250); + }); + } + + Annotation.prototype.computeScale = function() { + var cm = this.cm; + var hScale = (cm.getWrapperElement().clientHeight - cm.display.barHeight - this.buttonHeight * 2) / + cm.getScrollerElement().scrollHeight + if (hScale != this.hScale) { + this.hScale = hScale; + return true; + } + }; + + Annotation.prototype.update = function(annotations) { + this.annotations = annotations; + this.redraw(); + }; + + Annotation.prototype.redraw = function(compute) { + if (compute !== false) this.computeScale(); + var cm = this.cm, hScale = this.hScale; + + var frag = document.createDocumentFragment(), anns = this.annotations; + + var wrapping = cm.getOption("lineWrapping"); + var singleLineH = wrapping && cm.defaultTextHeight() * 1.5; + var curLine = null, curLineObj = null; + function getY(pos, top) { + if (curLine != pos.line) { + curLine = pos.line; + curLineObj = cm.getLineHandle(curLine); + } + if ((curLineObj.widgets && curLineObj.widgets.length) || + (wrapping && curLineObj.height > singleLineH)) + return cm.charCoords(pos, "local")[top ? "top" : "bottom"]; + var topY = cm.heightAtLine(curLineObj, "local"); + return topY + (top ? 0 : curLineObj.height); + } + + var lastLine = cm.lastLine() + if (cm.display.barWidth) for (var i = 0, nextTop; i < anns.length; i++) { + var ann = anns[i]; + if (ann.to.line > lastLine) continue; + var top = nextTop || getY(ann.from, true) * hScale; + var bottom = getY(ann.to, false) * hScale; + while (i < anns.length - 1) { + if (anns[i + 1].to.line > lastLine) break; + nextTop = getY(anns[i + 1].from, true) * hScale; + if (nextTop > bottom + .9) break; + ann = anns[++i]; + bottom = getY(ann.to, false) * hScale; + } + if (bottom == top) continue; + var height = Math.max(bottom - top, 3); + + var elt = frag.appendChild(document.createElement("div")); + elt.style.cssText = "position: absolute; right: 0px; width: " + Math.max(cm.display.barWidth - 1, 2) + "px; top: " + + (top + this.buttonHeight) + "px; height: " + height + "px"; + elt.className = this.options.className; + if (ann.id) { + elt.setAttribute("annotation-id", ann.id); + } + } + this.div.textContent = ""; + this.div.appendChild(frag); + }; + + Annotation.prototype.clear = function() { + this.cm.off("refresh", this.resizeHandler); + this.cm.off("markerAdded", this.resizeHandler); + this.cm.off("markerCleared", this.resizeHandler); + if (this.changeHandler) this.cm.off("change", this.changeHandler); + this.div.parentNode.removeChild(this.div); + }; +}); diff --git a/modules/editor/codemirror/addon/scroll/simplescrollbars.js b/modules/editor/codemirror/addon/scroll/simplescrollbars.js @@ -0,0 +1,152 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + function Bar(cls, orientation, scroll) { + this.orientation = orientation; + this.scroll = scroll; + this.screen = this.total = this.size = 1; + this.pos = 0; + + this.node = document.createElement("div"); + this.node.className = cls + "-" + orientation; + this.inner = this.node.appendChild(document.createElement("div")); + + var self = this; + CodeMirror.on(this.inner, "mousedown", function(e) { + if (e.which != 1) return; + CodeMirror.e_preventDefault(e); + var axis = self.orientation == "horizontal" ? "pageX" : "pageY"; + var start = e[axis], startpos = self.pos; + function done() { + CodeMirror.off(document, "mousemove", move); + CodeMirror.off(document, "mouseup", done); + } + function move(e) { + if (e.which != 1) return done(); + self.moveTo(startpos + (e[axis] - start) * (self.total / self.size)); + } + CodeMirror.on(document, "mousemove", move); + CodeMirror.on(document, "mouseup", done); + }); + + CodeMirror.on(this.node, "click", function(e) { + CodeMirror.e_preventDefault(e); + var innerBox = self.inner.getBoundingClientRect(), where; + if (self.orientation == "horizontal") + where = e.clientX < innerBox.left ? -1 : e.clientX > innerBox.right ? 1 : 0; + else + where = e.clientY < innerBox.top ? -1 : e.clientY > innerBox.bottom ? 1 : 0; + self.moveTo(self.pos + where * self.screen); + }); + + function onWheel(e) { + var moved = CodeMirror.wheelEventPixels(e)[self.orientation == "horizontal" ? "x" : "y"]; + var oldPos = self.pos; + self.moveTo(self.pos + moved); + if (self.pos != oldPos) CodeMirror.e_preventDefault(e); + } + CodeMirror.on(this.node, "mousewheel", onWheel); + CodeMirror.on(this.node, "DOMMouseScroll", onWheel); + } + + Bar.prototype.setPos = function(pos, force) { + if (pos < 0) pos = 0; + if (pos > this.total - this.screen) pos = this.total - this.screen; + if (!force && pos == this.pos) return false; + this.pos = pos; + this.inner.style[this.orientation == "horizontal" ? "left" : "top"] = + (pos * (this.size / this.total)) + "px"; + return true + }; + + Bar.prototype.moveTo = function(pos) { + if (this.setPos(pos)) this.scroll(pos, this.orientation); + } + + var minButtonSize = 10; + + Bar.prototype.update = function(scrollSize, clientSize, barSize) { + var sizeChanged = this.screen != clientSize || this.total != scrollSize || this.size != barSize + if (sizeChanged) { + this.screen = clientSize; + this.total = scrollSize; + this.size = barSize; + } + + var buttonSize = this.screen * (this.size / this.total); + if (buttonSize < minButtonSize) { + this.size -= minButtonSize - buttonSize; + buttonSize = minButtonSize; + } + this.inner.style[this.orientation == "horizontal" ? "width" : "height"] = + buttonSize + "px"; + this.setPos(this.pos, sizeChanged); + }; + + function SimpleScrollbars(cls, place, scroll) { + this.addClass = cls; + this.horiz = new Bar(cls, "horizontal", scroll); + place(this.horiz.node); + this.vert = new Bar(cls, "vertical", scroll); + place(this.vert.node); + this.width = null; + } + + SimpleScrollbars.prototype.update = function(measure) { + if (this.width == null) { + var style = window.getComputedStyle ? window.getComputedStyle(this.horiz.node) : this.horiz.node.currentStyle; + if (style) this.width = parseInt(style.height); + } + var width = this.width || 0; + + var needsH = measure.scrollWidth > measure.clientWidth + 1; + var needsV = measure.scrollHeight > measure.clientHeight + 1; + this.vert.node.style.display = needsV ? "block" : "none"; + this.horiz.node.style.display = needsH ? "block" : "none"; + + if (needsV) { + this.vert.update(measure.scrollHeight, measure.clientHeight, + measure.viewHeight - (needsH ? width : 0)); + this.vert.node.style.bottom = needsH ? width + "px" : "0"; + } + if (needsH) { + this.horiz.update(measure.scrollWidth, measure.clientWidth, + measure.viewWidth - (needsV ? width : 0) - measure.barLeft); + this.horiz.node.style.right = needsV ? width + "px" : "0"; + this.horiz.node.style.left = measure.barLeft + "px"; + } + + return {right: needsV ? width : 0, bottom: needsH ? width : 0}; + }; + + SimpleScrollbars.prototype.setScrollTop = function(pos) { + this.vert.setPos(pos); + }; + + SimpleScrollbars.prototype.setScrollLeft = function(pos) { + this.horiz.setPos(pos); + }; + + SimpleScrollbars.prototype.clear = function() { + var parent = this.horiz.node.parentNode; + parent.removeChild(this.horiz.node); + parent.removeChild(this.vert.node); + }; + + CodeMirror.scrollbarModel.simple = function(place, scroll) { + return new SimpleScrollbars("CodeMirror-simplescroll", place, scroll); + }; + CodeMirror.scrollbarModel.overlay = function(place, scroll) { + return new SimpleScrollbars("CodeMirror-overlayscroll", place, scroll); + }; +}); diff --git a/modules/editor/codemirror/addon/search/jump-to-line.min.js b/modules/editor/codemirror/addon/search/jump-to-line.min.js @@ -0,0 +1,49 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// Defines jumpToLine command. Uses dialog.js if present. + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror"), require("../dialog/dialog")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror", "../dialog/dialog"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + function dialog(cm, text, shortText, deflt, f) { + if (cm.openDialog) cm.openDialog(text, f, {value: deflt, selectValueOnOpen: true}); + else f(prompt(shortText, deflt)); + } + + var jumpDialog = + 'Jump to line: <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">(Use line:column or scroll% syntax)</span>'; + + function interpretLine(cm, string) { + var num = Number(string) + if (/^[-+]/.test(string)) return cm.getCursor().line + num + else return num - 1 + } + + CodeMirror.commands.jumpToLine = function(cm) { + var cur = cm.getCursor(); + dialog(cm, jumpDialog, "Jump to line:", (cur.line + 1) + ":" + cur.ch, function(posStr) { + if (!posStr) return; + + var match; + if (match = /^\s*([\+\-]?\d+)\s*\:\s*(\d+)\s*$/.exec(posStr)) { + cm.setCursor(interpretLine(cm, match[1]), Number(match[2])) + } else if (match = /^\s*([\+\-]?\d+(\.\d+)?)\%\s*/.exec(posStr)) { + var line = Math.round(cm.lineCount() * Number(match[1]) / 100); + if (/^[-+]/.test(match[1])) line = cur.line + line + 1; + cm.setCursor(line - 1, cur.ch); + } else if (match = /^\s*\:?\s*([\+\-]?\d+)\s*/.exec(posStr)) { + cm.setCursor(interpretLine(cm, match[1]), cur.ch); + } + }); + }; + + CodeMirror.keyMap["default"]["Alt-G"] = "jumpToLine"; +}); diff --git a/modules/editor/codemirror/addon/search/match-highlighter.js b/modules/editor/codemirror/addon/search/match-highlighter.js @@ -0,0 +1,165 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// Highlighting text that matches the selection +// +// Defines an option highlightSelectionMatches, which, when enabled, +// will style strings that match the selection throughout the +// document. +// +// The option can be set to true to simply enable it, or to a +// {minChars, style, wordsOnly, showToken, delay} object to explicitly +// configure it. minChars is the minimum amount of characters that should be +// selected for the behavior to occur, and style is the token style to +// apply to the matches. This will be prefixed by "cm-" to create an +// actual CSS class name. If wordsOnly is enabled, the matches will be +// highlighted only if the selected text is a word. showToken, when enabled, +// will cause the current token to be highlighted when nothing is selected. +// delay is used to specify how much time to wait, in milliseconds, before +// highlighting the matches. If annotateScrollbar is enabled, the occurences +// will be highlighted on the scrollbar via the matchesonscrollbar addon. + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror"), require("./matchesonscrollbar")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror", "./matchesonscrollbar"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + var defaults = { + style: "matchhighlight", + minChars: 2, + delay: 100, + wordsOnly: false, + annotateScrollbar: false, + showToken: false, + trim: true + } + + function State(options) { + this.options = {} + for (var name in defaults) + this.options[name] = (options && options.hasOwnProperty(name) ? options : defaults)[name] + this.overlay = this.timeout = null; + this.matchesonscroll = null; + this.active = false; + } + + CodeMirror.defineOption("highlightSelectionMatches", false, function(cm, val, old) { + if (old && old != CodeMirror.Init) { + removeOverlay(cm); + clearTimeout(cm.state.matchHighlighter.timeout); + cm.state.matchHighlighter = null; + cm.off("cursorActivity", cursorActivity); + cm.off("focus", onFocus) + } + if (val) { + var state = cm.state.matchHighlighter = new State(val); + if (cm.hasFocus()) { + state.active = true + highlightMatches(cm) + } else { + cm.on("focus", onFocus) + } + cm.on("cursorActivity", cursorActivity); + } + }); + + function cursorActivity(cm) { + var state = cm.state.matchHighlighter; + if (state.active || cm.hasFocus()) scheduleHighlight(cm, state) + } + + function onFocus(cm) { + var state = cm.state.matchHighlighter + if (!state.active) { + state.active = true + scheduleHighlight(cm, state) + } + } + + function scheduleHighlight(cm, state) { + clearTimeout(state.timeout); + state.timeout = setTimeout(function() {highlightMatches(cm);}, state.options.delay); + } + + function addOverlay(cm, query, hasBoundary, style) { + var state = cm.state.matchHighlighter; + cm.addOverlay(state.overlay = makeOverlay(query, hasBoundary, style)); + if (state.options.annotateScrollbar && cm.showMatchesOnScrollbar) { + var searchFor = hasBoundary ? new RegExp("\\b" + query + "\\b") : query; + state.matchesonscroll = cm.showMatchesOnScrollbar(searchFor, false, + {className: "CodeMirror-selection-highlight-scrollbar"}); + } + } + + function removeOverlay(cm) { + var state = cm.state.matchHighlighter; + if (state.overlay) { + cm.removeOverlay(state.overlay); + state.overlay = null; + if (state.matchesonscroll) { + state.matchesonscroll.clear(); + state.matchesonscroll = null; + } + } + } + + function highlightMatches(cm) { + cm.operation(function() { + var state = cm.state.matchHighlighter; + removeOverlay(cm); + if (!cm.somethingSelected() && state.options.showToken) { + var re = state.options.showToken === true ? /[\w$]/ : state.options.showToken; + var cur = cm.getCursor(), line = cm.getLine(cur.line), start = cur.ch, end = start; + while (start && re.test(line.charAt(start - 1))) --start; + while (end < line.length && re.test(line.charAt(end))) ++end; + if (start < end) + addOverlay(cm, line.slice(start, end), re, state.options.style); + return; + } + var from = cm.getCursor("from"), to = cm.getCursor("to"); + if (from.line != to.line) return; + if (state.options.wordsOnly && !isWord(cm, from, to)) return; + var selection = cm.getRange(from, to) + if (state.options.trim) selection = selection.replace(/^\s+|\s+$/g, "") + if (selection.length >= state.options.minChars) + addOverlay(cm, selection, false, state.options.style); + }); + } + + function isWord(cm, from, to) { + var str = cm.getRange(from, to); + if (str.match(/^\w+$/) !== null) { + if (from.ch > 0) { + var pos = {line: from.line, ch: from.ch - 1}; + var chr = cm.getRange(pos, from); + if (chr.match(/\W/) === null) return false; + } + if (to.ch < cm.getLine(from.line).length) { + var pos = {line: to.line, ch: to.ch + 1}; + var chr = cm.getRange(to, pos); + if (chr.match(/\W/) === null) return false; + } + return true; + } else return false; + } + + function boundariesAround(stream, re) { + return (!stream.start || !re.test(stream.string.charAt(stream.start - 1))) && + (stream.pos == stream.string.length || !re.test(stream.string.charAt(stream.pos))); + } + + function makeOverlay(query, hasBoundary, style) { + return {token: function(stream) { + if (stream.match(query) && + (!hasBoundary || boundariesAround(stream, hasBoundary))) + return style; + stream.next(); + stream.skipTo(query.charAt(0)) || stream.skipToEnd(); + }}; + } +}); diff --git a/modules/editor/codemirror/addon/search/searchcursor.min.js b/modules/editor/codemirror/addon/search/searchcursor.min.js @@ -0,0 +1,289 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")) + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod) + else // Plain browser env + mod(CodeMirror) +})(function(CodeMirror) { + "use strict" + var Pos = CodeMirror.Pos + + function regexpFlags(regexp) { + var flags = regexp.flags + return flags != null ? flags : (regexp.ignoreCase ? "i" : "") + + (regexp.global ? "g" : "") + + (regexp.multiline ? "m" : "") + } + + function ensureGlobal(regexp) { + return regexp.global ? regexp : new RegExp(regexp.source, regexpFlags(regexp) + "g") + } + + function maybeMultiline(regexp) { + return /\\s|\\n|\n|\\W|\\D|\[\^/.test(regexp.source) + } + + function searchRegexpForward(doc, regexp, start) { + regexp = ensureGlobal(regexp) + for (var line = start.line, ch = start.ch, last = doc.lastLine(); line <= last; line++, ch = 0) { + regexp.lastIndex = ch + var string = doc.getLine(line), match = regexp.exec(string) + if (match) + return {from: Pos(line, match.index), + to: Pos(line, match.index + match[0].length), + match: match} + } + } + + function searchRegexpForwardMultiline(doc, regexp, start) { + if (!maybeMultiline(regexp)) return searchRegexpForward(doc, regexp, start) + + regexp = ensureGlobal(regexp) + var string, chunk = 1 + for (var line = start.line, last = doc.lastLine(); line <= last;) { + // This grows the search buffer in exponentially-sized chunks + // between matches, so that nearby matches are fast and don't + // require concatenating the whole document (in case we're + // searching for something that has tons of matches), but at the + // same time, the amount of retries is limited. + for (var i = 0; i < chunk; i++) { + var curLine = doc.getLine(line++) + string = string == null ? curLine : string + "\n" + curLine + } + chunk = chunk * 2 + regexp.lastIndex = start.ch + var match = regexp.exec(string) + if (match) { + var before = string.slice(0, match.index).split("\n"), inside = match[0].split("\n") + var startLine = start.line + before.length - 1, startCh = before[before.length - 1].length + return {from: Pos(startLine, startCh), + to: Pos(startLine + inside.length - 1, + inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length), + match: match} + } + } + } + + function lastMatchIn(string, regexp) { + var cutOff = 0, match + for (;;) { + regexp.lastIndex = cutOff + var newMatch = regexp.exec(string) + if (!newMatch) return match + match = newMatch + cutOff = match.index + (match[0].length || 1) + if (cutOff == string.length) return match + } + } + + function searchRegexpBackward(doc, regexp, start) { + regexp = ensureGlobal(regexp) + for (var line = start.line, ch = start.ch, first = doc.firstLine(); line >= first; line--, ch = -1) { + var string = doc.getLine(line) + if (ch > -1) string = string.slice(0, ch) + var match = lastMatchIn(string, regexp) + if (match) + return {from: Pos(line, match.index), + to: Pos(line, match.index + match[0].length), + match: match} + } + } + + function searchRegexpBackwardMultiline(doc, regexp, start) { + regexp = ensureGlobal(regexp) + var string, chunk = 1 + for (var line = start.line, first = doc.firstLine(); line >= first;) { + for (var i = 0; i < chunk; i++) { + var curLine = doc.getLine(line--) + string = string == null ? curLine.slice(0, start.ch) : curLine + "\n" + string + } + chunk *= 2 + + var match = lastMatchIn(string, regexp) + if (match) { + var before = string.slice(0, match.index).split("\n"), inside = match[0].split("\n") + var startLine = line + before.length, startCh = before[before.length - 1].length + return {from: Pos(startLine, startCh), + to: Pos(startLine + inside.length - 1, + inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length), + match: match} + } + } + } + + var doFold, noFold + if (String.prototype.normalize) { + doFold = function(str) { return str.normalize("NFD").toLowerCase() } + noFold = function(str) { return str.normalize("NFD") } + } else { + doFold = function(str) { return str.toLowerCase() } + noFold = function(str) { return str } + } + + // Maps a position in a case-folded line back to a position in the original line + // (compensating for codepoints increasing in number during folding) + function adjustPos(orig, folded, pos, foldFunc) { + if (orig.length == folded.length) return pos + for (var min = 0, max = pos + Math.max(0, orig.length - folded.length);;) { + if (min == max) return min + var mid = (min + max) >> 1 + var len = foldFunc(orig.slice(0, mid)).length + if (len == pos) return mid + else if (len > pos) max = mid + else min = mid + 1 + } + } + + function searchStringForward(doc, query, start, caseFold) { + // Empty string would match anything and never progress, so we + // define it to match nothing instead. + if (!query.length) return null + var fold = caseFold ? doFold : noFold + var lines = fold(query).split(/\r|\n\r?/) + + search: for (var line = start.line, ch = start.ch, last = doc.lastLine() + 1 - lines.length; line <= last; line++, ch = 0) { + var orig = doc.getLine(line).slice(ch), string = fold(orig) + if (lines.length == 1) { + var found = string.indexOf(lines[0]) + if (found == -1) continue search + var start = adjustPos(orig, string, found, fold) + ch + return {from: Pos(line, adjustPos(orig, string, found, fold) + ch), + to: Pos(line, adjustPos(orig, string, found + lines[0].length, fold) + ch)} + } else { + var cutFrom = string.length - lines[0].length + if (string.slice(cutFrom) != lines[0]) continue search + for (var i = 1; i < lines.length - 1; i++) + if (fold(doc.getLine(line + i)) != lines[i]) continue search + var end = doc.getLine(line + lines.length - 1), endString = fold(end), lastLine = lines[lines.length - 1] + if (endString.slice(0, lastLine.length) != lastLine) continue search + return {from: Pos(line, adjustPos(orig, string, cutFrom, fold) + ch), + to: Pos(line + lines.length - 1, adjustPos(end, endString, lastLine.length, fold))} + } + } + } + + function searchStringBackward(doc, query, start, caseFold) { + if (!query.length) return null + var fold = caseFold ? doFold : noFold + var lines = fold(query).split(/\r|\n\r?/) + + search: for (var line = start.line, ch = start.ch, first = doc.firstLine() - 1 + lines.length; line >= first; line--, ch = -1) { + var orig = doc.getLine(line) + if (ch > -1) orig = orig.slice(0, ch) + var string = fold(orig) + if (lines.length == 1) { + var found = string.lastIndexOf(lines[0]) + if (found == -1) continue search + return {from: Pos(line, adjustPos(orig, string, found, fold)), + to: Pos(line, adjustPos(orig, string, found + lines[0].length, fold))} + } else { + var lastLine = lines[lines.length - 1] + if (string.slice(0, lastLine.length) != lastLine) continue search + for (var i = 1, start = line - lines.length + 1; i < lines.length - 1; i++) + if (fold(doc.getLine(start + i)) != lines[i]) continue search + var top = doc.getLine(line + 1 - lines.length), topString = fold(top) + if (topString.slice(topString.length - lines[0].length) != lines[0]) continue search + return {from: Pos(line + 1 - lines.length, adjustPos(top, topString, top.length - lines[0].length, fold)), + to: Pos(line, adjustPos(orig, string, lastLine.length, fold))} + } + } + } + + function SearchCursor(doc, query, pos, options) { + this.atOccurrence = false + this.doc = doc + pos = pos ? doc.clipPos(pos) : Pos(0, 0) + this.pos = {from: pos, to: pos} + + var caseFold + if (typeof options == "object") { + caseFold = options.caseFold + } else { // Backwards compat for when caseFold was the 4th argument + caseFold = options + options = null + } + + if (typeof query == "string") { + if (caseFold == null) caseFold = false + this.matches = function(reverse, pos) { + return (reverse ? searchStringBackward : searchStringForward)(doc, query, pos, caseFold) + } + } else { + query = ensureGlobal(query) + if (!options || options.multiline !== false) + this.matches = function(reverse, pos) { + return (reverse ? searchRegexpBackwardMultiline : searchRegexpForwardMultiline)(doc, query, pos) + } + else + this.matches = function(reverse, pos) { + return (reverse ? searchRegexpBackward : searchRegexpForward)(doc, query, pos) + } + } + } + + SearchCursor.prototype = { + findNext: function() {return this.find(false)}, + findPrevious: function() {return this.find(true)}, + + find: function(reverse) { + var result = this.matches(reverse, this.doc.clipPos(reverse ? this.pos.from : this.pos.to)) + + // Implements weird auto-growing behavior on null-matches for + // backwards-compatiblity with the vim code (unfortunately) + while (result && CodeMirror.cmpPos(result.from, result.to) == 0) { + if (reverse) { + if (result.from.ch) result.from = Pos(result.from.line, result.from.ch - 1) + else if (result.from.line == this.doc.firstLine()) result = null + else result = this.matches(reverse, this.doc.clipPos(Pos(result.from.line - 1))) + } else { + if (result.to.ch < this.doc.getLine(result.to.line).length) result.to = Pos(result.to.line, result.to.ch + 1) + else if (result.to.line == this.doc.lastLine()) result = null + else result = this.matches(reverse, Pos(result.to.line + 1, 0)) + } + } + + if (result) { + this.pos = result + this.atOccurrence = true + return this.pos.match || true + } else { + var end = Pos(reverse ? this.doc.firstLine() : this.doc.lastLine() + 1, 0) + this.pos = {from: end, to: end} + return this.atOccurrence = false + } + }, + + from: function() {if (this.atOccurrence) return this.pos.from}, + to: function() {if (this.atOccurrence) return this.pos.to}, + + replace: function(newText, origin) { + if (!this.atOccurrence) return + var lines = CodeMirror.splitLines(newText) + this.doc.replaceRange(lines, this.pos.from, this.pos.to, origin) + this.pos.to = Pos(this.pos.from.line + lines.length - 1, + lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0)) + } + } + + CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) { + return new SearchCursor(this.doc, query, pos, caseFold) + }) + CodeMirror.defineDocExtension("getSearchCursor", function(query, pos, caseFold) { + return new SearchCursor(this, query, pos, caseFold) + }) + + CodeMirror.defineExtension("selectMatches", function(query, caseFold) { + var ranges = [] + var cur = this.getSearchCursor(query, this.getCursor("from"), caseFold) + while (cur.findNext()) { + if (CodeMirror.cmpPos(cur.to(), this.getCursor("to")) > 0) break + ranges.push({anchor: cur.from(), head: cur.to()}) + } + if (ranges.length) + this.setSelections(ranges, 0) + }) +}); diff --git a/modules/editor/codemirror/addon/tern/worker.js b/modules/editor/codemirror/addon/tern/worker.js @@ -0,0 +1,44 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// declare global: tern, server + +var server; + +this.onmessage = function(e) { + var data = e.data; + switch (data.type) { + case "init": return startServer(data.defs, data.plugins, data.scripts); + case "add": return server.addFile(data.name, data.text); + case "del": return server.delFile(data.name); + case "req": return server.request(data.body, function(err, reqData) { + postMessage({id: data.id, body: reqData, err: err && String(err)}); + }); + case "getFile": + var c = pending[data.id]; + delete pending[data.id]; + return c(data.err, data.text); + default: throw new Error("Unknown message type: " + data.type); + } +}; + +var nextId = 0, pending = {}; +function getFile(file, c) { + postMessage({type: "getFile", name: file, id: ++nextId}); + pending[nextId] = c; +} + +function startServer(defs, plugins, scripts) { + if (scripts) importScripts.apply(null, scripts); + + server = new tern.Server({ + getFile: getFile, + async: true, + defs: defs, + plugins: plugins + }); +} + +this.console = { + log: function(v) { postMessage({type: "debug", message: v}); } +}; diff --git a/modules/editor/codemirror/bin/authors.sh b/modules/editor/codemirror/bin/authors.sh @@ -0,0 +1,6 @@ +# Combine existing list of authors with everyone known in git, sort, add header. +tail --lines=+3 AUTHORS > AUTHORS.tmp +git log --format='%aN' | grep -v "Piët Delport" >> AUTHORS.tmp +echo -e "List of CodeMirror contributors. Updated before every release.\n" > AUTHORS +sort -u AUTHORS.tmp >> AUTHORS +rm -f AUTHORS.tmp diff --git a/modules/editor/codemirror/demo/activeline.html b/modules/editor/codemirror/demo/activeline.html @@ -0,0 +1,88 @@ +<!doctype html> + +<title>CodeMirror: Active Line Demo</title> +<meta charset="utf-8"/> +<link rel=stylesheet href="../doc/docs.css"> + +<link rel="stylesheet" href="../lib/codemirror.css"> +<script src="../lib/codemirror.js"></script> +<script src="../mode/xml/xml.js"></script> +<script src="../addon/selection/active-line.js"></script> +<style type="text/css"> + .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;} + </style> +<div id=nav> + <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../doc/logo.png"></a> + + <ul> + <li><a href="../index.html">Home</a> + <li><a href="../doc/manual.html">Manual</a> + <li><a href="https://github.com/codemirror/codemirror">Code</a> + </ul> + <ul> + <li><a class=active href="#">Active Line</a> + </ul> +</div> + +<article> +<h2>Active Line Demo</h2> +<form><textarea id="code" name="code"> +<?xml version="1.0" encoding="UTF-8"?> +<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" + xmlns:georss="http://www.georss.org/georss" + xmlns:twitter="http://api.twitter.com"> + <channel> + <title>Twitter / codemirror</title> + <link>http://twitter.com/codemirror</link> + <atom:link type="application/rss+xml" + href="http://twitter.com/statuses/user_timeline/242283288.rss" rel="self"/> + <description>Twitter updates from CodeMirror / codemirror.</description> + <language>en-us</language> + <ttl>40</ttl> + <item> + <title>codemirror: http://cloud-ide.com &#8212; they're springing up like mushrooms. This one + uses CodeMirror as its editor.</title> + <description>codemirror: http://cloud-ide.com &#8212; they're springing up like mushrooms. This + one uses CodeMirror as its editor.</description> + <pubDate>Thu, 17 Mar 2011 23:34:47 +0000</pubDate> + <guid>http://twitter.com/codemirror/statuses/48527733722058752</guid> + <link>http://twitter.com/codemirror/statuses/48527733722058752</link> + <twitter:source>web</twitter:source> + <twitter:place/> + </item> + <item> + <title>codemirror: Posted a description of the CodeMirror 2 internals at + http://codemirror.net/2/internals.html</title> + <description>codemirror: Posted a description of the CodeMirror 2 internals at + http://codemirror.net/2/internals.html</description> + <pubDate>Wed, 02 Mar 2011 12:15:09 +0000</pubDate> + <guid>http://twitter.com/codemirror/statuses/42920879788789760</guid> + <link>http://twitter.com/codemirror/statuses/42920879788789760</link> + <twitter:source>web</twitter:source> + <twitter:place/> + </item> + </channel> +</rss></textarea></form> + + <script> +var nonEmpty = false; +var editor = CodeMirror.fromTextArea(document.getElementById("code"), { + mode: "application/xml", + styleActiveLine: true, + lineNumbers: true, + lineWrapping: true +}); + +function toggleSelProp() { + nonEmpty = !nonEmpty; + editor.setOption("styleActiveLine", {nonEmpty: nonEmpty}); + var label = nonEmpty ? 'Disable nonEmpty option' : 'Enable nonEmpty option'; + document.getElementById('toggleButton').innerText = label; +} +</script> + + <p>Styling the current cursor line.</p> + + <button onclick="toggleSelProp()" id="toggleButton">Enable <code>nonEmpty</code> option</button> + + </article> diff --git a/modules/editor/codemirror/demo/folding.html b/modules/editor/codemirror/demo/folding.html @@ -0,0 +1,133 @@ +<!doctype html> + +<head> + <title>CodeMirror: Code Folding Demo</title> + <meta charset="utf-8"/> + <link rel=stylesheet href="../doc/docs.css"> + + <style> + .some-css { + color: red; + line-height: 2; + } + </style> + + <link rel="stylesheet" href="../lib/codemirror.css"> + <link rel="stylesheet" href="../addon/fold/foldgutter.css" /> + <script src="../lib/codemirror.js"></script> + <script src="../addon/fold/foldcode.js"></script> + <script src="../addon/fold/foldgutter.js"></script> + <script src="../addon/fold/brace-fold.js"></script> + <script src="../addon/fold/xml-fold.js"></script> + <script src="../addon/fold/indent-fold.js"></script> + <script src="../addon/fold/markdown-fold.js"></script> + <script src="../addon/fold/comment-fold.js"></script> + <script src="../mode/javascript/javascript.js"></script> + <script src="../mode/xml/xml.js"></script> + <script src="../mode/css/css.js"></script> + <script src="../mode/htmlmixed/htmlmixed.js"></script> + <script src="../mode/python/python.js"></script> + <script src="../mode/markdown/markdown.js"></script> + <style type="text/css"> + .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;} + </style> +</head> + +<body> +<div id=nav> + <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../doc/logo.png"></a> + + <ul> + <li><a href="../index.html">Home</a> + <li><a href="../doc/manual.html">Manual</a> + <li><a href="https://github.com/codemirror/codemirror">Code</a> + </ul> + <ul> + <li><a class=active href="#">Code Folding</a> + </ul> +</div> + +<article> + <h2>Code Folding Demo</h2> + <form> + <div style="max-width: 50em; margin-bottom: 1em">JavaScript:<br> + <textarea id="code" name="code"></textarea></div> + <div style="max-width: 50em; margin-bottom: 1em">HTML:<br> + <textarea id="code-html" name="code-html"></textarea></div> + <div style="max-width: 50em">Python:<br> + <textarea id="code-python" name="code"> +def foo(): + do_some_stuff() + here + return None + +class Bar: + __init__(self): + if True: + print("True") + else: + print("False") + + this_code_makes_no_sense(): + pass + +# A comment</textarea></div> + <div style="max-width: 50em">Markdown:<br> + <textarea id="code-markdown" name="code"></textarea></div> + </form> + <script id="script"> +/* + * Demonstration of code folding + */ +window.onload = function() { + var te = document.getElementById("code"); + var sc = document.getElementById("script"); + te.value = (sc.textContent || sc.innerText || sc.innerHTML).replace(/^\s*/, ""); + sc.innerHTML = ""; + var te_html = document.getElementById("code-html"); + te_html.value = document.documentElement.innerHTML; + var te_python = document.getElementById("code-python"); + var te_markdown = document.getElementById("code-markdown"); + te_markdown.value = "# Foo\n## Bar\n\nblah blah\n\n## Baz\n\nblah blah\n\n# Quux\n\nblah blah\n" + + window.editor = CodeMirror.fromTextArea(te, { + mode: "javascript", + lineNumbers: true, + lineWrapping: true, + extraKeys: {"Ctrl-Q": function(cm){ cm.foldCode(cm.getCursor()); }}, + foldGutter: true, + gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"] + }); + editor.foldCode(CodeMirror.Pos(13, 0)); + + window.editor_html = CodeMirror.fromTextArea(te_html, { + mode: "text/html", + lineNumbers: true, + lineWrapping: true, + extraKeys: {"Ctrl-Q": function(cm){ cm.foldCode(cm.getCursor()); }}, + foldGutter: true, + gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"] + }); + editor_html.foldCode(CodeMirror.Pos(0, 0)); + editor_html.foldCode(CodeMirror.Pos(34, 0)); + + window.editor_python = CodeMirror.fromTextArea(te_python, { + mode: "python", + lineNumbers: true, + extraKeys: {"Ctrl-Q": function(cm){ cm.foldCode(cm.getCursor()); }}, + foldGutter: true, + gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"] + }); + + window.editor_markdown = CodeMirror.fromTextArea(te_markdown, { + mode: "markdown", + lineNumbers: true, + lineWrapping: true, + extraKeys: {"Ctrl-Q": function(cm){ cm.foldCode(cm.getCursor()); }}, + foldGutter: true, + gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"] + }); +}; + </script> +</article> +</body> diff --git a/modules/editor/codemirror/demo/matchtags.html b/modules/editor/codemirror/demo/matchtags.html @@ -0,0 +1,48 @@ +<!doctype html> + +<title>CodeMirror: Tag Matcher Demo</title> +<meta charset="utf-8"/> +<link rel=stylesheet href="../doc/docs.css"> + +<link rel="stylesheet" href="../lib/codemirror.css"> +<script src="../lib/codemirror.js"></script> +<script src="../addon/fold/xml-fold.js"></script> +<script src="../addon/edit/matchtags.js"></script> +<script src="../mode/xml/xml.js"></script> +<style type="text/css"> + .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;} + </style> +<div id=nav> + <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../doc/logo.png"></a> + + <ul> + <li><a href="../index.html">Home</a> + <li><a href="../doc/manual.html">Manual</a> + <li><a href="https://github.com/codemirror/codemirror">Code</a> + </ul> + <ul> + <li><a class=active href="#">Tag Matcher</a> + </ul> +</div> + +<article> +<h2>Tag Matcher Demo</h2> + + + <div id="editor"></div> + + <script> +window.onload = function() { + editor = CodeMirror(document.getElementById("editor"), { + value: "<html>\n " + document.documentElement.innerHTML + "\n</html>", + mode: "text/html", + matchTags: {bothTags: true}, + extraKeys: {"Ctrl-J": "toMatchingTag"} + }); +}; + </script> + + <p>Put the cursor on or inside a pair of tags to highlight them. + Press Ctrl-J to jump to the tag that matches the one under the + cursor.</p> + </article> diff --git a/modules/editor/codemirror/demo/mustache.html b/modules/editor/codemirror/demo/mustache.html @@ -0,0 +1,69 @@ +<!doctype html> + +<title>CodeMirror: Overlay Parser Demo</title> +<meta charset="utf-8"/> +<link rel=stylesheet href="../doc/docs.css"> + +<link rel="stylesheet" href="../lib/codemirror.css"> +<script src="../lib/codemirror.js"></script> +<script src="../addon/mode/overlay.js"></script> +<script src="../mode/xml/xml.js"></script> +<style type="text/css"> + .CodeMirror {border: 1px solid black;} + .cm-mustache {color: #0ca;} +</style> +<div id=nav> + <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../doc/logo.png"></a> + + <ul> + <li><a href="../index.html">Home</a> + <li><a href="../doc/manual.html">Manual</a> + <li><a href="https://github.com/codemirror/codemirror">Code</a> + </ul> + <ul> + <li><a class=active href="#">Overlay Parser</a> + </ul> +</div> + +<article> +<h2>Overlay Parser Demo</h2> +<form><textarea id="code" name="code"> +<html> + <body> + <h1>{{title}}</h1> + <p>These are links to {{things}}:</p> + <ul>{{#links}} + <li><a href="{{url}}">{{text}}</a></li> + {{/links}}</ul> + </body> +</html> +</textarea></form> + + <script> +CodeMirror.defineMode("mustache", function(config, parserConfig) { + var mustacheOverlay = { + token: function(stream, state) { + var ch; + if (stream.match("{{")) { + while ((ch = stream.next()) != null) + if (ch == "}" && stream.next() == "}") { + stream.eat("}"); + return "mustache"; + } + } + while (stream.next() != null && !stream.match("{{", false)) {} + return null; + } + }; + return CodeMirror.overlayMode(CodeMirror.getMode(config, parserConfig.backdrop || "text/html"), mustacheOverlay); +}); +var editor = CodeMirror.fromTextArea(document.getElementById("code"), {mode: "mustache"}); +</script> + + <p>Demonstration of a mode that parses HTML, highlighting + the <a href="http://mustache.github.com/">Mustache</a> templating + directives inside of it by using the code + in <a href="../addon/mode/overlay.js"><code>overlay.js</code></a>. View + source to see the 15 lines of code needed to accomplish this.</p> + + </article> diff --git a/modules/editor/codemirror/demo/runmode.html b/modules/editor/codemirror/demo/runmode.html @@ -0,0 +1,62 @@ +<!doctype html> + +<title>CodeMirror: Mode Runner Demo</title> +<meta charset="utf-8"/> +<link rel=stylesheet href="../doc/docs.css"> + +<link rel="stylesheet" href="../lib/codemirror.css"> +<script src="../lib/codemirror.js"></script> +<script src="../addon/runmode/runmode.js"></script> +<script src="../mode/xml/xml.js"></script> +<div id=nav> + <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../doc/logo.png"></a> + + <ul> + <li><a href="../index.html">Home</a> + <li><a href="../doc/manual.html">Manual</a> + <li><a href="https://github.com/codemirror/codemirror">Code</a> + </ul> + <ul> + <li><a class=active href="#">Mode Runner</a> + </ul> +</div> + +<article> +<h2>Mode Runner Demo</h2> + + + <textarea id="code" style="width: 90%; height: 7em; border: 1px solid black; padding: .2em .4em;"> +<foobar> + <blah>Enter your xml here and press the button below to display + it as highlighted by the CodeMirror XML mode</blah> + <tag2 foo="2" bar="&amp;quot;bar&amp;quot;"/> +</foobar></textarea><br> + <button onclick="doHighlight();">Highlight!</button> + <pre id="output" class="cm-s-default"></pre> + + <script> +function doHighlight() { + CodeMirror.runMode(document.getElementById("code").value, "application/xml", + document.getElementById("output")); +} +</script> + + <p>Running a CodeMirror mode outside of the editor. + The <code>CodeMirror.runMode</code> function, defined + in <code><a href="../addon/runmode/runmode.js">addon/runmode/runmode.js</a></code> takes the following arguments:</p> + + <dl> + <dt><code>text (string)</code></dt> + <dd>The document to run through the highlighter.</dd> + <dt><code>mode (<a href="../doc/manual.html#option_mode">mode spec</a>)</code></dt> + <dd>The mode to use (must be loaded as normal).</dd> + <dt><code>output (function or DOM node)</code></dt> + <dd>If this is a function, it will be called for each token with + two arguments, the token's text and the token's style class (may + be <code>null</code> for unstyled tokens). If it is a DOM node, + the tokens will be converted to <code>span</code> elements as in + an editor, and inserted into the node + (through <code>innerHTML</code>).</dd> + </dl> + + </article> diff --git a/modules/editor/codemirror/demo/tern.html b/modules/editor/codemirror/demo/tern.html @@ -0,0 +1,133 @@ +<!doctype html> + +<title>CodeMirror: Tern Demo</title> +<meta charset="utf-8"/> +<link rel=stylesheet href="../doc/docs.css"> + +<link rel="stylesheet" href="../lib/codemirror.css"> +<link rel="stylesheet" href="../addon/dialog/dialog.css"> +<link rel="stylesheet" href="../addon/hint/show-hint.css"> +<link rel="stylesheet" href="../addon/tern/tern.css"> +<script src="../lib/codemirror.js"></script> +<script src="../mode/javascript/javascript.js"></script> +<script src="../addon/dialog/dialog.js"></script> +<script src="../addon/hint/show-hint.js"></script> +<script src="../addon/tern/tern.js"></script> +<script src="//ternjs.net/node_modules/acorn/dist/acorn.js"></script> +<script src="//ternjs.net/node_modules/acorn/dist/acorn_loose.js"></script> +<script src="//ternjs.net/node_modules/acorn/dist/walk.js"></script> +<script src="//ternjs.net/doc/demo/polyfill.js"></script> +<script src="//ternjs.net/lib/signal.js"></script> +<script src="//ternjs.net/lib/tern.js"></script> +<script src="//ternjs.net/lib/def.js"></script> +<script src="//ternjs.net/lib/comment.js"></script> +<script src="//ternjs.net/lib/infer.js"></script> +<script src="//ternjs.net/plugin/doc_comment.js"></script> +<style> + .CodeMirror {border: 1px solid #ddd;} + </style> +<div id=nav> + <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../doc/logo.png"></a> + + <ul> + <li><a href="../index.html">Home</a> + <li><a href="../doc/manual.html">Manual</a> + <li><a href="https://github.com/codemirror/codemirror">Code</a> + </ul> + <ul> + <li><a class=active href="#">Tern</a> + </ul> +</div> + +<article> +<h2>Tern Demo</h2> +<form><textarea id="code" name="code">// Use ctrl-space to complete something +// Put the cursor in or after an expression, press ctrl-o to +// find its type + +var foo = ["array", "of", "strings"]; +var bar = foo.slice(0, 2).join("").split("a")[0]; + +// Works for locally defined types too. + +function CTor() { this.size = 10; } +CTor.prototype.hallo = "hallo"; + +var baz = new CTor; +baz. + +// You can press ctrl-q when the cursor is on a variable name to +// rename it. Try it with CTor... + +// When the cursor is in an argument list, the arguments are +// shown below the editor. + +[1].reduce( ); + +// And a little more advanced code... + +(function(exports) { + exports.randomElt = function(arr) { + return arr[Math.floor(arr.length * Math.random())]; + }; + exports.strList = "foo".split(""); + exports.intList = exports.strList.map(function(s) { return s.charCodeAt(0); }); +})(window.myMod = {}); + +var randomStr = myMod.randomElt(myMod.strList); +var randomInt = myMod.randomElt(myMod.intList); +</textarea></form> + +<p>Demonstrates integration of <a href="http://ternjs.net/">Tern</a> +and CodeMirror. The following keys are bound:</p> + +<dl> + <dt>Ctrl-Space</dt><dd>Autocomplete</dd> + <dt>Ctrl-O</dt><dd>Find docs for the expression at the cursor</dd> + <dt>Ctrl-I</dt><dd>Find type at cursor</dd> + <dt>Alt-.</dt><dd>Jump to definition (Alt-, to jump back)</dd> + <dt>Ctrl-Q</dt><dd>Rename variable</dd> + <dt>Ctrl-.</dt><dd>Select all occurrences of a variable</dd> +</dl> + +<p>Documentation is sparse for now. See the top of +the <a href="../addon/tern/tern.js">script</a> for a rough API +overview.</p> + +<script> + function getURL(url, c) { + var xhr = new XMLHttpRequest(); + xhr.open("get", url, true); + xhr.send(); + xhr.onreadystatechange = function() { + if (xhr.readyState != 4) return; + if (xhr.status < 400) return c(null, xhr.responseText); + var e = new Error(xhr.responseText || "No response"); + e.status = xhr.status; + c(e); + }; + } + + var server; + getURL("//ternjs.net/defs/ecmascript.json", function(err, code) { + if (err) throw new Error("Request for ecmascript.json: " + err); + server = new CodeMirror.TernServer({defs: [JSON.parse(code)]}); + editor.setOption("extraKeys", { + "Ctrl-Space": function(cm) { server.complete(cm); }, + "Ctrl-I": function(cm) { server.showType(cm); }, + "Ctrl-O": function(cm) { server.showDocs(cm); }, + "Alt-.": function(cm) { server.jumpToDef(cm); }, + "Alt-,": function(cm) { server.jumpBack(cm); }, + "Ctrl-Q": function(cm) { server.rename(cm); }, + "Ctrl-.": function(cm) { server.selectName(cm); } + }) + editor.on("cursorActivity", function(cm) { server.updateArgHints(cm); }); + }); + + var editor = CodeMirror.fromTextArea(document.getElementById("code"), { + lineNumbers: true, + mode: "javascript" + }); +</script> + + </article> diff --git a/modules/editor/codemirror/demo/widget.html b/modules/editor/codemirror/demo/widget.html @@ -0,0 +1,85 @@ +<!doctype html> + +<title>CodeMirror: Inline Widget Demo</title> +<meta charset="utf-8"/> +<link rel=stylesheet href="../doc/docs.css"> + +<link rel="stylesheet" href="../lib/codemirror.css"> +<script src="../lib/codemirror.js"></script> +<script src="../mode/javascript/javascript.js"></script> +<script src="//ajax.aspnetcdn.com/ajax/jshint/r07/jshint.js"></script> +<style type="text/css"> + .CodeMirror {border: 1px solid black;} + .lint-error {font-family: arial; font-size: 70%; background: #ffa; color: #a00; padding: 2px 5px 3px; } + .lint-error-icon {color: white; background-color: red; font-weight: bold; border-radius: 50%; padding: 0 3px; margin-right: 7px;} + </style> +<div id=nav> + <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="../doc/logo.png"></a> + + <ul> + <li><a href="../index.html">Home</a> + <li><a href="../doc/manual.html">Manual</a> + <li><a href="https://github.com/codemirror/codemirror">Code</a> + </ul> + <ul> + <li><a class=active href="#">Inline Widget</a> + </ul> +</div> + +<article> +<h2>Inline Widget Demo</h2> + + + <div id=code></div> + <script id="script">var widgets = [] +function updateHints() { + editor.operation(function(){ + for (var i = 0; i < widgets.length; ++i) + editor.removeLineWidget(widgets[i]); + widgets.length = 0; + + JSHINT(editor.getValue()); + for (var i = 0; i < JSHINT.errors.length; ++i) { + var err = JSHINT.errors[i]; + if (!err) continue; + var msg = document.createElement("div"); + var icon = msg.appendChild(document.createElement("span")); + icon.innerHTML = "!!"; + icon.className = "lint-error-icon"; + msg.appendChild(document.createTextNode(err.reason)); + msg.className = "lint-error"; + widgets.push(editor.addLineWidget(err.line - 1, msg, {coverGutter: false, noHScroll: true})); + } + }); + var info = editor.getScrollInfo(); + var after = editor.charCoords({line: editor.getCursor().line + 1, ch: 0}, "local").top; + if (info.top + info.clientHeight < after) + editor.scrollTo(null, after - info.clientHeight + 3); +} + +window.onload = function() { + var sc = document.getElementById("script"); + var content = sc.textContent || sc.innerText || sc.innerHTML; + + window.editor = CodeMirror(document.getElementById("code"), { + lineNumbers: true, + mode: "javascript", + value: content + }); + + var waiting; + editor.on("change", function() { + clearTimeout(waiting); + waiting = setTimeout(updateHints, 500); + }); + + setTimeout(updateHints, 100); +}; + +"long line to create a horizontal scrollbar, in order to test whether the (non-inline) widgets stay in place when scrolling to the right"; +</script> +<p>This demo runs <a href="http://jshint.com">JSHint</a> over the code +in the editor (which is the script used on this page), and +inserts <a href="../doc/manual.html#addLineWidget">line widgets</a> to +display the warnings that JSHint comes up with.</p> + </article> diff --git a/modules/editor/codemirror/doc/docs.css b/modules/editor/codemirror/doc/docs.css @@ -0,0 +1,271 @@ +@font-face { + font-family: 'Source Sans Pro'; + font-style: normal; + font-weight: 400; + src: local('Source Sans Pro'), local('SourceSansPro-Regular'), url(//themes.googleusercontent.com/static/fonts/sourcesanspro/v5/ODelI1aHBYDBqgeIAH2zlBM0YzuT7MdOe03otPbuUS0.woff) format('woff'); +} + +body, html { margin: 0; padding: 0; height: 100%; } +section, article { display: block; padding: 0; } + +body { + background: #f8f8f8; + font-family: 'Source Sans Pro', Helvetica, Arial, sans-serif; + line-height: 1.5; +} + +p { margin-top: 0; } + +h2, h3, h1 { + font-weight: normal; + margin-bottom: .7em; +} +h1 { font-size: 140%; } +h2 { font-size: 120%; } +h3 { font-size: 110%; } +article > h2:first-child, section:first-child > h2 { margin-top: 0; } + +#nav h1 { + margin-right: 12px; + margin-top: 0; + margin-bottom: 2px; + color: #d30707; + letter-spacing: .5px; +} + +a, a:visited, a:link, .quasilink { + color: #A21313; + text-decoration: none; +} + +em { + padding-right: 2px; +} + +.quasilink { + cursor: pointer; +} + +article { + max-width: 700px; + margin: 0 0 0 160px; + border-left: 2px solid #E30808; + border-right: 1px solid #ddd; + padding: 30px 50px 100px 50px; + background: white; + z-index: 2; + position: relative; + min-height: 100%; + box-sizing: border-box; + -moz-box-sizing: border-box; +} + +#nav { + position: fixed; + padding-top: 30px; + max-height: 100%; + box-sizing: -moz-border-box; + box-sizing: border-box; + overflow-y: auto; + left: 0; right: none; + width: 160px; + text-align: right; + z-index: 1; +} + +@media screen and (min-width: 1000px) { + article { + margin: 0 auto; + } + #nav { + right: 50%; + width: auto; + border-right: 349px solid transparent; + } +} + +#nav ul { + display: block; + margin: 0; padding: 0; + margin-bottom: 32px; +} + +#nav li { + display: block; + margin-bottom: 4px; +} + +#nav li ul { + font-size: 80%; + margin-bottom: 0; + display: none; +} + +#nav li.active ul { + display: block; +} + +#nav li li a { + padding-right: 20px; + display: inline-block; +} + +#nav ul a { + color: black; + padding: 0 7px 1px 11px; +} + +#nav ul a.active, #nav ul a:hover { + border-bottom: 1px solid #E30808; + margin-bottom: -1px; + color: #E30808; +} + +#logo { + border: 0; + margin-right: 12px; + margin-bottom: 25px; +} + +section { + border-top: 1px solid #E30808; + margin: 1.5em 0; +} + +section.first { + border: none; + margin-top: 0; +} + +#demo { + position: relative; +} + +#demolist { + position: absolute; + right: 5px; + top: 5px; + z-index: 25; +} + +.yinyang { + position: absolute; + top: -10px; + left: 0; right: 0; + margin: auto; + display: block; + height: 120px; +} + +.actions { + margin: 1em 0 0; + min-height: 100px; + position: relative; +} + +.actionspicture { + pointer-events: none; + position: absolute; + height: 100px; + top: 0; left: 0; right: 0; +} + +.actionlink { + pointer-events: auto; + font-family: arial; + font-size: 80%; + font-weight: bold; + position: absolute; + top: 0; bottom: 0; + line-height: 1; + height: 1em; + margin: auto; +} + +.actionlink.download { + color: white; + right: 50%; + margin-right: 13px; + text-shadow: -1px 1px 3px #b00, -1px -1px 3px #b00, 1px 0px 3px #b00; +} + +.actionlink.fund { + color: #b00; + left: 50%; + margin-left: 15px; +} + +.actionlink:hover { + text-decoration: underline; +} + +.actionlink a { + color: inherit; +} + +.actionsleft { + float: left; +} + +.actionsright { + float: right; + text-align: right; +} + +@media screen and (max-width: 800px) { + .actions { + padding-top: 120px; + } + .actionsleft, .actionsright { + float: none; + text-align: left; + margin-bottom: 1em; + } +} + +th { + text-decoration: underline; + font-weight: normal; + text-align: left; +} + +#features ul { + list-style: none; + margin: 0 0 1em; + padding: 0 0 0 1.2em; +} + +#features li:before { + content: "-"; + width: 1em; + display: inline-block; + padding: 0; + margin: 0; + margin-left: -1em; +} + +.rel { + margin-bottom: 0; +} +.rel-note { + margin-top: 0; + color: #555; +} + +pre { + padding-left: 15px; + border-left: 2px solid #ddd; +} + +code { + padding: 0 2px; +} + +strong { + text-decoration: underline; + font-weight: normal; +} + +.field { + border: 1px solid #A21313; +} diff --git a/modules/editor/codemirror/doc/logo.png b/modules/editor/codemirror/doc/logo.png Binary files differ. diff --git a/modules/editor/codemirror/doc/manual.html b/modules/editor/codemirror/doc/manual.html @@ -0,0 +1,3527 @@ +<!doctype html> + +<title>CodeMirror: User Manual</title> +<meta charset="utf-8"/> +<link rel=stylesheet href="docs.css"> +<script src="activebookmark.js"></script> + +<script src="../lib/codemirror.js"></script> +<link rel="stylesheet" href="../lib/codemirror.css"> +<script src="../addon/runmode/runmode.js"></script> +<script src="../addon/runmode/colorize.js"></script> +<script src="../mode/javascript/javascript.js"></script> +<script src="../mode/xml/xml.js"></script> +<script src="../mode/css/css.js"></script> +<script src="../mode/htmlmixed/htmlmixed.js"></script> +<style> + dt { text-indent: -2em; padding-left: 2em; margin-top: 1em; } + dd { margin-left: 1.5em; margin-bottom: 1em; } + dt {margin-top: 1em;} + dd dl, dd dt, dd dd, dd ul { margin-top: 0; margin-bottom: 0; } + dt + dt { margin-top: 0; } + dt.command { position: relative; } + span.keybinding { position: absolute; right: 0; font-size: 80%; color: #555; text-indent: 0; } +</style> + +<div id=nav> + <a href="http://codemirror.net"><h1>CodeMirror</h1><img id=logo src="logo.png"></a> + <ul> + <li><a href="../index.html">Home</a></li> + <li><a href="#overview" class=active data-default="true">Manual</a></li> + <li><a href="https://github.com/codemirror/codemirror">Code</a></li> + </ul> + <ul> + <li><a href="#usage">Basic Usage</a></li> + <li><a href="#config">Configuration</a></li> + <li><a href="#events">Events</a></li> + <li><a href="#keymaps">Key maps</a></li> + <li><a href="#commands">Commands</a></li> + <li><a href="#styling">Customized Styling</a></li> + <li><a href="#api">Programming API</a> + <ul> + <li><a href="#api_constructor">Constructor</a></li> + <li><a href="#api_content">Content manipulation</a></li> + <li><a href="#api_selection">Selection</a></li> + <li><a href="#api_configuration">Configuration</a></li> + <li><a href="#api_doc">Document management</a></li> + <li><a href="#api_history">History</a></li> + <li><a href="#api_marker">Text-marking</a></li> + <li><a href="#api_decoration">Widget, gutter, and decoration</a></li> + <li><a href="#api_sizing">Sizing, scrolling, and positioning</a></li> + <li><a href="#api_mode">Mode, state, and tokens</a></li> + <li><a href="#api_misc">Miscellaneous methods</a></li> + <li><a href="#api_static">Static properties</a></li> + </ul> + </li> + <li><a href="#addons">Addons</a></li> + <li><a href="#modeapi">Writing CodeMirror Modes</a></li> + <li><a href="#vimapi">Vim Mode API</a> + <ul> + <li><a href="#vimapi_configuration">Configuration</a></li> + <li><a href="#vimapi_extending">Extending VIM</a></li> + </ul> + </li> + </ul> +</div> + +<article> + +<section class=first id=overview> + <h2 style="position: relative"> + User manual and reference guide + <span style="color: #888; font-size: 1rem; position: absolute; right: 0; bottom: 0">version 5.32.0</span> + </h2> + + <p>CodeMirror is a code-editor component that can be embedded in + Web pages. The core library provides <em>only</em> the editor + component, no accompanying buttons, auto-completion, or other IDE + functionality. It does provide a rich API on top of which such + functionality can be straightforwardly implemented. See + the <a href="#addons">addons</a> included in the distribution, + and the <a href="https://github.com/codemirror/CodeMirror/wiki/CodeMirror-addons">list + of externally hosted addons</a>, for reusable + implementations of extra features.</p> + + <p>CodeMirror works with language-specific modes. Modes are + JavaScript programs that help color (and optionally indent) text + written in a given language. The distribution comes with a number + of modes (see the <a href="../mode/"><code>mode/</code></a> + directory), and it isn't hard to <a href="#modeapi">write new + ones</a> for other languages.</p> +</section> + +<section id=usage> + <h2>Basic Usage</h2> + + <p>The easiest way to use CodeMirror is to simply load the script + and style sheet found under <code>lib/</code> in the distribution, + plus a mode script from one of the <code>mode/</code> directories. + For example:</p> + + <pre data-lang="text/html">&lt;script src="lib/codemirror.js">&lt;/script> +&lt;link rel="stylesheet" href="lib/codemirror.css"> +&lt;script src="mode/javascript/javascript.js">&lt;/script></pre> + + <p>(Alternatively, use a module loader. <a href="#modloader">More + about that later.</a>)</p> + + <p>Having done this, an editor instance can be created like + this:</p> + + <pre data-lang="javascript">var myCodeMirror = CodeMirror(document.body);</pre> + + <p>The editor will be appended to the document body, will start + empty, and will use the mode that we loaded. To have more control + over the new editor, a configuration object can be passed + to <a href="#CodeMirror"><code>CodeMirror</code></a> as a second + argument:</p> + + <pre data-lang="javascript">var myCodeMirror = CodeMirror(document.body, { + value: "function myScript(){return 100;}\n", + mode: "javascript" +});</pre> + + <p>This will initialize the editor with a piece of code already in + it, and explicitly tell it to use the JavaScript mode (which is + useful when multiple modes are loaded). + See <a href="#config">below</a> for a full discussion of the + configuration options that CodeMirror accepts.</p> + + <p>In cases where you don't want to append the editor to an + element, and need more control over the way it is inserted, the + first argument to the <code>CodeMirror</code> function can also + be a function that, when given a DOM element, inserts it into the + document somewhere. This could be used to, for example, replace a + textarea with a real editor:</p> + + <pre data-lang="javascript">var myCodeMirror = CodeMirror(function(elt) { + myTextArea.parentNode.replaceChild(elt, myTextArea); +}, {value: myTextArea.value});</pre> + + <p>However, for this use case, which is a common way to use + CodeMirror, the library provides a much more powerful + shortcut:</p> + + <pre data-lang="javascript">var myCodeMirror = CodeMirror.fromTextArea(myTextArea);</pre> + + <p>This will, among other things, ensure that the textarea's value + is updated with the editor's contents when the form (if it is part + of a form) is submitted. See the <a href="#fromTextArea">API + reference</a> for a full description of this method.</p> + + <h3 id=modloader>Module loaders</h3> + + <p>The files in the CodeMirror distribution contain shims for + loading them (and their dependencies) in AMD or CommonJS + environments. If the variables <code>exports</code> + and <code>module</code> exist and have type object, CommonJS-style + require will be used. If not, but there is a + function <code>define</code> with an <code>amd</code> property + present, AMD-style (RequireJS) will be used.</p> + + <p>It is possible to + use <a href="http://browserify.org/">Browserify</a> or similar + tools to statically build modules using CodeMirror. Alternatively, + use <a href="http://requirejs.org/">RequireJS</a> to dynamically + load dependencies at runtime. Both of these approaches have the + advantage that they don't use the global namespace and can, thus, + do things like load multiple versions of CodeMirror alongside each + other.</p> + + <p>Here's a simple example of using RequireJS to load CodeMirror:</p> + + <pre data-lang="javascript">require([ + "cm/lib/codemirror", "cm/mode/htmlmixed/htmlmixed" +], function(CodeMirror) { + CodeMirror.fromTextArea(document.getElementById("code"), { + lineNumbers: true, + mode: "htmlmixed" + }); +});</pre> + + <p>It will automatically load the modes that the mixed HTML mode + depends on (XML, JavaScript, and CSS). Do <em>not</em> use + RequireJS' <code>paths</code> option to configure the path to + CodeMirror, since it will break loading submodules through + relative paths. Use + the <a href="http://requirejs.org/docs/api.html#packages"><code>packages</code></a> + configuration option instead, as in:</p> + + <pre data-lang=javascript>require.config({ + packages: [{ + name: "codemirror", + location: "../path/to/codemirror", + main: "lib/codemirror" + }] +});</pre> + +</section> + +<section id=config> + <h2>Configuration</h2> + + <p>Both the <a href="#CodeMirror"><code>CodeMirror</code></a> + function and its <code>fromTextArea</code> method take as second + (optional) argument an object containing configuration options. + Any option not supplied like this will be taken + from <a href="#defaults"><code>CodeMirror.defaults</code></a>, an + object containing the default options. You can update this object + to change the defaults on your page.</p> + + <p>Options are not checked in any way, so setting bogus option + values is bound to lead to odd errors.</p> + + <p>These are the supported options:</p> + + <dl> + <dt id="option_value"><code><strong>value</strong>: string|CodeMirror.Doc</code></dt> + <dd>The starting value of the editor. Can be a string, or + a <a href="#api_doc">document object</a>.</dd> + + <dt id="option_mode"><code><strong>mode</strong>: string|object</code></dt> + <dd>The mode to use. When not given, this will default to the + first mode that was loaded. It may be a string, which either + simply names the mode or is + a <a href="http://en.wikipedia.org/wiki/MIME">MIME</a> type + associated with the mode. Alternatively, it may be an object + containing configuration options for the mode, with + a <code>name</code> property that names the mode (for + example <code>{name: "javascript", json: true}</code>). The demo + pages for each mode contain information about what configuration + parameters the mode supports. You can ask CodeMirror which modes + and MIME types have been defined by inspecting + the <code>CodeMirror.modes</code> + and <code>CodeMirror.mimeModes</code> objects. The first maps + mode names to their constructors, and the second maps MIME types + to mode specs.</dd> + + <dt id="option_lineSeparator"><code><strong>lineSeparator</strong>: string|null</code></dt> + <dd>Explicitly set the line separator for the editor. By default + (value <code>null</code>), the document will be split on CRLFs + as well as lone CRs and LFs, and a single LF will be used as + line separator in all output (such + as <a href="#getValue"><code>getValue</code></a>). When a + specific string is given, lines will only be split on that + string, and output will, by default, use that same + separator.</dd> + + <dt id="option_theme"><code><strong>theme</strong>: string</code></dt> + <dd>The theme to style the editor with. You must make sure the + CSS file defining the corresponding <code>.cm-s-[name]</code> + styles is loaded (see + the <a href="../theme/"><code>theme</code></a> directory in the + distribution). The default is <code>"default"</code>, for which + colors are included in <code>codemirror.css</code>. It is + possible to use multiple theming classes at once—for + example <code>"foo bar"</code> will assign both + the <code>cm-s-foo</code> and the <code>cm-s-bar</code> classes + to the editor.</dd> + + <dt id="option_indentUnit"><code><strong>indentUnit</strong>: integer</code></dt> + <dd>How many spaces a block (whatever that means in the edited + language) should be indented. The default is 2.</dd> + + <dt id="option_smartIndent"><code><strong>smartIndent</strong>: boolean</code></dt> + <dd>Whether to use the context-sensitive indentation that the + mode provides (or just indent the same as the line before). + Defaults to true.</dd> + + <dt id="option_tabSize"><code><strong>tabSize</strong>: integer</code></dt> + <dd>The width of a tab character. Defaults to 4.</dd> + + <dt id="option_indentWithTabs"><code><strong>indentWithTabs</strong>: boolean</code></dt> + <dd>Whether, when indenting, the first N*<code>tabSize</code> + spaces should be replaced by N tabs. Default is false.</dd> + + <dt id="option_electricChars"><code><strong>electricChars</strong>: boolean</code></dt> + <dd>Configures whether the editor should re-indent the current + line when a character is typed that might change its proper + indentation (only works if the mode supports indentation). + Default is true.</dd> + + <dt id="option_specialChars"><code><strong>specialChars</strong>: RegExp</code></dt> + <dd>A regular expression used to determine which characters + should be replaced by a + special <a href="#option_specialCharPlaceholder">placeholder</a>. + Mostly useful for non-printing special characters. The default + is <code>/[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/</code>.</dd> + <dt id="option_specialCharPlaceholder"><code><strong>specialCharPlaceholder</strong>: function(char) → Element</code></dt> + <dd>A function that, given a special character identified by + the <a href="#option_specialChars"><code>specialChars</code></a> + option, produces a DOM node that is used to represent the + character. By default, a red dot (<span style="color: red">•</span>) + is shown, with a title tooltip to indicate the character code.</dd> + + <dt id="option_rtlMoveVisually"><code><strong>rtlMoveVisually</strong>: boolean</code></dt> + <dd>Determines whether horizontal cursor movement through + right-to-left (Arabic, Hebrew) text is visual (pressing the left + arrow moves the cursor left) or logical (pressing the left arrow + moves to the next lower index in the string, which is visually + right in right-to-left text). The default is <code>false</code> + on Windows, and <code>true</code> on other platforms.</dd> + + <dt id="option_keyMap"><code><strong>keyMap</strong>: string</code></dt> + <dd>Configures the key map to use. The default + is <code>"default"</code>, which is the only key map defined + in <code>codemirror.js</code> itself. Extra key maps are found in + the <a href="../keymap/"><code>key map</code></a> directory. See + the <a href="#keymaps">section on key maps</a> for more + information.</dd> + + <dt id="option_extraKeys"><code><strong>extraKeys</strong>: object</code></dt> + <dd>Can be used to specify extra key bindings for the editor, + alongside the ones defined + by <a href="#option_keyMap"><code>keyMap</code></a>. Should be + either null, or a valid <a href="#keymaps">key map</a> value.</dd> + + <dt id="option_configureMouse"><code><strong>configureMouse</strong>: fn(cm: CodeMirror, repeat: "single" | "double" | "triple", event: Event) → Object</code></dt> + <dd>Allows you to configure the behavior of mouse selection and + dragging. The function is called when the left mouse button is + pressed. The returned object may have the following properties: + <dl> + <dt><code><strong>unit</strong>: "char" | "word" | "line" | "rectangle" | fn(CodeMirror, Pos) → {from: Pos, to: Pos}</code></dt> + <dd>The unit by which to select. May be one of the built-in + units, or a function that takes a position and returns a + range around that, for a custom unit.</dd> + <dt><code><strong>extend</strong>: bool</code></dt> + <dd>Whether to extend the existing selection range or start a new one.</dd> + <dt><code><strong>addNew</strong>: bool</code></dt> + <dd>When enabled, this adds a new range to the existing selection, rather than replacing it.</dd> + <dt><code><strong>moveOnDrag</strong>: bool</code></dt> + <dd>When the mouse even drags content around inside the + editor, this controls whether it is copied (false) or moved + (true).</dt> + </dl> + </dd> + + <dt id="option_lineWrapping"><code><strong>lineWrapping</strong>: boolean</code></dt> + <dd>Whether CodeMirror should scroll or wrap for long lines. + Defaults to <code>false</code> (scroll).</dd> + + <dt id="option_lineNumbers"><code><strong>lineNumbers</strong>: boolean</code></dt> + <dd>Whether to show line numbers to the left of the editor.</dd> + + <dt id="option_firstLineNumber"><code><strong>firstLineNumber</strong>: integer</code></dt> + <dd>At which number to start counting lines. Default is 1.</dd> + + <dt id="option_lineNumberFormatter"><code><strong>lineNumberFormatter</strong>: function(line: integer) → string</code></dt> + <dd>A function used to format line numbers. The function is + passed the line number, and should return a string that will be + shown in the gutter.</dd> + + <dt id="option_gutters"><code><strong>gutters</strong>: array&lt;string&gt;</code></dt> + <dd>Can be used to add extra gutters (beyond or instead of the + line number gutter). Should be an array of CSS class names, each + of which defines a <code>width</code> (and optionally a + background), and which will be used to draw the background of + the gutters. <em>May</em> include + the <code>CodeMirror-linenumbers</code> class, in order to + explicitly set the position of the line number gutter (it will + default to be to the right of all other gutters). These class + names are the keys passed + to <a href="#setGutterMarker"><code>setGutterMarker</code></a>.</dd> + + <dt id="option_fixedGutter"><code><strong>fixedGutter</strong>: boolean</code></dt> + <dd>Determines whether the gutter scrolls along with the content + horizontally (false) or whether it stays fixed during horizontal + scrolling (true, the default).</dd> + + <dt id="option_scrollbarStyle"><code><strong>scrollbarStyle</strong>: string</code></dt> + <dd>Chooses a scrollbar implementation. The default + is <code>"native"</code>, showing native scrollbars. The core + library also provides the <code>"null"</code> style, which + completely hides the + scrollbars. <a href="#addon_simplescrollbars">Addons</a> can + implement additional scrollbar models.</dd> + + <dt id="option_coverGutterNextToScrollbar"><code><strong>coverGutterNextToScrollbar</strong>: boolean</code></dt> + <dd>When <a href="#option_fixedGutter"><code>fixedGutter</code></a> + is on, and there is a horizontal scrollbar, by default the + gutter will be visible to the left of this scrollbar. If this + option is set to true, it will be covered by an element with + class <code>CodeMirror-gutter-filler</code>.</dd> + + <dt id="option_inputStyle"><code><strong>inputStyle</strong>: string</code></dt> + <dd>Selects the way CodeMirror handles input and focus. The core + library defines the <code>"textarea"</code> + and <code>"contenteditable"</code> input models. On mobile + browsers, the default is <code>"contenteditable"</code>. On + desktop browsers, the default is <code>"textarea"</code>. + Support for IME and screen readers is better in + the <code>"contenteditable"</code> model. The intention is to + make it the default on modern desktop browsers in the + future.</dd> + + <dt id="option_readOnly"><code><strong>readOnly</strong>: boolean|string</code></dt> + <dd>This disables editing of the editor content by the user. If + the special value <code>"nocursor"</code> is given (instead of + simply <code>true</code>), focusing of the editor is also + disallowed.</dd> + + <dt id="option_showCursorWhenSelecting"><code><strong>showCursorWhenSelecting</strong>: boolean</code></dt> + <dd>Whether the cursor should be drawn when a selection is + active. Defaults to false.</dd> + + <dt id="option_lineWiseCopyCut"><code><strong>lineWiseCopyCut</strong>: boolean</code></dt> + <dd>When enabled, which is the default, doing copy or cut when + there is no selection will copy or cut the whole lines that have + cursors on them.</dd> + + <dt id="option_pasteLinesPerSelection"><code><strong>pasteLinesPerSelection</strong>: boolean</code></dt> + <dd>When pasting something from an external source (not from the + editor itself), if the number of lines matches the number of + selection, CodeMirror will by default insert one line per + selection. You can set this to <code>false</code> to disable + that behavior.</dd> + + <dt id="option_undoDepth"><code><strong>undoDepth</strong>: integer</code></dt> + <dd>The maximum number of undo levels that the editor stores. + Note that this includes selection change events. Defaults to + 200.</dd> + + <dt id="option_historyEventDelay"><code><strong>historyEventDelay</strong>: integer</code></dt> + <dd>The period of inactivity (in milliseconds) that will cause a + new history event to be started when typing or deleting. + Defaults to 1250.</dd> + + <dt id="option_tabindex"><code><strong>tabindex</strong>: integer</code></dt> + <dd>The <a href="http://www.w3.org/TR/html401/interact/forms.html#adef-tabindex">tab + index</a> to assign to the editor. If not given, no tab index + will be assigned.</dd> + + <dt id="option_autofocus"><code><strong>autofocus</strong>: boolean</code></dt> + <dd>Can be used to make CodeMirror focus itself on + initialization. Defaults to off. + When <a href="#fromTextArea"><code>fromTextArea</code></a> is + used, and no explicit value is given for this option, it will be + set to true when either the source textarea is focused, or it + has an <code>autofocus</code> attribute and no other element is + focused.</dd> + </dl> + + <p>Below this a few more specialized, low-level options are + listed. These are only useful in very specific situations, you + might want to skip them the first time you read this manual.</p> + + <dl> + <dt id="option_dragDrop"><code><strong>dragDrop</strong>: boolean</code></dt> + <dd>Controls whether drag-and-drop is enabled. On by default.</dd> + + <dt id="option_allowDropFileTypes"><code><strong>allowDropFileTypes</strong>: array&lt;string&gt;</code></dt> + <dd>When set (default is <code>null</code>) only files whose + type is in the array can be dropped into the editor. The strings + should be MIME types, and will be checked against + the <a href="https://w3c.github.io/FileAPI/#dfn-type"><code>type</code></a> + of the <code>File</code> object as reported by the browser.</dd> + + <dt id="option_cursorBlinkRate"><code><strong>cursorBlinkRate</strong>: number</code></dt> + <dd>Half-period in milliseconds used for cursor blinking. The default blink + rate is 530ms. By setting this to zero, blinking can be disabled. A + negative value hides the cursor entirely.</dd> + + <dt id="option_cursorScrollMargin"><code><strong>cursorScrollMargin</strong>: number</code></dt> + <dd>How much extra space to always keep above and below the + cursor when approaching the top or bottom of the visible view in + a scrollable document. Default is 0.</dd> + + <dt id="option_cursorHeight"><code><strong>cursorHeight</strong>: number</code></dt> + <dd>Determines the height of the cursor. Default is 1, meaning + it spans the whole height of the line. For some fonts (and by + some tastes) a smaller height (for example <code>0.85</code>), + which causes the cursor to not reach all the way to the bottom + of the line, looks better</dd> + + <dt id="option_resetSelectionOnContextMenu"><code><strong>resetSelectionOnContextMenu</strong>: boolean</code></dt> + <dd>Controls whether, when the context menu is opened with a + click outside of the current selection, the cursor is moved to + the point of the click. Defaults to <code>true</code>.</dd> + + <dt id="option_workTime"><code id="option_wordkDelay"><strong>workTime</strong>, <strong>workDelay</strong>: number</code></dt> + <dd>Highlighting is done by a pseudo background-thread that will + work for <code>workTime</code> milliseconds, and then use + timeout to sleep for <code>workDelay</code> milliseconds. The + defaults are 200 and 300, you can change these options to make + the highlighting more or less aggressive.</dd> + + <dt id="option_pollInterval"><code><strong>pollInterval</strong>: number</code></dt> + <dd>Indicates how quickly CodeMirror should poll its input + textarea for changes (when focused). Most input is captured by + events, but some things, like IME input on some browsers, don't + generate events that allow CodeMirror to properly detect it. + Thus, it polls. Default is 100 milliseconds.</dd> + + <dt id="option_flattenSpans"><code><strong>flattenSpans</strong>: boolean</code></dt> + <dd>By default, CodeMirror will combine adjacent tokens into a + single span if they have the same class. This will result in a + simpler DOM tree, and thus perform better. With some kinds of + styling (such as rounded corners), this will change the way the + document looks. You can set this option to false to disable this + behavior.</dd> + + <dt id="option_addModeClass"><code><strong>addModeClass</strong>: boolean</code></dt> + <dd>When enabled (off by default), an extra CSS class will be + added to each token, indicating the + (<a href="#innerMode">inner</a>) mode that produced it, prefixed + with <code>"cm-m-"</code>. For example, tokens from the XML mode + will get the <code>cm-m-xml</code> class.</dd> + + <dt id="option_maxHighlightLength"><code><strong>maxHighlightLength</strong>: number</code></dt> + <dd>When highlighting long lines, in order to stay responsive, + the editor will give up and simply style the rest of the line as + plain text when it reaches a certain position. The default is + 10 000. You can set this to <code>Infinity</code> to turn off + this behavior.</dd> + + <dt id="option_viewportMargin"><code><strong>viewportMargin</strong>: integer</code></dt> + <dd>Specifies the amount of lines that are rendered above and + below the part of the document that's currently scrolled into + view. This affects the amount of updates needed when scrolling, + and the amount of work that such an update does. You should + usually leave it at its default, 10. Can be set + to <code>Infinity</code> to make sure the whole document is + always rendered, and thus the browser's text search works on it. + This <em>will</em> have bad effects on performance of big + documents.</dd> + </dl> +</section> + +<section id=events> + <h2>Events</h2> + + <p>Various CodeMirror-related objects emit events, which allow + client code to react to various situations. Handlers for such + events can be registered with the <a href="#on"><code>on</code></a> + and <a href="#off"><code>off</code></a> methods on the objects + that the event fires on. To fire your own events, + use <code>CodeMirror.signal(target, name, args...)</code>, + where <code>target</code> is a non-DOM-node object.</p> + + <p>An editor instance fires the following events. + The <code>instance</code> argument always refers to the editor + itself.</p> + + <dl> + <dt id="event_change"><code><strong>"change"</strong> (instance: CodeMirror, changeObj: object)</code></dt> + <dd>Fires every time the content of the editor is changed. + The <code>changeObj</code> is a <code>{from, to, text, removed, + origin}</code> object containing information about the changes + that occurred as second argument. <code>from</code> + and <code>to</code> are the positions (in the pre-change + coordinate system) where the change started and ended (for + example, it might be <code>{ch:0, line:18}</code> if the + position is at the beginning of line #19). <code>text</code> is + an array of strings representing the text that replaced the + changed range (split by line). <code>removed</code> is the text + that used to be between <code>from</code> and <code>to</code>, + which is overwritten by this change. This event is + fired <em>before</em> the end of + an <a href="#operation">operation</a>, before the DOM updates + happen.</dd> + + <dt id="event_changes"><code><strong>"changes"</strong> (instance: CodeMirror, changes: array&lt;object&gt;)</code></dt> + <dd>Like the <a href="#event_change"><code>"change"</code></a> + event, but batched per <a href="#operation">operation</a>, + passing an array containing all the changes that happened in the + operation. This event is fired after the operation finished, and + display changes it makes will trigger a new operation.</dd> + + <dt id="event_beforeChange"><code><strong>"beforeChange"</strong> (instance: CodeMirror, changeObj: object)</code></dt> + <dd>This event is fired before a change is applied, and its + handler may choose to modify or cancel the change. + The <code>changeObj</code> object + has <code>from</code>, <code>to</code>, and <code>text</code> + properties, as with + the <a href="#event_change"><code>"change"</code></a> event. It + also has a <code>cancel()</code> method, which can be called to + cancel the change, and, <strong>if</strong> the change isn't + coming from an undo or redo event, an <code>update(from, to, + text)</code> method, which may be used to modify the change. + Undo or redo changes can't be modified, because they hold some + metainformation for restoring old marked ranges that is only + valid for that specific change. All three arguments + to <code>update</code> are optional, and can be left off to + leave the existing value for that field + intact. <strong>Note:</strong> you may not do anything from + a <code>"beforeChange"</code> handler that would cause changes + to the document or its visualization. Doing so will, since this + handler is called directly from the bowels of the CodeMirror + implementation, probably cause the editor to become + corrupted.</dd> + + <dt id="event_cursorActivity"><code><strong>"cursorActivity"</strong> (instance: CodeMirror)</code></dt> + <dd>Will be fired when the cursor or selection moves, or any + change is made to the editor content.</dd> + + <dt id="event_keyHandled"><code><strong>"keyHandled"</strong> (instance: CodeMirror, name: string, event: Event)</code></dt> + <dd>Fired after a key is handled through a + key map. <code>name</code> is the name of the handled key (for + example <code>"Ctrl-X"</code> or <code>"'q'"</code>), + and <code>event</code> is the DOM <code>keydown</code> + or <code>keypress</code> event.</dd> + + <dt id="event_inputRead"><code><strong>"inputRead"</strong> (instance: CodeMirror, changeObj: object)</code></dt> + <dd>Fired whenever new input is read from the hidden textarea + (typed or pasted by the user).</dd> + + <dt id="event_electricInput"><code><strong>"electricInput"</strong> (instance: CodeMirror, line: integer)</code></dt> + <dd>Fired if text input matched the + mode's <a href="#option_electricChars">electric</a> patterns, + and this caused the line's indentation to change.</dd> + + <dt id="event_beforeSelectionChange"><code><strong>"beforeSelectionChange"</strong> (instance: CodeMirror, obj: {ranges, origin, update})</code></dt> + <dd>This event is fired before the selection is moved. Its + handler may inspect the set of selection ranges, present as an + array of <code>{anchor, head}</code> objects in + the <code>ranges</code> property of the <code>obj</code> + argument, and optionally change them by calling + the <code>update</code> method on this object, passing an array + of ranges in the same format. The object also contains + an <code>origin</code> property holding the origin string passed + to the selection-changing method, if any. Handlers for this + event have the same restriction + as <a href="#event_beforeChange"><code>"beforeChange"</code></a> + handlers — they should not do anything to directly update the + state of the editor.</dd> + + <dt id="event_viewportChange"><code><strong>"viewportChange"</strong> (instance: CodeMirror, from: number, to: number)</code></dt> + <dd>Fires whenever the <a href="#getViewport">view port</a> of + the editor changes (due to scrolling, editing, or any other + factor). The <code>from</code> and <code>to</code> arguments + give the new start and end of the viewport.</dd> + + <dt id="event_swapDoc"><code><strong>"swapDoc"</strong> (instance: CodeMirror, oldDoc: Doc)</code></dt> + <dd>This is signalled when the editor's document is replaced + using the <a href="#swapDoc"><code>swapDoc</code></a> + method.</dd> + + <dt id="event_gutterClick"><code><strong>"gutterClick"</strong> (instance: CodeMirror, line: integer, gutter: string, clickEvent: Event)</code></dt> + <dd>Fires when the editor gutter (the line-number area) is + clicked. Will pass the editor instance as first argument, the + (zero-based) number of the line that was clicked as second + argument, the CSS class of the gutter that was clicked as third + argument, and the raw <code>mousedown</code> event object as + fourth argument.</dd> + + <dt id="event_gutterContextMenu"><code><strong>"gutterContextMenu"</strong> (instance: CodeMirror, line: integer, gutter: string, contextMenu: Event: Event)</code></dt> + <dd>Fires when the editor gutter (the line-number area) + receives a <code>contextmenu</code> event. Will pass the editor + instance as first argument, the (zero-based) number of the line + that was clicked as second argument, the CSS class of the + gutter that was clicked as third argument, and the raw + <code>contextmenu</code> mouse event object as fourth argument. + You can <code>preventDefault</code> the event, to signal that + CodeMirror should do no further handling.</dd> + + <dt id="event_focus"><code><strong>"focus"</strong> (instance: CodeMirror, event: Event)</code></dt> + <dd>Fires whenever the editor is focused.</dd> + + <dt id="event_blur"><code><strong>"blur"</strong> (instance: CodeMirror, event: Event)</code></dt> + <dd>Fires whenever the editor is unfocused.</dd> + + <dt id="event_scroll"><code><strong>"scroll"</strong> (instance: CodeMirror)</code></dt> + <dd>Fires when the editor is scrolled.</dd> + + <dt id="event_refresh"><code><strong>"refresh"</strong> (instance: CodeMirror)</code></dt> + <dd>Fires when the editor is <a href="#refresh">refreshed</a> + or <a href="#setSize">resized</a>. Mostly useful to invalidate + cached values that depend on the editor or character size.</dd> + + <dt id="event_optionChange"><code><strong>"optionChange"</strong> (instance: CodeMirror, option: string)</code></dt> + <dd>Dispatched every time an option is changed with <a href="#setOption"><code>setOption</code></a>.</dd> + + <dt id="event_scrollCursorIntoView"><code><strong>"scrollCursorIntoView"</strong> (instance: CodeMirror, event: Event)</code></dt> + <dd>Fires when the editor tries to scroll its cursor into view. + Can be hooked into to take care of additional scrollable + containers around the editor. When the event object has + its <code>preventDefault</code> method called, CodeMirror will + not itself try to scroll the window.</dd> + + <dt id="event_update"><code><strong>"update"</strong> (instance: CodeMirror)</code></dt> + <dd>Will be fired whenever CodeMirror updates its DOM display.</dd> + + <dt id="event_renderLine"><code><strong>"renderLine"</strong> (instance: CodeMirror, line: LineHandle, element: Element)</code></dt> + <dd>Fired whenever a line is (re-)rendered to the DOM. Fired + right after the DOM element is built, <em>before</em> it is + added to the document. The handler may mess with the style of + the resulting element, or add event handlers, but + should <em>not</em> try to change the state of the editor.</dd> + + <dt id="event_dom"><code><strong>"mousedown"</strong>, + <strong>"dblclick"</strong>, <strong>"touchstart"</strong>, <strong>"contextmenu"</strong>, + <strong>"keydown"</strong>, <strong>"keypress"</strong>, + <strong>"keyup"</strong>, <strong>"cut"</strong>, <strong>"copy"</strong>, <strong>"paste"</strong>, + <strong>"dragstart"</strong>, <strong>"dragenter"</strong>, + <strong>"dragover"</strong>, <strong>"dragleave"</strong>, + <strong>"drop"</strong> + (instance: CodeMirror, event: Event)</code></dt> + <dd>Fired when CodeMirror is handling a DOM event of this type. + You can <code>preventDefault</code> the event, or give it a + truthy <code>codemirrorIgnore</code> property, to signal that + CodeMirror should do no further handling.</dd> + </dl> + + <p>Document objects (instances + of <a href="#Doc"><code>CodeMirror.Doc</code></a>) emit the + following events:</p> + + <dl> + <dt id="event_doc_change"><code><strong>"change"</strong> (doc: CodeMirror.Doc, changeObj: object)</code></dt> + <dd>Fired whenever a change occurs to the + document. <code>changeObj</code> has a similar type as the + object passed to the + editor's <a href="#event_change"><code>"change"</code></a> + event.</dd> + + <dt id="event_doc_beforeChange"><code><strong>"beforeChange"</strong> (doc: CodeMirror.Doc, change: object)</code></dt> + <dd>See the <a href="#event_beforeChange">description of the + same event</a> on editor instances.</dd> + + <dt id="event_doc_cursorActivity"><code><strong>"cursorActivity"</strong> (doc: CodeMirror.Doc)</code></dt> + <dd>Fired whenever the cursor or selection in this document + changes.</dd> + + <dt id="event_doc_beforeSelectionChange"><code><strong>"beforeSelectionChange"</strong> (doc: CodeMirror.Doc, selection: {head, anchor})</code></dt> + <dd>Equivalent to + the <a href="#event_beforeSelectionChange">event by the same + name</a> as fired on editor instances.</dd> + </dl> + + <p>Line handles (as returned by, for + example, <a href="#getLineHandle"><code>getLineHandle</code></a>) + support these events:</p> + + <dl> + <dt id="event_delete"><code><strong>"delete"</strong> ()</code></dt> + <dd>Will be fired when the line object is deleted. A line object + is associated with the <em>start</em> of the line. Mostly useful + when you need to find out when your <a href="#setGutterMarker">gutter + markers</a> on a given line are removed.</dd> + <dt id="event_line_change"><code><strong>"change"</strong> (line: LineHandle, changeObj: object)</code></dt> + <dd>Fires when the line's text content is changed in any way + (but the line is not deleted outright). The <code>change</code> + object is similar to the one passed + to <a href="#event_change">change event</a> on the editor + object.</dd> + </dl> + + <p>Marked range handles (<code>CodeMirror.TextMarker</code>), as returned + by <a href="#markText"><code>markText</code></a> + and <a href="#setBookmark"><code>setBookmark</code></a>, emit the + following events:</p> + + <dl> + <dt id="event_beforeCursorEnter"><code><strong>"beforeCursorEnter"</strong> ()</code></dt> + <dd>Fired when the cursor enters the marked range. From this + event handler, the editor state may be inspected + but <em>not</em> modified, with the exception that the range on + which the event fires may be cleared.</dd> + <dt id="event_clear"><code><strong>"clear"</strong> (from: {line, ch}, to: {line, ch})</code></dt> + <dd>Fired when the range is cleared, either through cursor + movement in combination + with <a href="#mark_clearOnEnter"><code>clearOnEnter</code></a> + or through a call to its <code>clear()</code> method. Will only + be fired once per handle. Note that deleting the range through + text editing does not fire this event, because an undo action + might bring the range back into existence. <code>from</code> + and <code>to</code> give the part of the document that the range + spanned when it was cleared.</dd> + <dt id="event_hide"><code><strong>"hide"</strong> ()</code></dt> + <dd>Fired when the last part of the marker is removed from the + document by editing operations.</dd> + <dt id="event_unhide"><code><strong>"unhide"</strong> ()</code></dt> + <dd>Fired when, after the marker was removed by editing, a undo + operation brought the marker back.</dd> + </dl> + + <p>Line widgets (<code>CodeMirror.LineWidget</code>), returned + by <a href="#addLineWidget"><code>addLineWidget</code></a>, fire + these events:</p> + + <dl> + <dt id="event_redraw"><code><strong>"redraw"</strong> ()</code></dt> + <dd>Fired whenever the editor re-adds the widget to the DOM. + This will happen once right after the widget is added (if it is + scrolled into view), and then again whenever it is scrolled out + of view and back in again, or when changes to the editor options + or the line the widget is on require the widget to be + redrawn.</dd> + </dl> +</section> + +<section id=keymaps> + <h2>Key Maps</h2> + + <p>Key maps are ways to associate keys and mouse buttons with + functionality. A key map is an object mapping strings that + identify the buttons to functions that implement their + functionality.</p> + + <p>The CodeMirror distributions comes + with <a href="../demo/emacs.html">Emacs</a>, <a href="../demo/vim.html">Vim</a>, + and <a href="../demo/sublime.html">Sublime Text</a>-style keymaps.</p> + + <p>Keys are identified either by name or by character. + The <code>CodeMirror.keyNames</code> object defines names for + common keys and associates them with their key codes. Examples of + names defined here are <code>Enter</code>, <code>F5</code>, + and <code>Q</code>. These can be prefixed + with <code>Shift-</code>, <code>Cmd-</code>, <code>Ctrl-</code>, + and <code>Alt-</code> to specify a modifier. So for + example, <code>Shift-Ctrl-Space</code> would be a valid key + identifier.</p> + + <p>Common example: map the Tab key to insert spaces instead of a tab + character.</p> + + <pre data-lang="javascript"> +editor.setOption("extraKeys", { + Tab: function(cm) { + var spaces = Array(cm.getOption("indentUnit") + 1).join(" "); + cm.replaceSelection(spaces); + } +});</pre> + + <p>Alternatively, a character can be specified directly by + surrounding it in single quotes, for example <code>'$'</code> + or <code>'q'</code>. Due to limitations in the way browsers fire + key events, these may not be prefixed with modifiers.</p> + + <p>To bind mouse buttons, use the names `LeftClick`, + `MiddleClick`, and `RightClick`. These can also be prefixed with + modifiers, and in addition, the word `Double` or `Triple` can be + put before `Click` (as in `LeftDoubleClick`) to bind a double- or + triple-click. The function for such a binding is passed the + position that was clicked as second argument.</p> + + <p id="normalizeKeyMap">Multi-stroke key bindings can be specified + by separating the key names by spaces in the property name, for + example <code>Ctrl-X Ctrl-V</code>. When a map contains + multi-stoke bindings or keys with modifiers that are not specified + in the default order (<code>Shift-Cmd-Ctrl-Alt</code>), you must + call <code>CodeMirror.normalizeKeyMap</code> on it before it can + be used. This function takes a keymap and modifies it to normalize + modifier order and properly recognize multi-stroke bindings. It + will return the keymap itself.</p> + + <p>The <code>CodeMirror.keyMap</code> object associates key maps + with names. User code and key map definitions can assign extra + properties to this object. Anywhere where a key map is expected, a + string can be given, which will be looked up in this object. It + also contains the <code>"default"</code> key map holding the + default bindings.</p> + + <p>The values of properties in key maps can be either functions of + a single argument (the CodeMirror instance), strings, or + <code>false</code>. Strings refer + to <a href="#commands">commands</a>, which are described below. If + the property is set to <code>false</code>, CodeMirror leaves + handling of the key up to the browser. A key handler function may + return <code>CodeMirror.Pass</code> to indicate that it has + decided not to handle the key, and other handlers (or the default + behavior) should be given a turn.</p> + + <p>Keys mapped to command names that start with the + characters <code>"go"</code> or to functions that have a + truthy <code>motion</code> property (which should be used for + cursor-movement actions) will be fired even when an + extra <code>Shift</code> modifier is present (i.e. <code>"Up": + "goLineUp"</code> matches both up and shift-up). This is used to + easily implement shift-selection.</p> + + <p>Key maps can defer to each other by defining + a <code>fallthrough</code> property. This indicates that when a + key is not found in the map itself, one or more other maps should + be searched. It can hold either a single key map or an array of + key maps.</p> + + <p>When a key map needs to set something up when it becomes + active, or tear something down when deactivated, it can + contain <code>attach</code> and/or <code>detach</code> properties, + which should hold functions that take the editor instance and the + next or previous keymap. Note that this only works for the + <a href="#option_keyMap">top-level keymap</a>, not for fallthrough + maps or maps added + with <a href="#option_extraKeys"><code>extraKeys</code></a> + or <a href="#addKeyMap"><code>addKeyMap</code></a>.</p> +</section> + +<section id=commands> + <h2>Commands</h2> + + <p>Commands are parameter-less actions that can be performed on an + editor. Their main use is for key bindings. Commands are defined by + adding properties to the <code>CodeMirror.commands</code> object. + A number of common commands are defined by the library itself, + most of them used by the default key bindings. The value of a + command property must be a function of one argument (an editor + instance).</p> + + <p>Some of the commands below are referenced in the default + key map, but not defined by the core library. These are intended to + be defined by user code or addons.</p> + + <p>Commands can also be run with + the <a href="#execCommand"><code>execCommand</code></a> + method.</p> + + <dl> + <dt class=command id=command_selectAll><code><strong>selectAll</strong></code><span class=keybinding>Ctrl-A (PC), Cmd-A (Mac)</span></dt> + <dd>Select the whole content of the editor.</dd> + + <dt class=command id=command_singleSelection><code><strong>singleSelection</strong></code><span class=keybinding>Esc</span></dt> + <dd>When multiple selections are present, this deselects all but + the primary selection.</dd> + + <dt class=command id=command_killLine><code><strong>killLine</strong></code><span class=keybinding>Ctrl-K (Mac)</span></dt> + <dd>Emacs-style line killing. Deletes the part of the line after + the cursor. If that consists only of whitespace, the newline at + the end of the line is also deleted.</dd> + + <dt class=command id=command_deleteLine><code><strong>deleteLine</strong></code><span class=keybinding>Ctrl-D (PC), Cmd-D (Mac)</span></dt> + <dd>Deletes the whole line under the cursor, including newline at the end.</dd> + + <dt class=command id=command_delLineLeft><code><strong>delLineLeft</strong></code></dt> + <dd>Delete the part of the line before the cursor.</dd> + + <dt class=command id=command_delWrappedLineLeft><code><strong>delWrappedLineLeft</strong></code><span class=keybinding>Cmd-Backspace (Mac)</span></dt> + <dd>Delete the part of the line from the left side of the visual line the cursor is on to the cursor.</dd> + + <dt class=command id=command_delWrappedLineRight><code><strong>delWrappedLineRight</strong></code><span class=keybinding>Cmd-Delete (Mac)</span></dt> + <dd>Delete the part of the line from the cursor to the right side of the visual line the cursor is on.</dd> + + <dt class=command id=command_undo><code><strong>undo</strong></code><span class=keybinding>Ctrl-Z (PC), Cmd-Z (Mac)</span></dt> + <dd>Undo the last change. Note that, because browsers still + don't make it possible for scripts to react to or customize the + context menu, selecting undo (or redo) from the context menu in + a CodeMirror instance does not work.</dd> + + <dt class=command id=command_redo><code><strong>redo</strong></code><span class=keybinding>Ctrl-Y (PC), Shift-Cmd-Z (Mac), Cmd-Y (Mac)</span></dt> + <dd>Redo the last undone change.</dd> + + <dt class=command id=command_undoSelection><code><strong>undoSelection</strong></code><span class=keybinding>Ctrl-U (PC), Cmd-U (Mac)</span></dt> + <dd>Undo the last change to the selection, or if there are no + selection-only changes at the top of the history, undo the last + change.</dd> + + <dt class=command id=command_redoSelection><code><strong>redoSelection</strong></code><span class=keybinding>Alt-U (PC), Shift-Cmd-U (Mac)</span></dt> + <dd>Redo the last change to the selection, or the last text change if + no selection changes remain.</dd> + + <dt class=command id=command_goDocStart><code><strong>goDocStart</strong></code><span class=keybinding>Ctrl-Home (PC), Cmd-Up (Mac), Cmd-Home (Mac)</span></dt> + <dd>Move the cursor to the start of the document.</dd> + + <dt class=command id=command_goDocEnd><code><strong>goDocEnd</strong></code><span class=keybinding>Ctrl-End (PC), Cmd-End (Mac), Cmd-Down (Mac)</span></dt> + <dd>Move the cursor to the end of the document.</dd> + + <dt class=command id=command_goLineStart><code><strong>goLineStart</strong></code><span class=keybinding>Alt-Left (PC), Ctrl-A (Mac)</span></dt> + <dd>Move the cursor to the start of the line.</dd> + + <dt class=command id=command_goLineStartSmart><code><strong>goLineStartSmart</strong></code><span class=keybinding>Home</span></dt> + <dd>Move to the start of the text on the line, or if we are + already there, to the actual start of the line (including + whitespace).</dd> + + <dt class=command id=command_goLineEnd><code><strong>goLineEnd</strong></code><span class=keybinding>Alt-Right (PC), Ctrl-E (Mac)</span></dt> + <dd>Move the cursor to the end of the line.</dd> + + <dt class=command id=command_goLineRight><code><strong>goLineRight</strong></code><span class=keybinding>Cmd-Right (Mac)</span></dt> + <dd>Move the cursor to the right side of the visual line it is on.</dd> + + <dt class=command id=command_goLineLeft><code><strong>goLineLeft</strong></code><span class=keybinding>Cmd-Left (Mac)</span></dt> + <dd>Move the cursor to the left side of the visual line it is on. If + this line is wrapped, that may not be the start of the line.</dd> + + <dt class=command id=command_goLineLeftSmart><code><strong>goLineLeftSmart</strong></code></dt> + <dd>Move the cursor to the left side of the visual line it is + on. If that takes it to the start of the line, behave + like <a href="#command_goLineStartSmart"><code>goLineStartSmart</code></a>.</dd> + + <dt class=command id=command_goLineUp><code><strong>goLineUp</strong></code><span class=keybinding>Up, Ctrl-P (Mac)</span></dt> + <dd>Move the cursor up one line.</dd> + + <dt class=command id=command_goLineDown><code><strong>goLineDown</strong></code><span class=keybinding>Down, Ctrl-N (Mac)</span></dt> + <dd>Move down one line.</dd> + + <dt class=command id=command_goPageUp><code><strong>goPageUp</strong></code><span class=keybinding>PageUp, Shift-Ctrl-V (Mac)</span></dt> + <dd>Move the cursor up one screen, and scroll up by the same distance.</dd> + + <dt class=command id=command_goPageDown><code><strong>goPageDown</strong></code><span class=keybinding>PageDown, Ctrl-V (Mac)</span></dt> + <dd>Move the cursor down one screen, and scroll down by the same distance.</dd> + + <dt class=command id=command_goCharLeft><code><strong>goCharLeft</strong></code><span class=keybinding>Left, Ctrl-B (Mac)</span></dt> + <dd>Move the cursor one character left, going to the previous line + when hitting the start of line.</dd> + + <dt class=command id=command_goCharRight><code><strong>goCharRight</strong></code><span class=keybinding>Right, Ctrl-F (Mac)</span></dt> + <dd>Move the cursor one character right, going to the next line + when hitting the end of line.</dd> + + <dt class=command id=command_goColumnLeft><code><strong>goColumnLeft</strong></code></dt> + <dd>Move the cursor one character left, but don't cross line boundaries.</dd> + + <dt class=command id=command_goColumnRight><code><strong>goColumnRight</strong></code></dt> + <dd>Move the cursor one character right, don't cross line boundaries.</dd> + + <dt class=command id=command_goWordLeft><code><strong>goWordLeft</strong></code><span class=keybinding>Alt-B (Mac)</span></dt> + <dd>Move the cursor to the start of the previous word.</dd> + + <dt class=command id=command_goWordRight><code><strong>goWordRight</strong></code><span class=keybinding>Alt-F (Mac)</span></dt> + <dd>Move the cursor to the end of the next word.</dd> + + <dt class=command id=command_goGroupLeft><code><strong>goGroupLeft</strong></code><span class=keybinding>Ctrl-Left (PC), Alt-Left (Mac)</span></dt> + <dd>Move to the left of the group before the cursor. A group is + a stretch of word characters, a stretch of punctuation + characters, a newline, or a stretch of <em>more than one</em> + whitespace character.</dd> + + <dt class=command id=command_goGroupRight><code><strong>goGroupRight</strong></code><span class=keybinding>Ctrl-Right (PC), Alt-Right (Mac)</span></dt> + <dd>Move to the right of the group after the cursor + (see <a href="#command_goGroupLeft">above</a>).</dd> + + <dt class=command id=command_delCharBefore><code><strong>delCharBefore</strong></code><span class=keybinding>Shift-Backspace, Ctrl-H (Mac)</span></dt> + <dd>Delete the character before the cursor.</dd> + + <dt class=command id=command_delCharAfter><code><strong>delCharAfter</strong></code><span class=keybinding>Delete, Ctrl-D (Mac)</span></dt> + <dd>Delete the character after the cursor.</dd> + + <dt class=command id=command_delWordBefore><code><strong>delWordBefore</strong></code><span class=keybinding>Alt-Backspace (Mac)</span></dt> + <dd>Delete up to the start of the word before the cursor.</dd> + + <dt class=command id=command_delWordAfter><code><strong>delWordAfter</strong></code><span class=keybinding>Alt-D (Mac)</span></dt> + <dd>Delete up to the end of the word after the cursor.</dd> + + <dt class=command id=command_delGroupBefore><code><strong>delGroupBefore</strong></code><span class=keybinding>Ctrl-Backspace (PC), Alt-Backspace (Mac)</span></dt> + <dd>Delete to the left of the <a href="#command_goGroupLeft">group</a> before the cursor.</dd> + + <dt class=command id=command_delGroupAfter><code><strong>delGroupAfter</strong></code><span class=keybinding>Ctrl-Delete (PC), Ctrl-Alt-Backspace (Mac), Alt-Delete (Mac)</span></dt> + <dd>Delete to the start of the <a href="#command_goGroupLeft">group</a> after the cursor.</dd> + + <dt class=command id=command_indentAuto><code><strong>indentAuto</strong></code><span class=keybinding>Shift-Tab</span></dt> + <dd>Auto-indent the current line or selection.</dd> + + <dt class=command id=command_indentMore><code><strong>indentMore</strong></code><span class=keybinding>Ctrl-] (PC), Cmd-] (Mac)</span></dt> + <dd>Indent the current line or selection by one <a href="#option_indentUnit">indent unit</a>.</dd> + + <dt class=command id=command_indentLess><code><strong>indentLess</strong></code><span class=keybinding>Ctrl-[ (PC), Cmd-[ (Mac)</span></dt> + <dd>Dedent the current line or selection by one <a href="#option_indentUnit">indent unit</a>.</dd> + + <dt class=command id=command_insertTab><code><strong>insertTab</strong></code></dt> + <dd>Insert a tab character at the cursor.</dd> + + <dt class=command id=command_insertSoftTab><code><strong>insertSoftTab</strong></code></dt> + <dd>Insert the amount of spaces that match the width a tab at + the cursor position would have.</dd> + + <dt class=command id=command_defaultTab><code><strong>defaultTab</strong></code><span class=keybinding>Tab</span></dt> + <dd>If something is selected, indent it by + one <a href="#option_indentUnit">indent unit</a>. If nothing is + selected, insert a tab character.</dd> + + <dt class=command id=command_transposeChars><code><strong>transposeChars</strong></code><span class=keybinding>Ctrl-T (Mac)</span></dt> + <dd>Swap the characters before and after the cursor.</dd> + + <dt class=command id=command_newlineAndIndent><code><strong>newlineAndIndent</strong></code><span class=keybinding>Enter</span></dt> + <dd>Insert a newline and auto-indent the new line.</dd> + + <dt class=command id=command_toggleOverwrite><code><strong>toggleOverwrite</strong></code><span class=keybinding>Insert</span></dt> + <dd>Flip the <a href="#toggleOverwrite">overwrite</a> flag.</dd> + + <dt class=command id=command_save><code><strong>save</strong></code><span class=keybinding>Ctrl-S (PC), Cmd-S (Mac)</span></dt> + <dd>Not defined by the core library, only referred to in + key maps. Intended to provide an easy way for user code to define + a save command.</dd> + + <dt class=command id=command_find><code><strong>find</strong></code><span class=keybinding>Ctrl-F (PC), Cmd-F (Mac)</span></dt> + <dt class=command id=command_findNext><code><strong>findNext</strong></code><span class=keybinding>Ctrl-G (PC), Cmd-G (Mac)</span></dt> + <dt class=command id=command_findPrev><code><strong>findPrev</strong></code><span class=keybinding>Shift-Ctrl-G (PC), Shift-Cmd-G (Mac)</span></dt> + <dt class=command id=command_replace><code><strong>replace</strong></code><span class=keybinding>Shift-Ctrl-F (PC), Cmd-Alt-F (Mac)</span></dt> + <dt class=command id=command_replaceAll><code><strong>replaceAll</strong></code><span class=keybinding>Shift-Ctrl-R (PC), Shift-Cmd-Alt-F (Mac)</span></dt> + <dd>Not defined by the core library, but defined in + the <a href="#addon_search">search addon</a> (or custom client + addons).</dd> + + </dl> + +</section> + +<section id=styling> + <h2>Customized Styling</h2> + + <p>Up to a certain extent, CodeMirror's look can be changed by + modifying style sheet files. The style sheets supplied by modes + simply provide the colors for that mode, and can be adapted in a + very straightforward way. To style the editor itself, it is + possible to alter or override the styles defined + in <a href="../lib/codemirror.css"><code>codemirror.css</code></a>.</p> + + <p>Some care must be taken there, since a lot of the rules in this + file are necessary to have CodeMirror function properly. Adjusting + colors should be safe, of course, and with some care a lot of + other things can be changed as well. The CSS classes defined in + this file serve the following roles:</p> + + <dl> + <dt id="class_CodeMirror"><code><strong>CodeMirror</strong></code></dt> + <dd>The outer element of the editor. This should be used for the + editor width, height, borders and positioning. Can also be used + to set styles that should hold for everything inside the editor + (such as font and font size), or to set a background. Setting + this class' <code>height</code> style to <code>auto</code> will + make the editor <a href="../demo/resize.html">resize to fit its + content</a> (it is recommended to also set + the <a href="#option_viewportMargin"><code>viewportMargin</code> + option</a> to <code>Infinity</code> when doing this.</dd> + + <dt id="class_CodeMirror_focused"><code><strong>CodeMirror-focused</strong></code></dt> + <dd>Whenever the editor is focused, the top element gets this + class. This is used to hide the cursor and give the selection a + different color when the editor is not focused.</dd> + + <dt id="class_CodeMirror_gutters"><code><strong>CodeMirror-gutters</strong></code></dt> + <dd>This is the backdrop for all gutters. Use it to set the + default gutter background color, and optionally add a border on + the right of the gutters.</dd> + + <dt id="class_CodeMirror_linenumbers"><code><strong>CodeMirror-linenumbers</strong></code></dt> + <dd>Use this for giving a background or width to the line number + gutter.</dd> + + <dt id="class_CodeMirror_linenumber"><code><strong>CodeMirror-linenumber</strong></code></dt> + <dd>Used to style the actual individual line numbers. These + won't be children of the <code>CodeMirror-linenumbers</code> + (plural) element, but rather will be absolutely positioned to + overlay it. Use this to set alignment and text properties for + the line numbers.</dd> + + <dt id="class_CodeMirror_lines"><code><strong>CodeMirror-lines</strong></code></dt> + <dd>The visible lines. This is where you specify vertical + padding for the editor content.</dd> + + <dt id="class_CodeMirror_cursor"><code><strong>CodeMirror-cursor</strong></code></dt> + <dd>The cursor is a block element that is absolutely positioned. + You can make it look whichever way you want.</dd> + + <dt id="class_CodeMirror_selected"><code><strong>CodeMirror-selected</strong></code></dt> + <dd>The selection is represented by <code>span</code> elements + with this class.</dd> + + <dt id="class_CodeMirror_matchingbracket"><code><strong>CodeMirror-matchingbracket</strong></code>, + <code><strong>CodeMirror-nonmatchingbracket</strong></code></dt> + <dd>These are used to style matched (or unmatched) brackets.</dd> + </dl> + + <p>If your page's style sheets do funky things to + all <code>div</code> or <code>pre</code> elements (you probably + shouldn't do that), you'll have to define rules to cancel these + effects out again for elements under the <code>CodeMirror</code> + class.</p> + + <p>Themes are also simply CSS files, which define colors for + various syntactic elements. See the files in + the <a href="../theme/"><code>theme</code></a> directory.</p> +</section> + +<section id=api> + <h2>Programming API</h2> + + <p>A lot of CodeMirror features are only available through its + API. Thus, you need to write code (or + use <a href="#addons">addons</a>) if you want to expose them to + your users.</p> + + <p>Whenever points in the document are represented, the API uses + objects with <code>line</code> and <code>ch</code> properties. + Both are zero-based. CodeMirror makes sure to 'clip' any positions + passed by client code so that they fit inside the document, so you + shouldn't worry too much about sanitizing your coordinates. If you + give <code>ch</code> a value of <code>null</code>, or don't + specify it, it will be replaced with the length of the specified + line. Such positions may also have a <code>sticky</code> property + holding <code>"before"</code> or <code>"after"</code>, whether the + position is associated with the character before or after it. This + influences, for example, where the cursor is drawn on a + line-break or bidi-direction boundary.</p> + + <p>Methods prefixed with <code>doc.</code> can, unless otherwise + specified, be called both on <code>CodeMirror</code> (editor) + instances and <code>CodeMirror.Doc</code> instances. Methods + prefixed with <code>cm.</code> are <em>only</em> available + on <code>CodeMirror</code> instances.</p> + + <h3 id="api_constructor">Constructor</h3> + + <p id="CodeMirror">Constructing an editor instance is done with + the <code><strong>CodeMirror</strong>(place: Element|fn(Element), + ?option: object)</code> constructor. If the <code>place</code> + argument is a DOM element, the editor will be appended to it. If + it is a function, it will be called, and is expected to place the + editor into the document. <code>options</code> may be an element + mapping <a href="#config">option names</a> to values. The options + that it doesn't explicitly specify (or all options, if it is not + passed) will be taken + from <a href="#defaults"><code>CodeMirror.defaults</code></a>.</p> + + <p>Note that the options object passed to the constructor will be + mutated when the instance's options + are <a href="#setOption">changed</a>, so you shouldn't share such + objects between instances.</p> + + <p>See <a href="#fromTextArea"><code>CodeMirror.fromTextArea</code></a> + for another way to construct an editor instance.</p> + + <h3 id="api_content">Content manipulation methods</h3> + + <dl> + <dt id="getValue"><code><strong>doc.getValue</strong>(?separator: string) → string</code></dt> + <dd>Get the current editor content. You can pass it an optional + argument to specify the string to be used to separate lines + (defaults to <code>"\n"</code>).</dd> + <dt id="setValue"><code><strong>doc.setValue</strong>(content: string)</code></dt> + <dd>Set the editor content.</dd> + + <dt id="getRange"><code><strong>doc.getRange</strong>(from: {line, ch}, to: {line, ch}, ?separator: string) → string</code></dt> + <dd>Get the text between the given points in the editor, which + should be <code>{line, ch}</code> objects. An optional third + argument can be given to indicate the line separator string to + use (defaults to <code>"\n"</code>).</dd> + <dt id="replaceRange"><code><strong>doc.replaceRange</strong>(replacement: string, from: {line, ch}, to: {line, ch}, ?origin: string)</code></dt> + <dd>Replace the part of the document between <code>from</code> + and <code>to</code> with the given string. <code>from</code> + and <code>to</code> must be <code>{line, ch}</code> + objects. <code>to</code> can be left off to simply insert the + string at position <code>from</code>. When <code>origin</code> + is given, it will be passed on + to <a href="#event_change"><code>"change"</code> events</a>, and + its first letter will be used to determine whether this change + can be merged with previous history events, in the way described + for <a href="#selection_origin">selection origins</a>.</dd> + + <dt id="getLine"><code><strong>doc.getLine</strong>(n: integer) → string</code></dt> + <dd>Get the content of line <code>n</code>.</dd> + + <dt id="lineCount"><code><strong>doc.lineCount</strong>() → integer</code></dt> + <dd>Get the number of lines in the editor.</dd> + <dt id="firstLine"><code><strong>doc.firstLine</strong>() → integer</code></dt> + <dd>Get the first line of the editor. This will + usually be zero but for <a href="#linkedDoc_from">linked sub-views</a>, + or <a href="#api_doc">documents</a> instantiated with a non-zero + first line, it might return other values.</dd> + <dt id="lastLine"><code><strong>doc.lastLine</strong>() → integer</code></dt> + <dd>Get the last line of the editor. This will + usually be <code>doc.lineCount() - 1</code>, + but for <a href="#linkedDoc_from">linked sub-views</a>, + it might return other values.</dd> + + <dt id="getLineHandle"><code><strong>doc.getLineHandle</strong>(num: integer) → LineHandle</code></dt> + <dd>Fetches the line handle for the given line number.</dd> + <dt id="getLineNumber"><code><strong>doc.getLineNumber</strong>(handle: LineHandle) → integer</code></dt> + <dd>Given a line handle, returns the current position of that + line (or <code>null</code> when it is no longer in the + document).</dd> + <dt id="eachLine"><code><strong>doc.eachLine</strong>(f: (line: LineHandle))</code></dt> + <dt><code><strong>doc.eachLine</strong>(start: integer, end: integer, f: (line: LineHandle))</code></dt> + <dd>Iterate over the whole document, or if <code>start</code> + and <code>end</code> line numbers are given, the range + from <code>start</code> up to (not including) <code>end</code>, + and call <code>f</code> for each line, passing the line handle. + This is a faster way to visit a range of line handlers than + calling <a href="#getLineHandle"><code>getLineHandle</code></a> + for each of them. Note that line handles have + a <code>text</code> property containing the line's content (as a + string).</dd> + + <dt id="markClean"><code><strong>doc.markClean</strong>()</code></dt> + <dd>Set the editor content as 'clean', a flag that it will + retain until it is edited, and which will be set again when such + an edit is undone again. Useful to track whether the content + needs to be saved. This function is deprecated in favor + of <a href="#changeGeneration"><code>changeGeneration</code></a>, + which allows multiple subsystems to track different notions of + cleanness without interfering.</dd> + <dt id="changeGeneration"><code><strong>doc.changeGeneration</strong>(?closeEvent: boolean) → integer</code></dt> + <dd>Returns a number that can later be passed + to <a href="#isClean"><code>isClean</code></a> to test whether + any edits were made (and not undone) in the meantime. + If <code>closeEvent</code> is true, the current history event + will be ‘closed’, meaning it can't be combined with further + changes (rapid typing or deleting events are typically + combined).</dd> + <dt id="isClean"><code><strong>doc.isClean</strong>(?generation: integer) → boolean</code></dt> + <dd>Returns whether the document is currently clean — not + modified since initialization or the last call + to <a href="#markClean"><code>markClean</code></a> if no + argument is passed, or since the matching call + to <a href="#changeGeneration"><code>changeGeneration</code></a> + if a generation value is given.</dd> + </dl> + + <h3 id="api_selection">Cursor and selection methods</h3> + + <dl> + <dt id="getSelection"><code><strong>doc.getSelection</strong>(?lineSep: string) → string</code></dt> + <dd>Get the currently selected code. Optionally pass a line + separator to put between the lines in the output. When multiple + selections are present, they are concatenated with instances + of <code>lineSep</code> in between.</dd> + <dt id="getSelections"><code><strong>doc.getSelections</strong>(?lineSep: string) → array&lt;string&gt;</code></dt> + <dd>Returns an array containing a string for each selection, + representing the content of the selections.</dd> + + <dt id="replaceSelection"><code><strong>doc.replaceSelection</strong>(replacement: string, ?select: string)</code></dt> + <dd>Replace the selection(s) with the given string. By default, + the new selection ends up after the inserted text. The + optional <code>select</code> argument can be used to change + this—passing <code>"around"</code> will cause the new text to be + selected, passing <code>"start"</code> will collapse the + selection to the start of the inserted text.</dd> + <dt id="replaceSelections"><code><strong>doc.replaceSelections</strong>(replacements: array&lt;string&gt;, ?select: string)</code></dt> + <dd>The length of the given array should be the same as the + number of active selections. Replaces the content of the + selections with the strings in the array. + The <code>select</code> argument works the same as + in <a href="#replaceSelection"><code>replaceSelection</code></a>.</dd> + + <dt id="getCursor"><code><strong>doc.getCursor</strong>(?start: string) → {line, ch}</code></dt> + <dd>Retrieve one end of the <em>primary</em> + selection. <code>start</code> is an optional string indicating + which end of the selection to return. It may + be <code>"from"</code>, <code>"to"</code>, <code>"head"</code> + (the side of the selection that moves when you press + shift+arrow), or <code>"anchor"</code> (the fixed side of the + selection). Omitting the argument is the same as + passing <code>"head"</code>. A <code>{line, ch}</code> object + will be returned.</dd> + <dt id="listSelections"><code><strong>doc.listSelections</strong>() → array&lt;{anchor, head}&gt;</code></dt> + <dd>Retrieves a list of all current selections. These will + always be sorted, and never overlap (overlapping selections are + merged). Each object in the array contains <code>anchor</code> + and <code>head</code> properties referring to <code>{line, + ch}</code> objects.</dd> + + <dt id="somethingSelected"><code><strong>doc.somethingSelected</strong>() → boolean</code></dt> + <dd>Return true if any text is selected.</dd> + <dt id="setCursor"><code><strong>doc.setCursor</strong>(pos: {line, ch}|number, ?ch: number, ?options: object)</code></dt> + <dd>Set the cursor position. You can either pass a + single <code>{line, ch}</code> object, or the line and the + character as two separate parameters. Will replace all + selections with a single, empty selection at the given position. + The supported options are the same as for <a href="#setSelection"><code>setSelection</code></a>.</dd> + + <dt id="setSelection"><code><strong>doc.setSelection</strong>(anchor: {line, ch}, ?head: {line, ch}, ?options: object)</code></dt> + <dd>Set a single selection range. <code>anchor</code> + and <code>head</code> should be <code>{line, ch}</code> + objects. <code>head</code> defaults to <code>anchor</code> when + not given. These options are supported: + <dl> + <dt id="selection_scroll"><code><strong>scroll</strong>: boolean</code></dt> + <dd>Determines whether the selection head should be scrolled + into view. Defaults to true.</dd> + <dt id="selection_origin"><code><strong>origin</strong>: string</code></dt> + <dd>Determines whether the selection history event may be + merged with the previous one. When an origin starts with the + character <code>+</code>, and the last recorded selection had + the same origin and was similar (close + in <a href="#option_historyEventDelay">time</a>, both + collapsed or both non-collapsed), the new one will replace the + old one. When it starts with <code>*</code>, it will always + replace the previous event (if that had the same origin). + Built-in motion uses the <code>"+move"</code> origin. User input uses the <code>"+input"</code> origin.</dd> + <dt id="selection_bias"><code><strong>bias</strong>: number</code></dt> + <dd>Determine the direction into which the selection endpoints + should be adjusted when they fall inside + an <a href="#mark_atomic">atomic</a> range. Can be either -1 + (backward) or 1 (forward). When not given, the bias will be + based on the relative position of the old selection—the editor + will try to move further away from that, to prevent getting + stuck.</dd> + </dl></dd> + + <dt id="setSelections"><code><strong>doc.setSelections</strong>(ranges: array&lt;{anchor, head}&gt;, ?primary: integer, ?options: object)</code></dt> + <dd>Sets a new set of selections. There must be at least one + selection in the given array. When <code>primary</code> is a + number, it determines which selection is the primary one. When + it is not given, the primary index is taken from the previous + selection, or set to the last range if the previous selection + had less ranges than the new one. Supports the same options + as <a href="#setSelection"><code>setSelection</code></a>.</dd> + <dt id="addSelection"><code><strong>doc.addSelection</strong>(anchor: {line, ch}, ?head: {line, ch})</code></dt> + <dd>Adds a new selection to the existing set of selections, and + makes it the primary selection.</dd> + + <dt id="extendSelection"><code><strong>doc.extendSelection</strong>(from: {line, ch}, ?to: {line, ch}, ?options: object)</code></dt> + <dd>Similar + to <a href="#setSelection"><code>setSelection</code></a>, but + will, if shift is held or + the <a href="#setExtending">extending</a> flag is set, move the + head of the selection while leaving the anchor at its current + place. <code>to</code> is optional, and can be passed to ensure + a region (for example a word or paragraph) will end up selected + (in addition to whatever lies between that region and the + current anchor). When multiple selections are present, all but + the primary selection will be dropped by this method. + Supports the same options as <a href="#setSelection"><code>setSelection</code></a>.</dd> + <dt id="extendSelections"><code><strong>doc.extendSelections</strong>(heads: array&lt;{line, ch}&gt;, ?options: object)</code></dt> + <dd>An equivalent + of <a href="#extendSelection"><code>extendSelection</code></a> + that acts on all selections at once.</dd> + <dt id="extendSelectionsBy"><code><strong>doc.extendSelectionsBy</strong>(f: function(range: {anchor, head}) → {line, ch}), ?options: object)</code></dt> + <dd>Applies the given function to all existing selections, and + calls <a href="#extendSelections"><code>extendSelections</code></a> + on the result.</dd> + <dt id="setExtending"><code><strong>doc.setExtending</strong>(value: boolean)</code></dt> + <dd>Sets or clears the 'extending' flag, which acts similar to + the shift key, in that it will cause cursor movement and calls + to <a href="#extendSelection"><code>extendSelection</code></a> + to leave the selection anchor in place.</dd> + <dt id="getExtending"><code><strong>doc.getExtending</strong>() → boolean</code></dt> + <dd>Get the value of the 'extending' flag.</dd> + + <dt id="hasFocus"><code><strong>cm.hasFocus</strong>() → boolean</code></dt> + <dd>Tells you whether the editor currently has focus.</dd> + + <dt id="findPosH"><code><strong>cm.findPosH</strong>(start: {line, ch}, amount: integer, unit: string, visually: boolean) → {line, ch, ?hitSide: boolean}</code></dt> + <dd>Used to find the target position for horizontal cursor + motion. <code>start</code> is a <code>{line, ch}</code> + object, <code>amount</code> an integer (may be negative), + and <code>unit</code> one of the + string <code>"char"</code>, <code>"column"</code>, + or <code>"word"</code>. Will return a position that is produced + by moving <code>amount</code> times the distance specified + by <code>unit</code>. When <code>visually</code> is true, motion + in right-to-left text will be visual rather than logical. When + the motion was clipped by hitting the end or start of the + document, the returned value will have a <code>hitSide</code> + property set to true.</dd> + <dt id="findPosV"><code><strong>cm.findPosV</strong>(start: {line, ch}, amount: integer, unit: string) → {line, ch, ?hitSide: boolean}</code></dt> + <dd>Similar to <a href="#findPosH"><code>findPosH</code></a>, + but used for vertical motion. <code>unit</code> may + be <code>"line"</code> or <code>"page"</code>. The other + arguments and the returned value have the same interpretation as + they have in <code>findPosH</code>.</dd> + + <dt id="findWordAt"><code><strong>cm.findWordAt</strong>(pos: {line, ch}) → {anchor: {line, ch}, head: {line, ch}}</code></dt> + <dd>Returns the start and end of the 'word' (the stretch of + letters, whitespace, or punctuation) at the given position.</dd> + </dl> + + <h3 id="api_configuration">Configuration methods</h3> + + <dl> + <dt id="setOption"><code><strong>cm.setOption</strong>(option: string, value: any)</code></dt> + <dd>Change the configuration of the editor. <code>option</code> + should the name of an <a href="#config">option</a>, + and <code>value</code> should be a valid value for that + option.</dd> + <dt id="getOption"><code><strong>cm.getOption</strong>(option: string) → any</code></dt> + <dd>Retrieves the current value of the given option for this + editor instance.</dd> + + <dt id="addKeyMap"><code><strong>cm.addKeyMap</strong>(map: object, bottom: boolean)</code></dt> + <dd>Attach an additional <a href="#keymaps">key map</a> to the + editor. This is mostly useful for addons that need to register + some key handlers without trampling on + the <a href="#option_extraKeys"><code>extraKeys</code></a> + option. Maps added in this way have a higher precedence than + the <code>extraKeys</code> + and <a href="#option_keyMap"><code>keyMap</code></a> options, + and between them, the maps added earlier have a lower precedence + than those added later, unless the <code>bottom</code> argument + was passed, in which case they end up below other key maps added + with this method.</dd> + <dt id="removeKeyMap"><code><strong>cm.removeKeyMap</strong>(map: object)</code></dt> + <dd>Disable a keymap added + with <a href="#addKeyMap"><code>addKeyMap</code></a>. Either + pass in the key map object itself, or a string, which will be + compared against the <code>name</code> property of the active + key maps.</dd> + + <dt id="addOverlay"><code><strong>cm.addOverlay</strong>(mode: string|object, ?options: object)</code></dt> + <dd>Enable a highlighting overlay. This is a stateless mini-mode + that can be used to add extra highlighting. For example, + the <a href="../demo/search.html">search addon</a> uses it to + highlight the term that's currently being + searched. <code>mode</code> can be a <a href="#option_mode">mode + spec</a> or a mode object (an object with + a <a href="#token"><code>token</code></a> method). + The <code>options</code> parameter is optional. If given, it + should be an object, optionally containing the following options: + <dl> + <dt><code><strong>opaque</strong>: bool</code></dt> + <dd>Defaults to off, but can be given to allow the overlay + styling, when not <code>null</code>, to override the styling of + the base mode entirely, instead of the two being applied + together.</dd> + <dt><code><strong>priority</strong>: number</code></dt> + <dd>Determines the ordering in which the overlays are + applied. Those with high priority are applied after those + with lower priority, and able to override the opaqueness of + the ones that come before. Defaults to 0.</dd> + </dl> + </dd> + + <dt id="removeOverlay"><code><strong>cm.removeOverlay</strong>(mode: string|object)</code></dt> + <dd>Pass this the exact value passed for the <code>mode</code> + parameter to <a href="#addOverlay"><code>addOverlay</code></a>, + or a string that corresponds to the <code>name</code> property of + that value, to remove an overlay again.</dd> + + <dt id="on"><code><strong>cm.on</strong>(type: string, func: (...args))</code></dt> + <dd>Register an event handler for the given event type (a + string) on the editor instance. There is also + a <code>CodeMirror.on(object, type, func)</code> version + that allows registering of events on any object.</dd> + <dt id="off"><code><strong>cm.off</strong>(type: string, func: (...args))</code></dt> + <dd>Remove an event handler on the editor instance. An + equivalent <code>CodeMirror.off(object, type, + func)</code> also exists.</dd> + </dl> + + <h3 id="api_doc">Document management methods</h3> + + <p id="Doc">Each editor is associated with an instance + of <code>CodeMirror.Doc</code>, its document. A document + represents the editor content, plus a selection, an undo history, + and a <a href="#option_mode">mode</a>. A document can only be + associated with a single editor at a time. You can create new + documents by calling the <code>CodeMirror.Doc(text, mode, + firstLineNumber)</code> constructor. The last two arguments are + optional and can be used to set a mode for the document and make + it start at a line number other than 0, respectively.</p> + + <dl> + <dt id="getDoc"><code><strong>cm.getDoc</strong>() → Doc</code></dt> + <dd>Retrieve the currently active document from an editor.</dd> + <dt id="getEditor"><code><strong>doc.getEditor</strong>() → CodeMirror</code></dt> + <dd>Retrieve the editor associated with a document. May + return <code>null</code>.</dd> + + <dt id="swapDoc"><code><strong>cm.swapDoc</strong>(doc: CodeMirror.Doc) → Doc</code></dt> + <dd>Attach a new document to the editor. Returns the old + document, which is now no longer associated with an editor.</dd> + + <dt id="copy"><code><strong>doc.copy</strong>(copyHistory: boolean) → Doc</code></dt> + <dd>Create an identical copy of the given doc. + When <code>copyHistory</code> is true, the history will also be + copied. Can not be called directly on an editor.</dd> + + <dt id="linkedDoc"><code><strong>doc.linkedDoc</strong>(options: object) → Doc</code></dt> + <dd>Create a new document that's linked to the target document. + Linked documents will stay in sync (changes to one are also + applied to the other) until <a href="#unlinkDoc">unlinked</a>. + These are the options that are supported: + <dl> + <dt id="linkedDoc_sharedHist"><code><strong>sharedHist</strong>: boolean</code></dt> + <dd>When turned on, the linked copy will share an undo + history with the original. Thus, something done in one of + the two can be undone in the other, and vice versa.</dd> + <dt id="linkedDoc_from"><code><strong>from</strong>: integer</code></dt> + <dt id="linkedDoc_to"><code><strong>to</strong>: integer</code></dt> + <dd>Can be given to make the new document a subview of the + original. Subviews only show a given range of lines. Note + that line coordinates inside the subview will be consistent + with those of the parent, so that for example a subview + starting at line 10 will refer to its first line as line 10, + not 0.</dd> + <dt id="linkedDoc_mode"><code><strong>mode</strong>: string|object</code></dt> + <dd>By default, the new document inherits the mode of the + parent. This option can be set to + a <a href="#option_mode">mode spec</a> to give it a + different mode.</dd> + </dl></dd> + <dt id="unlinkDoc"><code><strong>doc.unlinkDoc</strong>(doc: CodeMirror.Doc)</code></dt> + <dd>Break the link between two documents. After calling this, + changes will no longer propagate between the documents, and, if + they had a shared history, the history will become + separate.</dd> + <dt id="iterLinkedDocs"><code><strong>doc.iterLinkedDocs</strong>(function: (doc: CodeMirror.Doc, sharedHist: boolean))</code></dt> + <dd>Will call the given function for all documents linked to the + target document. It will be passed two arguments, the linked document + and a boolean indicating whether that document shares history + with the target.</dd> + </dl> + + <h3 id="api_history">History-related methods</h3> + + <dl> + <dt id="undo"><code><strong>doc.undo</strong>()</code></dt> + <dd>Undo one edit (if any undo events are stored).</dd> + <dt id="redo"><code><strong>doc.redo</strong>()</code></dt> + <dd>Redo one undone edit.</dd> + + <dt id="undoSelection"><code><strong>doc.undoSelection</strong>()</code></dt> + <dd>Undo one edit or selection change.</dd> + <dt id="redoSelection"><code><strong>doc.redoSelection</strong>()</code></dt> + <dd>Redo one undone edit or selection change.</dd> + + <dt id="historySize"><code><strong>doc.historySize</strong>() → {undo: integer, redo: integer}</code></dt> + <dd>Returns an object with <code>{undo, redo}</code> properties, + both of which hold integers, indicating the amount of stored + undo and redo operations.</dd> + <dt id="clearHistory"><code><strong>doc.clearHistory</strong>()</code></dt> + <dd>Clears the editor's undo history.</dd> + <dt id="getHistory"><code><strong>doc.getHistory</strong>() → object</code></dt> + <dd>Get a (JSON-serializable) representation of the undo history.</dd> + <dt id="setHistory"><code><strong>doc.setHistory</strong>(history: object)</code></dt> + <dd>Replace the editor's undo history with the one provided, + which must be a value as returned + by <a href="#getHistory"><code>getHistory</code></a>. Note that + this will have entirely undefined results if the editor content + isn't also the same as it was when <code>getHistory</code> was + called.</dd> + </dl> + + <h3 id="api_marker">Text-marking methods</h3> + + <dl> + <dt id="markText"><code><strong>doc.markText</strong>(from: {line, ch}, to: {line, ch}, ?options: object) → TextMarker</code></dt> + <dd>Can be used to mark a range of text with a specific CSS + class name. <code>from</code> and <code>to</code> should + be <code>{line, ch}</code> objects. The <code>options</code> + parameter is optional. When given, it should be an object that + may contain the following configuration options: + <dl> + <dt id="mark_className"><code><strong>className</strong>: string</code></dt> + <dd>Assigns a CSS class to the marked stretch of text.</dd> + <dt id="mark_inclusiveLeft"><code><strong>inclusiveLeft</strong>: boolean</code></dt> + <dd>Determines whether + text inserted on the left of the marker will end up inside + or outside of it.</dd> + <dt id="mark_inclusiveRight"><code><strong>inclusiveRight</strong>: boolean</code></dt> + <dd>Like <code>inclusiveLeft</code>, + but for the right side.</dd> + <dt id="mark_atomic"><code><strong>atomic</strong>: boolean</code></dt> + <dd>Atomic ranges act as a single unit when cursor movement is + concerned—i.e. it is impossible to place the cursor inside of + them. In atomic ranges, <code>inclusiveLeft</code> + and <code>inclusiveRight</code> have a different meaning—they + will prevent the cursor from being placed respectively + directly before and directly after the range.</dd> + <dt id="mark_collapsed"><code><strong>collapsed</strong>: boolean</code></dt> + <dd>Collapsed ranges do not show up in the display. Setting a + range to be collapsed will automatically make it atomic.</dd> + <dt id="mark_clearOnEnter"><code><strong>clearOnEnter</strong>: boolean</code></dt> + <dd>When enabled, will cause the mark to clear itself whenever + the cursor enters its range. This is mostly useful for + text-replacement widgets that need to 'snap open' when the + user tries to edit them. The + <a href="#event_clear"><code>"clear"</code></a> event + fired on the range handle can be used to be notified when this + happens.</dd> + <dt id="mark_clearWhenEmpty"><code><strong>clearWhenEmpty</strong>: boolean</code></dt> + <dd>Determines whether the mark is automatically cleared when + it becomes empty. Default is true.</dd> + <dt id="mark_replacedWith"><code><strong>replacedWith</strong>: Element</code></dt> + <dd>Use a given node to display this range. Implies both + collapsed and atomic. The given DOM node <em>must</em> be an + inline element (as opposed to a block element).</dd> + <dt><code><strong>handleMouseEvents</strong>: boolean</code></dt> + <dd>When <code>replacedWith</code> is given, this determines + whether the editor will capture mouse and drag events + occurring in this widget. Default is false—the events will be + left alone for the default browser handler, or specific + handlers on the widget, to capture.</dd> + <dt id="mark_readOnly"><code><strong>readOnly</strong>: boolean</code></dt> + <dd>A read-only span can, as long as it is not cleared, not be + modified except by + calling <a href="#setValue"><code>setValue</code></a> to reset + the whole document. <em>Note:</em> adding a read-only span + currently clears the undo history of the editor, because + existing undo events being partially nullified by read-only + spans would corrupt the history (in the current + implementation).</dd> + <dt id="mark_addToHistory"><code><strong>addToHistory</strong>: boolean</code></dt> + <dd>When set to true (default is false), adding this marker + will create an event in the undo history that can be + individually undone (clearing the marker).</dd> + <dt id="mark_startStyle"><code><strong>startStyle</strong>: string</code></dt><dd>Can be used to specify + an extra CSS class to be applied to the leftmost span that + is part of the marker.</dd> + <dt id="mark_endStyle"><code><strong>endStyle</strong>: string</code></dt><dd>Equivalent + to <code>startStyle</code>, but for the rightmost span.</dd> + <dt id="mark_css"><code><strong>css</strong>: string</code></dt> + <dd>A string of CSS to be applied to the covered text. For example <code>"color: #fe3"</code>.</dd> + <dt id="mark_title"><code><strong>title</strong>: + string</code></dt><dd>When given, will give the nodes created + for this span a HTML <code>title</code> attribute with the + given value.</dd> + <dt id="mark_shared"><code><strong>shared</strong>: boolean</code></dt><dd>When the + target document is <a href="#linkedDoc">linked</a> to other + documents, you can set <code>shared</code> to true to make the + marker appear in all documents. By default, a marker appears + only in its target document.</dd> + </dl> + The method will return an object that represents the marker + (with constructor <code>CodeMirror.TextMarker</code>), which + exposes three methods: + <code><strong>clear</strong>()</code>, to remove the mark, + <code><strong>find</strong>()</code>, which returns + a <code>{from, to}</code> object (both holding document + positions), indicating the current position of the marked range, + or <code>undefined</code> if the marker is no longer in the + document, and finally <code><strong>changed</strong>()</code>, + which you can call if you've done something that might change + the size of the marker (for example changing the content of + a <a href="#mark_replacedWith"><code>replacedWith</code></a> + node), and want to cheaply update the display.</dd> + + <dt id="setBookmark"><code><strong>doc.setBookmark</strong>(pos: {line, ch}, ?options: object) → TextMarker</code></dt> + <dd>Inserts a bookmark, a handle that follows the text around it + as it is being edited, at the given position. A bookmark has two + methods <code>find()</code> and <code>clear()</code>. The first + returns the current position of the bookmark, if it is still in + the document, and the second explicitly removes the bookmark. + The options argument is optional. If given, the following + properties are recognized: + <dl> + <dt><code><strong>widget</strong>: Element</code></dt><dd>Can be used to display a DOM + node at the current location of the bookmark (analogous to + the <a href="#mark_replacedWith"><code>replacedWith</code></a> + option to <a href="#markText"><code>markText</code></a>).</dd> + <dt><code><strong>insertLeft</strong>: boolean</code></dt><dd>By default, text typed + when the cursor is on top of the bookmark will end up to the + right of the bookmark. Set this option to true to make it go + to the left instead.</dd> + <dt><code><strong>shared</strong>: boolean</code></dt><dd>See + the corresponding <a href="#mark_shared">option</a> + to <code>markText</code>.</dd> + <dt><code><strong>handleMouseEvents</strong>: boolean</code></dt> + <dd>As with <a href="#markText"><code>markText</code></a>, + this determines whether mouse events on the widget inserted + for this bookmark are handled by CodeMirror. The default is + false.</dd> + </dl></dd> + + <dt id="findMarks"><code><strong>doc.findMarks</strong>(from: {line, ch}, to: {line, ch}) → array&lt;TextMarker&gt;</code></dt> + <dd>Returns an array of all the bookmarks and marked ranges + found between the given positions (non-inclusive).</dd> + <dt id="findMarksAt"><code><strong>doc.findMarksAt</strong>(pos: {line, ch}) → array&lt;TextMarker&gt;</code></dt> + <dd>Returns an array of all the bookmarks and marked ranges + present at the given position.</dd> + <dt id="getAllMarks"><code><strong>doc.getAllMarks</strong>() → array&lt;TextMarker&gt;</code></dt> + <dd>Returns an array containing all marked ranges in the document.</dd> + </dl> + + <h3 id="api_decoration">Widget, gutter, and decoration methods</h3> + + <dl> + <dt id="setGutterMarker"><code><strong>doc.setGutterMarker</strong>(line: integer|LineHandle, gutterID: string, value: Element) → LineHandle</code></dt> + <dd>Sets the gutter marker for the given gutter (identified by + its CSS class, see + the <a href="#option_gutters"><code>gutters</code></a> option) + to the given value. Value can be either <code>null</code>, to + clear the marker, or a DOM element, to set it. The DOM element + will be shown in the specified gutter next to the specified + line.</dd> + + <dt id="clearGutter"><code><strong>doc.clearGutter</strong>(gutterID: string)</code></dt> + <dd>Remove all gutter markers in + the <a href="#option_gutters">gutter</a> with the given ID.</dd> + + <dt id="addLineClass"><code><strong>doc.addLineClass</strong>(line: integer|LineHandle, where: string, class: string) → LineHandle</code></dt> + <dd>Set a CSS class name for the given line. <code>line</code> + can be a number or a line handle. <code>where</code> determines + to which element this class should be applied, can can be one + of <code>"text"</code> (the text element, which lies in front of + the selection), <code>"background"</code> (a background element + that will be behind the selection), <code>"gutter"</code> (the + line's gutter space), or <code>"wrap"</code> (the wrapper node + that wraps all of the line's elements, including gutter + elements). <code>class</code> should be the name of the class to + apply.</dd> + + <dt id="removeLineClass"><code><strong>doc.removeLineClass</strong>(line: integer|LineHandle, where: string, class: string) → LineHandle</code></dt> + <dd>Remove a CSS class from a line. <code>line</code> can be a + line handle or number. <code>where</code> should be one + of <code>"text"</code>, <code>"background"</code>, + or <code>"wrap"</code> + (see <a href="#addLineClass"><code>addLineClass</code></a>). <code>class</code> + can be left off to remove all classes for the specified node, or + be a string to remove only a specific class.</dd> + + <dt id="lineInfo"><code><strong>doc.lineInfo</strong>(line: integer|LineHandle) → object</code></dt> + <dd>Returns the line number, text content, and marker status of + the given line, which can be either a number or a line handle. + The returned object has the structure <code>{line, handle, text, + gutterMarkers, textClass, bgClass, wrapClass, widgets}</code>, + where <code>gutterMarkers</code> is an object mapping gutter IDs + to marker elements, and <code>widgets</code> is an array + of <a href="#addLineWidget">line widgets</a> attached to this + line, and the various class properties refer to classes added + with <a href="#addLineClass"><code>addLineClass</code></a>.</dd> + + <dt id="addWidget"><code><strong>cm.addWidget</strong>(pos: {line, ch}, node: Element, scrollIntoView: boolean)</code></dt> + <dd>Puts <code>node</code>, which should be an absolutely + positioned DOM node, into the editor, positioned right below the + given <code>{line, ch}</code> position. + When <code>scrollIntoView</code> is true, the editor will ensure + that the entire node is visible (if possible). To remove the + widget again, simply use DOM methods (move it somewhere else, or + call <code>removeChild</code> on its parent).</dd> + + <dt id="addLineWidget"><code><strong>doc.addLineWidget</strong>(line: integer|LineHandle, node: Element, ?options: object) → LineWidget</code></dt> + <dd>Adds a line widget, an element shown below a line, spanning + the whole of the editor's width, and moving the lines below it + downwards. <code>line</code> should be either an integer or a + line handle, and <code>node</code> should be a DOM node, which + will be displayed below the given line. <code>options</code>, + when given, should be an object that configures the behavior of + the widget. The following options are supported (all default to + false): + <dl> + <dt><code><strong>coverGutter</strong>: boolean</code></dt> + <dd>Whether the widget should cover the gutter.</dd> + <dt><code><strong>noHScroll</strong>: boolean</code></dt> + <dd>Whether the widget should stay fixed in the face of + horizontal scrolling.</dd> + <dt><code><strong>above</strong>: boolean</code></dt> + <dd>Causes the widget to be placed above instead of below + the text of the line.</dd> + <dt><code><strong>handleMouseEvents</strong>: boolean</code></dt> + <dd>Determines whether the editor will capture mouse and + drag events occurring in this widget. Default is false—the + events will be left alone for the default browser handler, + or specific handlers on the widget, to capture.</dd> + <dt><code><strong>insertAt</strong>: integer</code></dt> + <dd>By default, the widget is added below other widgets for + the line. This option can be used to place it at a different + position (zero for the top, N to put it after the Nth other + widget). Note that this only has effect once, when the + widget is created. + </dl> + Note that the widget node will become a descendant of nodes with + CodeMirror-specific CSS classes, and those classes might in some + cases affect it. This method returns an object that represents + the widget placement. It'll have a <code>line</code> property + pointing at the line handle that it is associated with, and the following methods: + <dl> + <dt id="widget_clear"><code><strong>clear</strong>()</code></dt><dd>Removes the widget.</dd> + <dt id="widget_changed"><code><strong>changed</strong>()</code></dt><dd>Call + this if you made some change to the widget's DOM node that + might affect its height. It'll force CodeMirror to update + the height of the line that contains the widget.</dd> + </dl> + </dd> + </dl> + + <h3 id="api_sizing">Sizing, scrolling and positioning methods</h3> + + <dl> + <dt id="setSize"><code><strong>cm.setSize</strong>(width: number|string, height: number|string)</code></dt> + <dd>Programmatically set the size of the editor (overriding the + applicable <a href="#css-resize">CSS + rules</a>). <code>width</code> and <code>height</code> + can be either numbers (interpreted as pixels) or CSS units + (<code>"100%"</code>, for example). You can + pass <code>null</code> for either of them to indicate that that + dimension should not be changed.</dd> + + <dt id="scrollTo"><code><strong>cm.scrollTo</strong>(x: number, y: number)</code></dt> + <dd>Scroll the editor to a given (pixel) position. Both + arguments may be left as <code>null</code> + or <code>undefined</code> to have no effect.</dd> + <dt id="getScrollInfo"><code><strong>cm.getScrollInfo</strong>() → {left, top, width, height, clientWidth, clientHeight}</code></dt> + <dd>Get an <code>{left, top, width, height, clientWidth, + clientHeight}</code> object that represents the current scroll + position, the size of the scrollable area, and the size of the + visible area (minus scrollbars).</dd> + <dt id="scrollIntoView"><code><strong>cm.scrollIntoView</strong>(what: {line, ch}|{left, top, right, bottom}|{from, to}|null, ?margin: number)</code></dt> + <dd>Scrolls the given position into view. <code>what</code> may + be <code>null</code> to scroll the cursor into view, + a <code>{line, ch}</code> position to scroll a character into + view, a <code>{left, top, right, bottom}</code> pixel range (in + editor-local coordinates), or a range <code>{from, to}</code> + containing either two character positions or two pixel squares. + The <code>margin</code> parameter is optional. When given, it + indicates the amount of vertical pixels around the given area + that should be made visible as well.</dd> + + <dt id="cursorCoords"><code><strong>cm.cursorCoords</strong>(where: boolean|{line, ch}, mode: string) → {left, top, bottom}</code></dt> + <dd>Returns an <code>{left, top, bottom}</code> object + containing the coordinates of the cursor position. + If <code>mode</code> is <code>"local"</code>, they will be + relative to the top-left corner of the editable document. If it + is <code>"page"</code> or not given, they are relative to the + top-left corner of the page. If <code>mode</code> + is <code>"window"</code>, the coordinates are relative to the + top-left corner of the currently visible (scrolled) + window. <code>where</code> can be a boolean indicating whether + you want the start (<code>true</code>) or the end + (<code>false</code>) of the selection, or, if a <code>{line, + ch}</code> object is given, it specifies the precise position at + which you want to measure.</dd> + <dt id="charCoords"><code><strong>cm.charCoords</strong>(pos: {line, ch}, ?mode: string) → {left, right, top, bottom}</code></dt> + <dd>Returns the position and dimensions of an arbitrary + character. <code>pos</code> should be a <code>{line, ch}</code> + object. This differs from <code>cursorCoords</code> in that + it'll give the size of the whole character, rather than just the + position that the cursor would have when it would sit at that + position.</dd> + <dt id="coordsChar"><code><strong>cm.coordsChar</strong>(object: {left, top}, ?mode: string) → {line, ch}</code></dt> + <dd>Given an <code>{left, top}</code> object (e.g. coordinates of a mouse event) returns + the <code>{line, ch}</code> position that corresponds to it. The + optional <code>mode</code> parameter determines relative to what + the coordinates are interpreted. It may + be <code>"window"</code>, <code>"page"</code> (the default), + or <code>"local"</code>.</dd> + <dt id="lineAtHeight"><code><strong>cm.lineAtHeight</strong>(height: number, ?mode: string) → number</code></dt> + <dd>Computes the line at the given pixel + height. <code>mode</code> can be one of the same strings + that <a href="#coordsChar"><code>coordsChar</code></a> + accepts.</dd> + <dt id="heightAtLine"><code><strong>cm.heightAtLine</strong>(line: integer|LineHandle, ?mode: string, ?includeWidgets: bool) → number</code></dt> + <dd>Computes the height of the top of a line, in the coordinate + system specified by <code>mode</code> + (see <a href="#coordsChar"><code>coordsChar</code></a>), which + defaults to <code>"page"</code>. When a line below the bottom of + the document is specified, the returned value is the bottom of + the last line in the document. By default, the position of the + actual text is returned. If `includeWidgets` is true and the + line has line widgets, the position above the first line widget + is returned.</dd> + <dt id="defaultTextHeight"><code><strong>cm.defaultTextHeight</strong>() → number</code></dt> + <dd>Returns the line height of the default font for the editor.</dd> + <dt id="defaultCharWidth"><code><strong>cm.defaultCharWidth</strong>() → number</code></dt> + <dd>Returns the pixel width of an 'x' in the default font for + the editor. (Note that for non-monospace fonts, this is mostly + useless, and even for monospace fonts, non-ascii characters + might have a different width).</dd> + + <dt id="getViewport"><code><strong>cm.getViewport</strong>() → {from: number, to: number}</code></dt> + <dd>Returns a <code>{from, to}</code> object indicating the + start (inclusive) and end (exclusive) of the currently rendered + part of the document. In big documents, when most content is + scrolled out of view, CodeMirror will only render the visible + part, and a margin around it. See also + the <a href="#event_viewportChange"><code>viewportChange</code></a> + event.</dd> + + <dt id="refresh"><code><strong>cm.refresh</strong>()</code></dt> + <dd>If your code does something to change the size of the editor + element (window resizes are already listened for), or unhides + it, you should probably follow up by calling this method to + ensure CodeMirror is still looking as intended. See also + the <a href="#addon_autorefresh">autorefresh addon</a>.</dd> + </dl> + + <h3 id="api_mode">Mode, state, and token-related methods</h3> + + <p>When writing language-aware functionality, it can often be + useful to hook into the knowledge that the CodeMirror language + mode has. See <a href="#modeapi">the section on modes</a> for a + more detailed description of how these work.</p> + + <dl> + <dt id="getMode"><code><strong>doc.getMode</strong>() → object</code></dt> + <dd>Gets the (outer) mode object for the editor. Note that this + is distinct from <code>getOption("mode")</code>, which gives you + the mode specification, rather than the resolved, instantiated + <a href="#defineMode">mode object</a>.</dd> + + <dt id="getModeAt"><code><strong>cm.getModeAt</strong>(pos: {line, ch}) → object</code></dt> + <dd>Gets the inner mode at a given position. This will return + the same as <a href="#getMode"><code>getMode</code></a> for + simple modes, but will return an inner mode for nesting modes + (such as <code>htmlmixed</code>).</dd> + + <dt id="getTokenAt"><code><strong>cm.getTokenAt</strong>(pos: {line, ch}, ?precise: boolean) → object</code></dt> + <dd>Retrieves information about the token the current mode found + before the given position (a <code>{line, ch}</code> object). The + returned object has the following properties: + <dl> + <dt><code><strong>start</strong></code></dt><dd>The character (on the given line) at which the token starts.</dd> + <dt><code><strong>end</strong></code></dt><dd>The character at which the token ends.</dd> + <dt><code><strong>string</strong></code></dt><dd>The token's string.</dd> + <dt><code><strong>type</strong></code></dt><dd>The token type the mode assigned + to the token, such as <code>"keyword"</code> + or <code>"comment"</code> (may also be null).</dd> + <dt><code><strong>state</strong></code></dt><dd>The mode's state at the end of this token.</dd> + </dl> + If <code>precise</code> is true, the token will be guaranteed to be accurate based on recent edits. If false or + not specified, the token will use cached state information, which will be faster but might not be accurate if + edits were recently made and highlighting has not yet completed. + </dd> + + <dt id="getLineTokens"><code><strong>cm.getLineTokens</strong>(line: integer, ?precise: boolean) → array&lt;{start, end, string, type, state}&gt;</code></dt> + <dd>This is similar + to <a href="#getTokenAt"><code>getTokenAt</code></a>, but + collects all tokens for a given line into an array. It is much + cheaper than repeatedly calling <code>getTokenAt</code>, which + re-parses the part of the line before the token for every call.</dd> + + <dt id="getTokenTypeAt"><code><strong>cm.getTokenTypeAt</strong>(pos: {line, ch}) → string</code></dt> + <dd>This is a (much) cheaper version + of <a href="#getTokenAt"><code>getTokenAt</code></a> useful for + when you just need the type of the token at a given position, + and no other information. Will return <code>null</code> for + unstyled tokens, and a string, potentially containing multiple + space-separated style names, otherwise.</dd> + + <dt id="getHelpers"><code><strong>cm.getHelpers</strong>(pos: {line, ch}, type: string) → array&lt;helper&gt;</code></dt> + <dd>Fetch the set of applicable helper values for the given + position. Helpers provide a way to look up functionality + appropriate for a mode. The <code>type</code> argument provides + the helper namespace (see + <a href="#registerHelper"><code>registerHelper</code></a>), in + which the values will be looked up. When the mode itself has a + property that corresponds to the <code>type</code>, that + directly determines the keys that are used to look up the helper + values (it may be either a single string, or an array of + strings). Failing that, the mode's <code>helperType</code> + property and finally the mode's name are used.</dd> + <dd>For example, the JavaScript mode has a + property <code>fold</code> containing <code>"brace"</code>. When + the <code>brace-fold</code> addon is loaded, that defines a + helper named <code>brace</code> in the <code>fold</code> + namespace. This is then used by + the <a href="#addon_foldcode"><code>foldcode</code></a> addon to + figure out that it can use that folding function to fold + JavaScript code.</dd> + <dd>When any <a href="#registerGlobalHelper">'global'</a> + helpers are defined for the given namespace, their predicates + are called on the current mode and editor, and all those that + declare they are applicable will also be added to the array that + is returned.</dd> + + <dt id="getHelper"><code><strong>cm.getHelper</strong>(pos: {line, ch}, type: string) → helper</code></dt> + <dd>Returns the first applicable helper value. + See <a href="#getHelpers"><code>getHelpers</code></a>.</dd> + + <dt id="getStateAfter"><code><strong>cm.getStateAfter</strong>(?line: integer, ?precise: boolean) → object</code></dt> + <dd>Returns the mode's parser state, if any, at the end of the + given line number. If no line number is given, the state at the + end of the document is returned. This can be useful for storing + parsing errors in the state, or getting other kinds of + contextual information for a line. <code>precise</code> is defined + as in <code>getTokenAt()</code>.</dd> + </dl> + + <h3 id="api_misc">Miscellaneous methods</h3> + + <dl> + <dt id="operation"><code><strong>cm.operation</strong>(func: () → any) → any</code></dt> + <dd>CodeMirror internally buffers changes and only updates its + DOM structure after it has finished performing some operation. + If you need to perform a lot of operations on a CodeMirror + instance, you can call this method with a function argument. It + will call the function, buffering up all changes, and only doing + the expensive update after the function returns. This can be a + lot faster. The return value from this method will be the return + value of your function.</dd> + + <dt id="startOperation"><code><strong>cm.startOperation</strong>()</code></dt> + <dt id="endOperation"><code><strong>cm.endOperation</strong>()</code></dt> + <dd>In normal circumstances, use the above <code>operation</code> + method. But if you want to buffer operations happening asynchronously, + or that can't all be wrapped in a callback function, you can + call <code>startOperation</code> to tell CodeMirror to start + buffering changes, and <code>endOperation</code> to actually + render all the updates. <em>Be careful:</em> if you use this + API and forget to call <code>endOperation</code>, the editor will + just never update.</dd> + + <dt id="indentLine"><code><strong>cm.indentLine</strong>(line: integer, ?dir: string|integer)</code></dt> + <dd>Adjust the indentation of the given line. The second + argument (which defaults to <code>"smart"</code>) may be one of: + <dl> + <dt><code><strong>"prev"</strong></code></dt> + <dd>Base indentation on the indentation of the previous line.</dd> + <dt><code><strong>"smart"</strong></code></dt> + <dd>Use the mode's smart indentation if available, behave + like <code>"prev"</code> otherwise.</dd> + <dt><code><strong>"add"</strong></code></dt> + <dd>Increase the indentation of the line by + one <a href="#option_indentUnit">indent unit</a>.</dd> + <dt><code><strong>"subtract"</strong></code></dt> + <dd>Reduce the indentation of the line.</dd> + <dt><code><strong>&lt;integer></strong></code></dt> + <dd>Add (positive number) or reduce (negative number) the + indentation by the given amount of spaces.</dd> + </dl></dd> + + <dt id="toggleOverwrite"><code><strong>cm.toggleOverwrite</strong>(?value: boolean)</code></dt> + <dd>Switches between overwrite and normal insert mode (when not + given an argument), or sets the overwrite mode to a specific + state (when given an argument).</dd> + + <dt id="isReadOnly"><code><strong>cm.isReadOnly</strong>() → boolean</code></dt> + <dd>Tells you whether the editor's content can be edited by the + user.</dd> + + <dt id="lineSeparator"><code><strong>doc.lineSeparator</strong>()</code></dt> + <dd>Returns the preferred line separator string for this + document, as per the <a href="#option_lineSeparator">option</a> + by the same name. When that option is <code>null</code>, the + string <code>"\n"</code> is returned.</dd> + + <dt id="execCommand"><code><strong>cm.execCommand</strong>(name: string)</code></dt> + <dd>Runs the <a href="#commands">command</a> with the given name on the editor.</dd> + + <dt id="posFromIndex"><code><strong>doc.posFromIndex</strong>(index: integer) → {line, ch}</code></dt> + <dd>Calculates and returns a <code>{line, ch}</code> object for a + zero-based <code>index</code> who's value is relative to the start of the + editor's text. If the <code>index</code> is out of range of the text then + the returned object is clipped to start or end of the text + respectively.</dd> + <dt id="indexFromPos"><code><strong>doc.indexFromPos</strong>(object: {line, ch}) → integer</code></dt> + <dd>The reverse of <a href="#posFromIndex"><code>posFromIndex</code></a>.</dd> + + <dt id="focus"><code><strong>cm.focus</strong>()</code></dt> + <dd>Give the editor focus.</dd> + + <dt id="getInputField"><code><strong>cm.getInputField</strong>() → Element</code></dt> + <dd>Returns the input field for the editor. Will be a textarea + or an editable div, depending on the value of + the <a href="#option_inputStyle"><code>inputStyle</code></a> + option.</dd> + <dt id="getWrapperElement"><code><strong>cm.getWrapperElement</strong>() → Element</code></dt> + <dd>Returns the DOM node that represents the editor, and + controls its size. Remove this from your tree to delete an + editor instance.</dd> + <dt id="getScrollerElement"><code><strong>cm.getScrollerElement</strong>() → Element</code></dt> + <dd>Returns the DOM node that is responsible for the scrolling + of the editor.</dd> + <dt id="getGutterElement"><code><strong>cm.getGutterElement</strong>() → Element</code></dt> + <dd>Fetches the DOM node that contains the editor gutters.</dd> + </dl> + + <h3 id="api_static">Static properties</h3> + <p>The <code>CodeMirror</code> object itself provides + several useful properties.</p> + + <dl> + <dt id="version"><code><strong>CodeMirror.version</strong>: string</code></dt> + <dd>It contains a string that indicates the version of the + library. This is a triple of + integers <code>"major.minor.patch"</code>, + where <code>patch</code> is zero for releases, and something + else (usually one) for dev snapshots.</dd> + + <dt id="fromTextArea"><code><strong>CodeMirror.fromTextArea</strong>(textArea: TextAreaElement, ?config: object)</code></dt> + <dd>This method provides another way to initialize an editor. It + takes a textarea DOM node as first argument and an optional + configuration object as second. It will replace the textarea + with a CodeMirror instance, and wire up the form of that + textarea (if any) to make sure the editor contents are put into + the textarea when the form is submitted. The text in the + textarea will provide the content for the editor. A CodeMirror + instance created this way has three additional methods: + <dl> + <dt id="save"><code><strong>cm.save</strong>()</code></dt> + <dd>Copy the content of the editor into the textarea.</dd> + + <dt id="toTextArea"><code><strong>cm.toTextArea</strong>()</code></dt> + <dd>Remove the editor, and restore the original textarea (with + the editor's current content). If you dynamically create and + destroy editors made with `fromTextArea`, without destroying + the form they are part of, you should make sure to call + `toTextArea` to remove the editor, or its `"submit"` handler + on the form will cause a memory leak.</dd> + + <dt id="getTextArea"><code><strong>cm.getTextArea</strong>() → TextAreaElement</code></dt> + <dd>Returns the textarea that the instance was based on.</dd> + </dl> + </dd> + + <dt id="defaults"><code><strong>CodeMirror.defaults</strong>: object</code></dt> + <dd>An object containing default values for + all <a href="#config">options</a>. You can assign to its + properties to modify defaults (though this won't affect editors + that have already been created).</dd> + + <dt id="defineExtension"><code><strong>CodeMirror.defineExtension</strong>(name: string, value: any)</code></dt> + <dd>If you want to define extra methods in terms of the + CodeMirror API, it is possible to + use <code>defineExtension</code>. This will cause the given + value (usually a method) to be added to all CodeMirror instances + created from then on.</dd> + + <dt id="defineDocExtension"><code><strong>CodeMirror.defineDocExtension</strong>(name: string, value: any)</code></dt> + <dd>Like <a href="#defineExtension"><code>defineExtension</code></a>, + but the method will be added to the interface + for <a href="#Doc"><code>Doc</code></a> objects instead.</dd> + + <dt id="defineOption"><code><strong>CodeMirror.defineOption</strong>(name: string, + default: any, updateFunc: function)</code></dt> + <dd>Similarly, <code>defineOption</code> can be used to define new options for + CodeMirror. The <code>updateFunc</code> will be called with the + editor instance and the new value when an editor is initialized, + and whenever the option is modified + through <a href="#setOption"><code>setOption</code></a>.</dd> + + <dt id="defineInitHook"><code><strong>CodeMirror.defineInitHook</strong>(func: function)</code></dt> + <dd>If your extension just needs to run some + code whenever a CodeMirror instance is initialized, + use <code>CodeMirror.defineInitHook</code>. Give it a function as + its only argument, and from then on, that function will be called + (with the instance as argument) whenever a new CodeMirror instance + is initialized.</dd> + + <dt id="registerHelper"><code><strong>CodeMirror.registerHelper</strong>(type: string, name: string, value: helper)</code></dt> + <dd>Registers a helper value with the given <code>name</code> in + the given namespace (<code>type</code>). This is used to define + functionality that may be looked up by mode. Will create (if it + doesn't already exist) a property on the <code>CodeMirror</code> + object for the given <code>type</code>, pointing to an object + that maps names to values. I.e. after + doing <code>CodeMirror.registerHelper("hint", "foo", + myFoo)</code>, the value <code>CodeMirror.hint.foo</code> will + point to <code>myFoo</code>.</dd> + + <dt id="registerGlobalHelper"><code><strong>CodeMirror.registerGlobalHelper</strong>(type: string, name: string, predicate: fn(mode, CodeMirror), value: helper)</code></dt> + <dd>Acts + like <a href="#registerHelper"><code>registerHelper</code></a>, + but also registers this helper as 'global', meaning that it will + be included by <a href="#getHelpers"><code>getHelpers</code></a> + whenever the given <code>predicate</code> returns true when + called with the local mode and editor.</dd> + + <dt id="Pos"><code><strong>CodeMirror.Pos</strong>(line: integer, ?ch: integer, ?sticky: string)</code></dt> + <dd>A constructor for the objects that are used to represent + positions in editor documents. <code>sticky</code> defaults to + null, but can be set to <code>"before"</code> + or <code>"after"</code> to make the position explicitly + associate with the character before or after it.</dd> + + <dt id="changeEnd"><code><strong>CodeMirror.changeEnd</strong>(change: object) → {line, ch}</code></dt> + <dd>Utility function that computes an end position from a change + (an object with <code>from</code>, <code>to</code>, + and <code>text</code> properties, as passed to + various <a href="#event_change">event handlers</a>). The + returned position will be the end of the changed + range, <em>after</em> the change is applied.</dd> + + <dt id="countColumn"><code><strong>CodeMirror.countColumn</strong>(line: string, index: number, tabSize: number) → number</code></dt> + <dd>Find the column position at a given string index using a given tabsize.</dd> + </dl> +</section> + +<section id=addons> + <h2 id="addons">Addons</h2> + + <p>The <code>addon</code> directory in the distribution contains a + number of reusable components that implement extra editor + functionality (on top of extension functions + like <a href="#defineOption"><code>defineOption</code></a>, <a href="#defineExtension"><code>defineExtension</code></a>, + and <a href="#registerHelper"><code>registerHelper</code></a>). In + brief, they are:</p> + + <dl> + <dt id="addon_dialog"><a href="../addon/dialog/dialog.js"><code>dialog/dialog.js</code></a></dt> + <dd>Provides a very simple way to query users for text input. + Adds the <strong><code>openDialog(template, callback, options) → + closeFunction</code></strong> method to CodeMirror instances, + which can be called with an HTML fragment or a detached DOM + node that provides the prompt (should include an <code>input</code> + or <code>button</code> tag), and a callback function that is called + when the user presses enter. It returns a function <code>closeFunction</code> + which, if called, will close the dialog immediately. + <strong><code>openDialog</code></strong> takes the following options: + <dl> + <dt><code><strong>closeOnEnter</strong>: bool</code></dt> + <dd>If true, the dialog will be closed when the user presses + enter in the input. Defaults to <code>true</code>.</dd> + <dt><code><strong>closeOnBlur</strong>: bool</code></dt> + <dd>Determines whether the dialog is closed when it loses focus. Defaults to <code>true</code>.</dd> + <dt><code><strong>onKeyDown</strong>: fn(event: KeyboardEvent, value: string, close: fn()) → bool</code></dt> + <dd>An event handler that will be called whenever <code>keydown</code> fires in the + dialog's input. If your callback returns <code>true</code>, + the dialog will not do any further processing of the event.</dd> + <dt><code><strong>onKeyUp</strong>: fn(event: KeyboardEvent, value: string, close: fn()) → bool</code></dt> + <dd>Same as <code>onKeyDown</code> but for the + <code>keyup</code> event.</dd> + <dt><code><strong>onInput</strong>: fn(event: InputEvent, value: string, close: fn()) → bool</code></dt> + <dd>Same as <code>onKeyDown</code> but for the + <code>input</code> event.</dd> + <dt><code><strong>onClose</strong>: fn(instance)</code>:</dt> + <dd>A callback that will be called after the dialog has been closed and + removed from the DOM. No return value.</dd> + </dl> + + <p>Also adds an <strong><code>openNotification(template, options) → + closeFunction</code></strong> function that simply shows an HTML + fragment as a notification at the top of the editor. It takes a + single option: <code>duration</code>, the amount of time after + which the notification will be automatically closed. If <code> + duration</code> is zero, the dialog will not be closed automatically.</p> + + <p>Depends on <code>addon/dialog/dialog.css</code>.</p></dd> + + <dt id="addon_searchcursor"><a href="../addon/search/searchcursor.js"><code>search/searchcursor.js</code></a></dt> + <dd>Adds the <code>getSearchCursor(query, start, options) → + cursor</code> method to CodeMirror instances, which can be used + to implement search/replace functionality. <code>query</code> + can be a regular expression or a string. <code>start</code> + provides the starting position of the search. It can be + a <code>{line, ch}</code> object, or can be left off to default + to the start of the document. <code>options</code> is an + optional object, which can contain the property `caseFold: + false` to disable case folding when mathing a string, or the + property `multiline: disable` to disable multi-line matching for + regular expressions (which may help performance). A search + cursor has the following methods: + <dl> + <dt><code><strong>findNext</strong>() → boolean</code></dt> + <dt><code><strong>findPrevious</strong>() → boolean</code></dt> + <dd>Search forward or backward from the current position. + The return value indicates whether a match was found. If + matching a regular expression, the return value will be the + array returned by the <code>match</code> method, in case you + want to extract matched groups.</dd> + <dt><code><strong>from</strong>() → {line, ch}</code></dt> + <dt><code><strong>to</strong>() → {line, ch}</code></dt> + <dd>These are only valid when the last call + to <code>findNext</code> or <code>findPrevious</code> did + not return false. They will return <code>{line, ch}</code> + objects pointing at the start and end of the match.</dd> + <dt><code><strong>replace</strong>(text: string, ?origin: string)</code></dt> + <dd>Replaces the currently found match with the given text + and adjusts the cursor position to reflect the + replacement.</dd> + </dl></dd> + + <dt id="addon_search"><a href="../addon/search/search.js"><code>search/search.js</code></a></dt> + <dd>Implements the search commands. CodeMirror has keys bound to + these by default, but will not do anything with them unless an + implementation is provided. Depends + on <code>searchcursor.js</code>, and will make use + of <a href="#addon_dialog"><code>openDialog</code></a> when + available to make prompting for search queries less ugly.</dd> + + <dt id="addon_jump-to-line"><a href="../addon/search/jump-to-line.js"><code>search/jump-to-line.js</code></a></dt> + <dd>Implements a <code>jumpToLine</code> command and binding <code>Alt-G</code> to it. + Accepts <code>linenumber</code>, <code>+/-linenumber</code>, <code>line:char</code>, + <code>scroll%</code> and <code>:linenumber</code> formats. + This will make use of <a href="#addon_dialog"><code>openDialog</code></a> + when available to make prompting for line number neater.</dd> + + <dt id="addon_matchesonscrollbar"><a href="../addon/search/matchesonscrollbar.js"><code>search/matchesonscrollbar.js</code></a></dt> + <dd>Adds a <code>showMatchesOnScrollbar</code> method to editor + instances, which should be given a query (string or regular + expression), optionally a case-fold flag (only applicable for + strings), and optionally a class name (defaults + to <code>CodeMirror-search-match</code>) as arguments. When + called, matches of the given query will be displayed on the + editor's vertical scrollbar. The method returns an object with + a <code>clear</code> method that can be called to remove the + matches. Depends on + the <a href="#addon_annotatescrollbar"><code>annotatescrollbar</code></a> + addon, and + the <a href="../addon/search/matchesonscrollbar.css"><code>matchesonscrollbar.css</code></a> + file provides a default (transparent yellowish) definition of + the CSS class applied to the matches. Note that the matches are + only perfectly aligned if your scrollbar does not have buttons + at the top and bottom. You can use + the <a href="#addon_simplescrollbars"><code>simplescrollbar</code></a> + addon to make sure of this. If this addon is loaded, + the <a href="#addon_search"><code>search</code></a> addon will + automatically use it.</dd> + + <dt id="addon_matchbrackets"><a href="../addon/edit/matchbrackets.js"><code>edit/matchbrackets.js</code></a></dt> + <dd>Defines an option <code>matchBrackets</code> which, when set + to true or an options object, causes matching brackets to be + highlighted whenever the cursor is next to them. It also adds a + method <code>matchBrackets</code> that forces this to happen + once, and a method <code>findMatchingBracket</code> that can be + used to run the bracket-finding algorithm that this uses + internally. It takes a start position and an optional config + object. By default, it will find the match to a matchable + character either before or after the cursor (preferring the one + before), but you can control its behavior with these options: + <dl> + <dt><strong><code>afterCursor</code></strong></dt> + <dd>Only use the character after the start position, never the one before it.</dd> + <dt><strong><code>strict</code></strong></dt> + <dd>Causes only matches where both brackets are at the same side of the start position to be considered.</dd> + <dt><strong><code>maxScanLines</code></strong></dt> + <dd>Stop after scanning this amount of lines without a successful match. Defaults to 1000.</dd> + <dt><strong><code>maxScanLineLength</code></strong></dt> + <dd>Ignore lines longer than this. Defaults to 10000.</dd> + </dl></dd> + + <dt id="addon_closebrackets"><a href="../addon/edit/closebrackets.js"><code>edit/closebrackets.js</code></a></dt> + <dd>Defines an option <code>autoCloseBrackets</code> that will + auto-close brackets and quotes when typed. By default, it'll + auto-close <code>()[]{}''""</code>, but you can pass it a string + similar to that (containing pairs of matching characters), or an + object with <code>pairs</code> and + optionally <code>explode</code> properties to customize + it. <code>explode</code> should be a similar string that gives + the pairs of characters that, when enter is pressed between + them, should have the second character also moved to its own + line. By default, if the active mode has + a <code>closeBrackets</code> property, that overrides the + configuration given in the option. But you can add + an <code>override</code> property with a truthy value to + override mode-specific + configuration. <a href="../demo/closebrackets.html">Demo + here</a>.</dd> + + <dt id="addon_matchtags"><a href="../addon/edit/matchtags.js"><code>edit/matchtags.js</code></a></dt> + <dd>Defines an option <code>matchTags</code> that, when enabled, + will cause the tags around the cursor to be highlighted (using + the <code>CodeMirror-matchingtag</code> class). Also + defines + a <a href="#commands">command</a> <code>toMatchingTag</code>, + which you can bind a key to in order to jump to the tag matching + the one under the cursor. Depends on + the <code>addon/fold/xml-fold.js</code> + addon. <a href="../demo/matchtags.html">Demo here.</a></dd> + + <dt id="addon_trailingspace"><a href="../addon/edit/trailingspace.js"><code>edit/trailingspace.js</code></a></dt> + <dd>Adds an option <code>showTrailingSpace</code> which, when + enabled, adds the CSS class <code>cm-trailingspace</code> to + stretches of whitespace at the end of lines. + The <a href="../demo/trailingspace.html">demo</a> has a nice + squiggly underline style for this class.</dd> + + <dt id="addon_closetag"><a href="../addon/edit/closetag.js"><code>edit/closetag.js</code></a></dt> + <dd>Defines an <code>autoCloseTags</code> option that will + auto-close XML tags when '<code>&gt;</code>' or '<code>/</code>' + is typed, and + a <code>closeTag</code> <a href="#commands">command</a> that + closes the nearest open tag. Depends on + the <code>fold/xml-fold.js</code> addon. See + the <a href="../demo/closetag.html">demo</a>.</dd> + + <dt id="addon_continuelist"><a href="../addon/edit/continuelist.js"><code>edit/continuelist.js</code></a></dt> + <dd>Markdown specific. Defines + a <code>"newlineAndIndentContinueMarkdownList"</code> <a href="#commands">command</a> + that can be bound to <code>enter</code> to automatically + insert the leading characters for continuing a list. See + the <a href="../mode/markdown/index.html">Markdown mode + demo</a>.</dd> + + <dt id="addon_comment"><a href="../addon/comment/comment.js"><code>comment/comment.js</code></a></dt> + <dd>Addon for commenting and uncommenting code. Adds four + methods to CodeMirror instances: + <dl> + <dt id="toggleComment"><code><strong>toggleComment</strong>(from: {line, ch}, to: {line, ch}, ?options: object)</code></dt> + <dd>Tries to uncomment the current selection, and if that + fails, line-comments it.</dd> + <dt id="lineComment"><code><strong>lineComment</strong>(from: {line, ch}, to: {line, ch}, ?options: object)</code></dt> + <dd>Set the lines in the given range to be line comments. Will + fall back to <code>blockComment</code> when no line comment + style is defined for the mode.</dd> + <dt id="blockComment"><code><strong>blockComment</strong>(from: {line, ch}, to: {line, ch}, ?options: object)</code></dt> + <dd>Wrap the code in the given range in a block comment. Will + fall back to <code>lineComment</code> when no block comment + style is defined for the mode.</dd> + <dt id="uncomment"><code><strong>uncomment</strong>(from: {line, ch}, to: {line, ch}, ?options: object) → boolean</code></dt> + <dd>Try to uncomment the given range. + Returns <code>true</code> if a comment range was found and + removed, <code>false</code> otherwise.</dd> + </dl> + The <code>options</code> object accepted by these methods may + have the following properties: + <dl> + <dt><code>blockCommentStart, blockCommentEnd, blockCommentLead, lineComment: string</code></dt> + <dd>Override the <a href="#mode_comment">comment string + properties</a> of the mode with custom comment strings.</dd> + <dt><code><strong>padding</strong>: string</code></dt> + <dd>A string that will be inserted after opening and leading + markers, and before closing comment markers. Defaults to a + single space.</dd> + <dt><code><strong>commentBlankLines</strong>: boolean</code></dt> + <dd>Whether, when adding line comments, to also comment lines + that contain only whitespace.</dd> + <dt><code><strong>indent</strong>: boolean</code></dt> + <dd>When adding line comments and this is turned on, it will + align the comment block to the current indentation of the + first line of the block.</dd> + <dt><code><strong>fullLines</strong>: boolean</code></dt> + <dd>When block commenting, this controls whether the whole + lines are indented, or only the precise range that is given. + Defaults to <code>true</code>.</dd> + </dl> + The addon also defines + a <code>toggleComment</code> <a href="#commands">command</a>, + which is a shorthand command for calling + <code>toggleComment</code> with no options.</dd> + + <dt id="addon_foldcode"><a href="../addon/fold/foldcode.js"><code>fold/foldcode.js</code></a></dt> + <dd>Helps with code folding. Adds a <code>foldCode</code> method + to editor instances, which will try to do a code fold starting + at the given line, or unfold the fold that is already present. + The method takes as first argument the position that should be + folded (may be a line number or + a <a href="#Pos"><code>Pos</code></a>), and as second optional + argument either a range-finder function, or an options object, + supporting the following properties: + <dl> + <dt><code><strong>rangeFinder</strong>: fn(CodeMirror, Pos)</code></dt> + <dd id="helper_fold_auto">The function that is used to find + foldable ranges. If this is not directly passed, it will + default to <code>CodeMirror.fold.auto</code>, which + uses <a href="#getHelpers"><code>getHelpers</code></a> with + a <code>"fold"</code> type to find folding functions + appropriate for the local mode. There are files in + the <a href="../addon/fold/"><code>addon/fold/</code></a> + directory providing <code>CodeMirror.fold.brace</code>, which + finds blocks in brace languages (JavaScript, C, Java, + etc), <code>CodeMirror.fold.indent</code>, for languages where + indentation determines block structure (Python, Haskell), + and <code>CodeMirror.fold.xml</code>, for XML-style languages, + and <code>CodeMirror.fold.comment</code>, for folding comment + blocks.</dd> + <dt><code><strong>widget</strong>: string|Element</code></dt> + <dd>The widget to show for folded ranges. Can be either a + string, in which case it'll become a span with + class <code>CodeMirror-foldmarker</code>, or a DOM node.</dd> + <dt><code><strong>scanUp</strong>: boolean</code></dt> + <dd>When true (default is false), the addon will try to find + foldable ranges on the lines above the current one if there + isn't an eligible one on the given line.</dd> + <dt><code><strong>minFoldSize</strong>: integer</code></dt> + <dd>The minimum amount of lines that a fold should span to be + accepted. Defaults to 0, which also allows single-line + folds.</dd> + </dl> + See <a href="../demo/folding.html">the demo</a> for an + example.</dd> + + <dt id="addon_foldgutter"><a href="../addon/fold/foldgutter.js"><code>fold/foldgutter.js</code></a></dt> + <dd>Provides an option <code>foldGutter</code>, which can be + used to create a gutter with markers indicating the blocks that + can be folded. Create a gutter using + the <a href="#option_gutters"><code>gutters</code></a> option, + giving it the class <code>CodeMirror-foldgutter</code> or + something else if you configure the addon to use a different + class, and this addon will show markers next to folded and + foldable blocks, and handle clicks in this gutter. Note that + CSS styles should be applied to make the gutter, and the fold + markers within it, visible. A default set of CSS styles are + available in: + <a href="../addon/fold/foldgutter.css"> + <code>addon/fold/foldgutter.css</code> + </a>. + The option + can be either set to <code>true</code>, or an object containing + the following optional option fields: + <dl> + <dt><code><strong>gutter</strong>: string</code></dt> + <dd>The CSS class of the gutter. Defaults + to <code>"CodeMirror-foldgutter"</code>. You will have to + style this yourself to give it a width (and possibly a + background). See the default gutter style rules above.</dd> + <dt><code><strong>indicatorOpen</strong>: string | Element</code></dt> + <dd>A CSS class or DOM element to be used as the marker for + open, foldable blocks. Defaults + to <code>"CodeMirror-foldgutter-open"</code>.</dd> + <dt><code><strong>indicatorFolded</strong>: string | Element</code></dt> + <dd>A CSS class or DOM element to be used as the marker for + folded blocks. Defaults to <code>"CodeMirror-foldgutter-folded"</code>.</dd> + <dt><code><strong>rangeFinder</strong>: fn(CodeMirror, Pos)</code></dt> + <dd>The range-finder function to use when determining whether + something can be folded. When not + given, <a href="#helper_fold_auto"><code>CodeMirror.fold.auto</code></a> + will be used as default.</dd> + </dl> + The <code>foldOptions</code> editor option can be set to an + object to provide an editor-wide default configuration. + Demo <a href="../demo/folding.html">here</a>.</dd> + + <dt id="addon_runmode"><a href="../addon/runmode/runmode.js"><code>runmode/runmode.js</code></a></dt> + <dd>Can be used to run a CodeMirror mode over text without + actually opening an editor instance. + See <a href="../demo/runmode.html">the demo</a> for an example. + There are alternate versions of the file available for + running <a href="../addon/runmode/runmode-standalone.js">stand-alone</a> + (without including all of CodeMirror) and + for <a href="../addon/runmode/runmode.node.js">running under + node.js</a> (see <code>bin/source-highlight</code> for an example of using the latter).</dd> + + <dt id="addon_colorize"><a href="../addon/runmode/colorize.js"><code>runmode/colorize.js</code></a></dt> + <dd>Provides a convenient way to syntax-highlight code snippets + in a webpage. Depends on + the <a href="#addon_runmode"><code>runmode</code></a> addon (or + its standalone variant). Provides + a <code>CodeMirror.colorize</code> function that can be called + with an array (or other array-ish collection) of DOM nodes that + represent the code snippets. By default, it'll get + all <code>pre</code> tags. Will read the <code>data-lang</code> + attribute of these nodes to figure out their language, and + syntax-color their content using the relevant CodeMirror mode + (you'll have to load the scripts for the relevant modes + yourself). A second argument may be provided to give a default + mode, used when no language attribute is found for a node. Used + in this manual to highlight example code.</dd> + + <dt id="addon_overlay"><a href="../addon/mode/overlay.js"><code>mode/overlay.js</code></a></dt> + <dd>Mode combinator that can be used to extend a mode with an + 'overlay' — a secondary mode is run over the stream, along with + the base mode, and can color specific pieces of text without + interfering with the base mode. + Defines <code>CodeMirror.overlayMode</code>, which is used to + create such a mode. See <a href="../demo/mustache.html">this + demo</a> for a detailed example.</dd> + + <dt id="addon_multiplex"><a href="../addon/mode/multiplex.js"><code>mode/multiplex.js</code></a></dt> + <dd>Mode combinator that can be used to easily 'multiplex' + between several modes. + Defines <code>CodeMirror.multiplexingMode</code> which, when + given as first argument a mode object, and as other arguments + any number of <code>{open, close, mode [, delimStyle, innerStyle, parseDelimiters]}</code> + objects, will return a mode object that starts parsing using the + mode passed as first argument, but will switch to another mode + as soon as it encounters a string that occurs in one of + the <code>open</code> fields of the passed objects. When in a + sub-mode, it will go back to the top mode again when + the <code>close</code> string is encountered. + Pass <code>"\n"</code> for <code>open</code> or <code>close</code> + if you want to switch on a blank line. + <ul><li>When <code>delimStyle</code> is specified, it will be the token + style returned for the delimiter tokens (as well as + <code>[delimStyle]-open</code> on the opening token and + <code>[delimStyle]-close</code> on the closing token).</li> + <li>When <code>innerStyle</code> is specified, it will be the token + style added for each inner mode token.</li> + <li>When <code>parseDelimiters</code> is true, the content of + the delimiters will also be passed to the inner mode. + (And <code>delimStyle</code> is ignored.)</li></ul> The outer + mode will not see the content between the delimiters. + See <a href="../demo/multiplex.html">this demo</a> for an + example.</dd> + + <dt id="addon_show-hint"><a href="../addon/hint/show-hint.js"><code>hint/show-hint.js</code></a></dt> + <dd>Provides a framework for showing autocompletion hints. + Defines <code>editor.showHint</code>, which takes an optional + options object, and pops up a widget that allows the user to + select a completion. Finding hints is done with a hinting + functions (the <code>hint</code> option), which is a function + that take an editor instance and options object, and return + a <code>{list, from, to}</code> object, where <code>list</code> + is an array of strings or objects (the completions), + and <code>from</code> and <code>to</code> give the start and end + of the token that is being completed as <code>{line, ch}</code> + objects. An optional <code>selectedHint</code> property (an + integer) can be added to the completion object to control the + initially selected hint.</dd> + <dd>If no hinting function is given, the addon will + use <code>CodeMirror.hint.auto</code>, which + calls <a href="#getHelpers"><code>getHelpers</code></a> with + the <code>"hint"</code> type to find applicable hinting + functions, and tries them one by one. If that fails, it looks + for a <code>"hintWords"</code> helper to fetch a list of + completable words for the mode, and + uses <code>CodeMirror.hint.fromList</code> to complete from + those.</dd> + <dd>When completions aren't simple strings, they should be + objects with the following properties: + <dl> + <dt><code><strong>text</strong>: string</code></dt> + <dd>The completion text. This is the only required + property.</dd> + <dt><code><strong>displayText</strong>: string</code></dt> + <dd>The text that should be displayed in the menu.</dd> + <dt><code><strong>className</strong>: string</code></dt> + <dd>A CSS class name to apply to the completion's line in the + menu.</dd> + <dt><code><strong>render</strong>: fn(Element, self, data)</code></dt> + <dd>A method used to create the DOM structure for showing the + completion by appending it to its first argument.</dd> + <dt><code><strong>hint</strong>: fn(CodeMirror, self, data)</code></dt> + <dd>A method used to actually apply the completion, instead of + the default behavior.</dd> + <dt><code><strong>from</strong>: {line, ch}</code></dt> + <dd>Optional <code>from</code> position that will be used by <code>pick()</code> instead + of the global one passed with the full list of completions.</dd> + <dt><code><strong>to</strong>: {line, ch}</code></dt> + <dd>Optional <code>to</code> position that will be used by <code>pick()</code> instead + of the global one passed with the full list of completions.</dd> + </dl></dd> + + <dd>The plugin understands the following options, which may be + either passed directly in the argument to <code>showHint</code>, + or provided by setting an <code>hintOptions</code> editor + option to an object (the former takes precedence). The options + object will also be passed along to the hinting function, which + may understand additional options. + <dl> + <dt><code><strong>hint</strong>: function</code></dt> + <dd>A hinting function, as specified above. It is possible to + set the <code>async</code> property on a hinting function to + true, in which case it will be called with + arguments <code>(cm, callback, ?options)</code>, and the + completion interface will only be popped up when the hinting + function calls the callback, passing it the object holding the + completions. + The hinting function can also return a promise, and the completion + interface will only be popped when the promise resolves. + By default, hinting only works when there is no + selection. You can give a hinting function + a <code>supportsSelection</code> property with a truthy value + to indicate that it supports selections.</dd> + <dt><code><strong>completeSingle</strong>: boolean</code></dt> + <dd>Determines whether, when only a single completion is + available, it is completed without showing the dialog. + Defaults to true.</dd> + <dt><code><strong>alignWithWord</strong>: boolean</code></dt> + <dd>Whether the pop-up should be horizontally aligned with the + start of the word (true, default), or with the cursor (false).</dd> + <dt><code><strong>closeOnUnfocus</strong>: boolean</code></dt> + <dd>When enabled (which is the default), the pop-up will close + when the editor is unfocused.</dd> + <dt><code><strong>customKeys</strong>: keymap</code></dt> + <dd>Allows you to provide a custom key map of keys to be active + when the pop-up is active. The handlers will be called with an + extra argument, a handle to the completion menu, which + has <code>moveFocus(n)</code>, <code>setFocus(n)</code>, <code>pick()</code>, + and <code>close()</code> methods (see the source for details), + that can be used to change the focused element, pick the + current element or close the menu. Additionally <code>menuSize()</code> + can give you access to the size of the current dropdown menu, + <code>length</code> give you the number of available completions, and + <code>data</code> give you full access to the completion returned by the + hinting function.</dd> + <dt><code><strong>extraKeys</strong>: keymap</code></dt> + <dd>Like <code>customKeys</code> above, but the bindings will + be added to the set of default bindings, instead of replacing + them.</dd> + </dl> + The following events will be fired on the completions object + during completion: + <dl> + <dt><code><strong>"shown"</strong> ()</code></dt> + <dd>Fired when the pop-up is shown.</dd> + <dt><code><strong>"select"</strong> (completion, Element)</code></dt> + <dd>Fired when a completion is selected. Passed the completion + value (string or object) and the DOM node that represents it + in the menu.</dd> + <dt><code><strong>"pick"</strong> (completion)</code></dt> + <dd>Fired when a completion is picked. Passed the completion value + (string or object).</dd> + <dt><code><strong>"close"</strong> ()</code></dt> + <dd>Fired when the completion is finished.</dd> + </dl> + This addon depends on styles + from <code>addon/hint/show-hint.css</code>. Check + out <a href="../demo/complete.html">the demo</a> for an + example.</dd> + + <dt id="addon_javascript-hint"><a href="../addon/hint/javascript-hint.js"><code>hint/javascript-hint.js</code></a></dt> + <dd>Defines a simple hinting function for JavaScript + (<code>CodeMirror.hint.javascript</code>) and CoffeeScript + (<code>CodeMirror.hint.coffeescript</code>) code. This will + simply use the JavaScript environment that the editor runs in as + a source of information about objects and their properties.</dd> + + <dt id="addon_xml-hint"><a href="../addon/hint/xml-hint.js"><code>hint/xml-hint.js</code></a></dt> + <dd>Defines <code>CodeMirror.hint.xml</code>, which produces + hints for XML tagnames, attribute names, and attribute values, + guided by a <code>schemaInfo</code> option (a property of the + second argument passed to the hinting function, or the third + argument passed to <code>CodeMirror.showHint</code>).<br>The + schema info should be an object mapping tag names to information + about these tags, with optionally a <code>"!top"</code> property + containing a list of the names of valid top-level tags. The + values of the properties should be objects with optional + properties <code>children</code> (an array of valid child + element names, omit to simply allow all tags to appear) + and <code>attrs</code> (an object mapping attribute names + to <code>null</code> for free-form attributes, and an array of + valid values for restricted + attributes). <a href="../demo/xmlcomplete.html">Demo + here.</a></dd> + + <dt id="addon_html-hint"><a href="../addon/hint/html-hint.js"><code>hint/html-hint.js</code></a></dt> + <dd>Provides schema info to + the <a href="#addon_xml-hint">xml-hint</a> addon for HTML + documents. Defines a schema + object <code>CodeMirror.htmlSchema</code> that you can pass to + as a <code>schemaInfo</code> option, and + a <code>CodeMirror.hint.html</code> hinting function that + automatically calls <code>CodeMirror.hint.xml</code> with this + schema data. See + the <a href="../demo/html5complete.html">demo</a>.</dd> + + <dt id="addon_css-hint"><a href="../addon/hint/css-hint.js"><code>hint/css-hint.js</code></a></dt> + <dd>A hinting function for CSS, SCSS, or LESS code. + Defines <code>CodeMirror.hint.css</code>.</dd> + + <dt id="addon_anyword-hint"><a href="../addon/hint/anyword-hint.js"><code>hint/anyword-hint.js</code></a></dt> + <dd>A very simple hinting function + (<code>CodeMirror.hint.anyword</code>) that simply looks for + words in the nearby code and completes to those. Takes two + optional options, <code>word</code>, a regular expression that + matches words (sequences of one or more character), + and <code>range</code>, which defines how many lines the addon + should scan when completing (defaults to 500).</dd> + + <dt id="addon_sql-hint"><a href="../addon/hint/sql-hint.js"><code>hint/sql-hint.js</code></a></dt> + <dd>A simple SQL hinter. Defines <code>CodeMirror.hint.sql</code>. + Takes two optional options, <code>tables</code>, a object with + table names as keys and array of respective column names as values, + and <code>defaultTable</code>, a string corresponding to a + table name in <code>tables</code> for autocompletion.</dd> + + <dt id="addon_match-highlighter"><a href="../addon/search/match-highlighter.js"><code>search/match-highlighter.js</code></a></dt> + <dd>Adds a <code>highlightSelectionMatches</code> option that + can be enabled to highlight all instances of a currently + selected word. Can be set either to true or to an object + containing the following options: <code>minChars</code>, for the + minimum amount of selected characters that triggers a highlight + (default 2), <code>style</code>, for the style to be used to + highlight the matches (default <code>"matchhighlight"</code>, + which will correspond to CSS + class <code>cm-matchhighlight</code>), <code>trim</code>, which + controls whether whitespace is trimmed from the selection, + and <code>showToken</code> which can be set to <code>true</code> + or to a regexp matching the characters that make up a word. When + enabled, it causes the current word to be highlighted when + nothing is selected (defaults to off). + Demo <a href="../demo/matchhighlighter.html">here</a>.</dd> + + <dt id="addon_lint"><a href="../addon/lint/lint.js"><code>lint/lint.js</code></a></dt> + <dd>Defines an interface component for showing linting warnings, + with pluggable warning sources + (see <a href="../addon/lint/html-lint.js"><code>html-lint.js</code></a>, + <a href="../addon/lint/json-lint.js"><code>json-lint.js</code></a>, + <a href="../addon/lint/javascript-lint.js"><code>javascript-lint.js</code></a>, + <a href="../addon/lint/coffeescript-lint.js"><code>coffeescript-lint.js</code></a>, + and <a href="../addon/lint/css-lint.js"><code>css-lint.js</code></a> + in the same directory). Defines a <code>lint</code> option that + can be set to an annotation source (for + example <code>CodeMirror.lint.javascript</code>), to an options + object (in which case the <code>getAnnotations</code> field is + used as annotation source), or simply to <code>true</code>. When + no annotation source is + specified, <a href="#getHelper"><code>getHelper</code></a> with + type <code>"lint"</code> is used to find an annotation function. + An annotation source function should, when given a document + string, an options object, and an editor instance, return an + array of <code>{message, severity, from, to}</code> objects + representing problems. When the function has + an <code>async</code> property with a truthy value, it will be + called with an additional second argument, which is a callback + to pass the array to. + The linting function can also return a promise, in that case the linter + will only be executed when the promise resolves. + By default, the linter will run (debounced) whenever the document is changed. + You can pass a <code>lintOnChange: false</code> option to disable that. + Depends on <code>addon/lint/lint.css</code>. A demo can be + found <a href="../demo/lint.html">here</a>.</dd> + + <dt id="addon_mark-selection"><a href="../addon/selection/mark-selection.js"><code>selection/mark-selection.js</code></a></dt> + <dd>Causes the selected text to be marked with the CSS class + <code>CodeMirror-selectedtext</code> when the <code>styleSelectedText</code> option + is enabled. Useful to change the colour of the selection (in addition to the background), + like in <a href="../demo/markselection.html">this demo</a>.</dd> + + <dt id="addon_active-line"><a href="../addon/selection/active-line.js"><code>selection/active-line.js</code></a></dt> + <dd>Defines a <code>styleActiveLine</code> option that, when + enabled, gives the wrapper of the line that contains the cursor + the class <code>CodeMirror-activeline</code>, adds a background + with the class <code>CodeMirror-activeline-background</code>, + and adds the class <code>CodeMirror-activeline-gutter</code> to + the line's gutter space is enabled. The option's value may be a + boolean or an object specifying the following options: + <dl> + <dt><code><strong>nonEmpty</strong>: bool</code></dt> + <dd>Controls whether single-line selections, or just cursor + selections, are styled. Defaults to false (only cursor + selections).</dd> + </dl> + See the <a href="../demo/activeline.html">demo</a>.</dd> + + <dt id="addon_selection-pointer"><a href="../addon/selection/selection-pointer.js"><code>selection/selection-pointer.js</code></a></dt> + <dd>Defines a <code>selectionPointer</code> option which you can + use to control the mouse cursor appearance when hovering over + the selection. It can be set to a string, + like <code>"pointer"</code>, or to true, in which case + the <code>"default"</code> (arrow) cursor will be used. You can + see a demo <a href="../mode/htmlmixed/index.html">here</a>.</dd> + + <dt id="addon_loadmode"><a href="../addon/mode/loadmode.js"><code>mode/loadmode.js</code></a></dt> + <dd>Defines a <code>CodeMirror.requireMode(modename, + callback)</code> function that will try to load a given mode and + call the callback when it succeeded. You'll have to + set <code>CodeMirror.modeURL</code> to a string that mode paths + can be constructed from, for + example <code>"mode/%N/%N.js"</code>—the <code>%N</code>'s will + be replaced with the mode name. Also + defines <code>CodeMirror.autoLoadMode(instance, mode)</code>, + which will ensure the given mode is loaded and cause the given + editor instance to refresh its mode when the loading + succeeded. See the <a href="../demo/loadmode.html">demo</a>.</dd> + + <dt id="addon_meta"><a href="../mode/meta.js"><code>mode/meta.js</code></a></dt> + <dd>Provides meta-information about all the modes in the + distribution in a single file. + Defines <code>CodeMirror.modeInfo</code>, an array of objects + with <code>{name, mime, mode}</code> properties, + where <code>name</code> is the human-readable + name, <code>mime</code> the MIME type, and <code>mode</code> the + name of the mode file that defines this MIME. There are optional + properties <code>mimes</code>, which holds an array of MIME + types for modes with multiple MIMEs associated, + and <code>ext</code>, which holds an array of file extensions + associated with this mode. Four convenience + functions, <code>CodeMirror.findModeByMIME</code>, + <code>CodeMirror.findModeByExtension</code>, + <code>CodeMirror.findModeByFileName</code> + and <code>CodeMirror.findModeByName</code> are provided, which + return such an object given a MIME, extension, file name or mode name + string. Note that, for historical reasons, this file resides in the + top-level <code>mode</code> directory, not + under <code>addon</code>. <a href="../demo/loadmode.html">Demo</a>.</dd> + + <dt id="addon_continuecomment"><a href="../addon/comment/continuecomment.js"><code>comment/continuecomment.js</code></a></dt> + <dd>Adds a <code>continueComments</code> option, which sets whether the + editor will make the next line continue a comment when you press Enter + inside a comment block. Can be set to a boolean to enable/disable this + functionality. Set to a string, it will continue comments using a custom + shortcut. Set to an object, it will use the <code>key</code> property for + a custom shortcut and the boolean <code>continueLineComment</code> + property to determine whether single-line comments should be continued + (defaulting to <code>true</code>).</dd> + + <dt id="addon_placeholder"><a href="../addon/display/placeholder.js"><code>display/placeholder.js</code></a></dt> + <dd>Adds a <code>placeholder</code> option that can be used to + make content appear in the editor when it is empty and not + focused. It can hold either a string or a DOM node. Also gives + the editor a <code>CodeMirror-empty</code> CSS class whenever it + doesn't contain any text. + See <a href="../demo/placeholder.html">the demo</a>.</dd> + + <dt id="addon_fullscreen"><a href="../addon/display/fullscreen.js"><code>display/fullscreen.js</code></a></dt> + <dd>Defines an option <code>fullScreen</code> that, when set + to <code>true</code>, will make the editor full-screen (as in, + taking up the whole browser window). Depends + on <a href="../addon/display/fullscreen.css"><code>fullscreen.css</code></a>. <a href="../demo/fullscreen.html">Demo + here</a>.</dd> + + <dt id="addon_autorefresh"><a href="../addon/display/autorefresh.js"><code>display/autorefresh.js</code></a></dt> + <dd>This addon can be useful when initializing an editor in a + hidden DOM node, in cases where it is difficult to + call <a href="#refresh"><code>refresh</code></a> when the editor + becomes visible. It defines an option <code>autoRefresh</code> + which you can set to true to ensure that, if the editor wasn't + visible on initialization, it will be refreshed the first time + it becomes visible. This is done by polling every 250 + milliseconds (you can pass a value like <code>{delay: + 500}</code> as the option value to configure this). Note that + this addon will only refresh the editor <em>once</em> when it + first becomes visible, and won't take care of further restyling + and resizing.</dd> + + <dt id="addon_simplescrollbars"><a href="../addon/scroll/simplescrollbars.js"><code>scroll/simplescrollbars.js</code></a></dt> + <dd>Defines two additional scrollbar + models, <code>"simple"</code> and <code>"overlay"</code> + (see <a href="../demo/simplescrollbars.html">demo</a>) that can + be selected with + the <a href="#option_scrollbarStyle"><code>scrollbarStyle</code></a> + option. Depends + on <a href="../addon/scroll/simplescrollbars.css"><code>simplescrollbars.css</code></a>, + which can be further overridden to style your own + scrollbars.</dd> + + <dt id="addon_annotatescrollbar"><a href="../addon/scroll/annotatescrollbar.js"><code>scroll/annotatescrollbar.js</code></a></dt> + <dd>Provides functionality for showing markers on the scrollbar + to call out certain parts of the document. Adds a + method <code>annotateScrollbar</code> to editor instances that + can be called, with a CSS class name as argument, to create a + set of annotations. The method returns an object + whose <code>update</code> method can be called with a sorted array + of <code>{from: Pos, to: Pos}</code> objects marking the ranges + to be highlighted. To detach the annotations, call the + object's <code>clear</code> method.</dd> + + <dt id="addon_rulers"><a href="../addon/display/rulers.js"><code>display/rulers.js</code></a></dt> + <dd>Adds a <code>rulers</code> option, which can be used to show + one or more vertical rulers in the editor. The option, if + defined, should be given an array of <code>{column [, className, + color, lineStyle, width]}</code> objects or numbers (which + indicate a column). The ruler will be displayed at the column + indicated by the number or the <code>column</code> property. + The <code>className</code> property can be used to assign a + custom style to a ruler. <a href="../demo/rulers.html">Demo + here</a>.</dd> + + <dt id="addon_panel"><a href="../addon/display/panel.js"><code>display/panel.js</code></a></dt> + <dd>Defines an <code>addPanel</code> method for CodeMirror + instances, which places a DOM node above or below an editor, and + shrinks the editor to make room for the node. The method takes + as first argument as DOM node, and as second an optional options + object. The <code>Panel</code> object returned by this method + has a <code>clear</code> method that is used to remove the + panel, and a <code>changed</code> method that can be used to + notify the addon when the size of the panel's DOM node has + changed.<br/> + The method accepts the following options: + <dl> + <dt><code><strong>position</strong>: string</code></dt> + <dd>Controls the position of the newly added panel. The + following values are recognized: + <dl> + <dt><code><strong>top</strong> (default)</code></dt> + <dd>Adds the panel at the very top.</dd> + <dt><code><strong>after-top</strong></code></dt> + <dd>Adds the panel at the bottom of the top panels.</dd> + <dt><code><strong>bottom</strong></code></dt> + <dd>Adds the panel at the very bottom.</dd> + <dt><code><strong>before-bottom</strong></code></dt> + <dd>Adds the panel at the top of the bottom panels.</dd> + </dl> + </dd> + <dt><code><strong>before</strong>: Panel</code></dt> + <dd>The new panel will be added before the given panel.</dd> + <dt><code><strong>after</strong>: Panel</code></dt> + <dd>The new panel will be added after the given panel.</dd> + <dt><code><strong>replace</strong>: Panel</code></dt> + <dd>The new panel will replace the given panel.</dd> + <dt><code><strong>stable</strong>: bool</code></dt> + <dd>Whether to scroll the editor to keep the text's vertical + position stable, when adding a panel above it. Defaults to false.</dd> + </dl> + When using the <code>after</code>, <code>before</code> or <code>replace</code> options, + if the panel doesn't exists or has been removed, + the value of the <code>position</code> option will be used as a fallback. + <br> + A demo of the addon is available <a href="../demo/panel.html">here</a>. + </dd> + + <dt id="addon_hardwrap"><a href="../addon/wrap/hardwrap.js"><code>wrap/hardwrap.js</code></a></dt> + <dd>Addon to perform hard line wrapping/breaking for paragraphs + of text. Adds these methods to editor instances: + <dl> + <dt><code><strong>wrapParagraph</strong>(?pos: {line, ch}, ?options: object)</code></dt> + <dd>Wraps the paragraph at the given position. + If <code>pos</code> is not given, it defaults to the cursor + position.</dd> + <dt><code><strong>wrapRange</strong>(from: {line, ch}, to: {line, ch}, ?options: object)</code></dt> + <dd>Wraps the given range as one big paragraph.</dd> + <dt><code><strong>wrapParagraphsInRange</strong>(from: {line, ch}, to: {line, ch}, ?options: object)</code></dt> + <dd>Wraps the paragraphs in (and overlapping with) the + given range individually.</dd> + </dl> + The following options are recognized: + <dl> + <dt><code><strong>paragraphStart</strong>, <strong>paragraphEnd</strong>: RegExp</code></dt> + <dd>Blank lines are always considered paragraph boundaries. + These options can be used to specify a pattern that causes + lines to be considered the start or end of a paragraph.</dd> + <dt><code><strong>column</strong>: number</code></dt> + <dd>The column to wrap at. Defaults to 80.</dd> + <dt><code><strong>wrapOn</strong>: RegExp</code></dt> + <dd>A regular expression that matches only those + two-character strings that allow wrapping. By default, the + addon wraps on whitespace and after dash characters.</dd> + <dt><code><strong>killTrailingSpace</strong>: boolean</code></dt> + <dd>Whether trailing space caused by wrapping should be + preserved, or deleted. Defaults to true.</dd> + </dl> + A demo of the addon is available <a href="../demo/hardwrap.html">here</a>. + </dd> + + <dt id="addon_merge"><a href="../addon/merge/merge.js"><code>merge/merge.js</code></a></dt> + <dd>Implements an interface for merging changes, using either a + 2-way or a 3-way view. The <code>CodeMirror.MergeView</code> + constructor takes arguments similar to + the <a href="#CodeMirror"><code>CodeMirror</code></a> + constructor, first a node to append the interface to, and then + an options object. Options are passed through to the editors + inside the view. These extra options are recognized: + <dl> + <dt><code><strong>origLeft</strong></code> and <code><strong>origRight</strong>: string</code></dt> + <dd>If given these provide original versions of the + document, which will be shown to the left and right of the + editor in non-editable CodeMirror instances. The merge + interface will highlight changes between the editable + document and the original(s). To create a 2-way (as opposed + to 3-way) merge view, provide only one of them.</dd> + <dt><code><strong>revertButtons</strong>: boolean</code></dt> + <dd>Determines whether buttons that allow the user to revert + changes are shown. Defaults to true.</dd> + <dt><code><strong>revertChunk</strong>: fn(mv: MergeView, from: CodeMirror, fromStart: Pos, fromEnd: Pos, to: CodeMirror, toStart: Pos, toEnd: Pos)</code></dt> + <dd>Can be used to define custom behavior when the user + reverts a changed chunk.</dd> + <dt><code><strong>connect</strong>: string</code></dt> + <dd>Sets the style used to connect changed chunks of code. + By default, connectors are drawn. When this is set + to <code>"align"</code>, the smaller chunk is padded to + align with the bigger chunk instead.</dd> + <dt><code><strong>collapseIdentical</strong>: boolean|number</code></dt> + <dd>When true (default is false), stretches of unchanged + text will be collapsed. When a number is given, this + indicates the amount of lines to leave visible around such + stretches (which defaults to 2).</dd> + <dt><code><strong>allowEditingOriginals</strong>: boolean</code></dt> + <dd>Determines whether the original editor allows editing. + Defaults to false.</dd> + <dt><code><strong>showDifferences</strong>: boolean</code></dt> + <dd>When true (the default), changed pieces of text are + highlighted.</dd> + <dt><code><strong>chunkClassLocation</strong>: string|Array</code></dt> + <dd>By default the chunk highlights are added + using <a href="#addLineClass"><code>addLineClass</code></a> + with "background". Override this to customize it to be any + valid `where` parameter or an Array of valid `where` + parameters.</dd> + </dl> + The addon also defines commands <code>"goNextDiff"</code> + and <code>"goPrevDiff"</code> to quickly jump to the next + changed chunk. <a href="../demo/merge.html">Demo + here</a>.</dd> + + <dt id="addon_tern"><a href="../addon/tern/tern.js"><code>tern/tern.js</code></a></dt> + <dd>Provides integration with + the <a href="http://ternjs.net">Tern</a> JavaScript analysis + engine, for completion, definition finding, and minor + refactoring help. See the <a href="../demo/tern.html">demo</a> + for a very simple integration. For more involved scenarios, see + the comments at the top of + the <a href="../addon/tern/tern.js">addon</a> and the + implementation of the + (multi-file) <a href="http://ternjs.net/doc/demo.html">demonstration + on the Tern website</a>.</dd> + </dl> +</section> + +<section id=modeapi> + <h2>Writing CodeMirror Modes</h2> + + <p>Modes typically consist of a single JavaScript file. This file + defines, in the simplest case, a lexer (tokenizer) for your + language—a function that takes a character stream as input, + advances it past a token, and returns a style for that token. More + advanced modes can also handle indentation for the language.</p> + + <p>This section describes the low-level mode interface. Many modes + are written directly against this, since it offers a lot of + control, but for a quick mode definition, you might want to use + the <a href="../demo/simplemode.html">simple mode addon</a>.</p> + + <p id="defineMode">The mode script should + call <code><strong>CodeMirror.defineMode</strong></code> to + register itself with CodeMirror. This function takes two + arguments. The first should be the name of the mode, for which you + should use a lowercase string, preferably one that is also the + name of the files that define the mode (i.e. <code>"xml"</code> is + defined in <code>xml.js</code>). The second argument should be a + function that, given a CodeMirror configuration object (the thing + passed to the <code>CodeMirror</code> function) and an optional + mode configuration object (as in + the <a href="#option_mode"><code>mode</code></a> option), returns + a mode object.</p> + + <p>Typically, you should use this second argument + to <code>defineMode</code> as your module scope function (modes + should not leak anything into the global scope!), i.e. write your + whole mode inside this function.</p> + + <p>The main responsibility of a mode script is <em>parsing</em> + the content of the editor. Depending on the language and the + amount of functionality desired, this can be done in really easy + or extremely complicated ways. Some parsers can be stateless, + meaning that they look at one element (<em>token</em>) of the code + at a time, with no memory of what came before. Most, however, will + need to remember something. This is done by using a <em>state + object</em>, which is an object that is always passed when + reading a token, and which can be mutated by the tokenizer.</p> + + <p id="startState">Modes that use a state must define + a <code><strong>startState</strong></code> method on their mode + object. This is a function of no arguments that produces a state + object to be used at the start of a document.</p> + + <p id="token">The most important part of a mode object is + its <code><strong>token</strong>(stream, state)</code> method. All + modes must define this method. It should read one token from the + stream it is given as an argument, optionally update its state, + and return a style string, or <code>null</code> for tokens that do + not have to be styled. For your styles, you are encouraged to use + the 'standard' names defined in the themes (without + the <code>cm-</code> prefix). If that fails, it is also possible + to come up with your own and write your own CSS theme file.<p> + + <p id="token_style_line">A typical token string would + be <code>"variable"</code> or <code>"comment"</code>. Multiple + styles can be returned (separated by spaces), for + example <code>"string error"</code> for a thing that looks like a + string but is invalid somehow (say, missing its closing quote). + When a style is prefixed by <code>"line-"</code> + or <code>"line-background-"</code>, the style will be applied to + the whole line, analogous to what + the <a href="#addLineClass"><code>addLineClass</code></a> method + does—styling the <code>"text"</code> in the simple case, and + the <code>"background"</code> element + when <code>"line-background-"</code> is prefixed.</p> + + <p id="StringStream">The stream object that's passed + to <code>token</code> encapsulates a line of code (tokens may + never span lines) and our current position in that line. It has + the following API:</p> + + <dl> + <dt><code><strong>eol</strong>() → boolean</code></dt> + <dd>Returns true only if the stream is at the end of the + line.</dd> + <dt><code><strong>sol</strong>() → boolean</code></dt> + <dd>Returns true only if the stream is at the start of the + line.</dd> + + <dt><code><strong>peek</strong>() → string</code></dt> + <dd>Returns the next character in the stream without advancing + it. Will return a <code>null</code> at the end of the + line.</dd> + <dt><code><strong>next</strong>() → string</code></dt> + <dd>Returns the next character in the stream and advances it. + Also returns <code>null</code> when no more characters are + available.</dd> + + <dt><code><strong>eat</strong>(match: string|regexp|function(char: string) → boolean) → string</code></dt> + <dd><code>match</code> can be a character, a regular expression, + or a function that takes a character and returns a boolean. If + the next character in the stream 'matches' the given argument, + it is consumed and returned. Otherwise, <code>undefined</code> + is returned.</dd> + <dt><code><strong>eatWhile</strong>(match: string|regexp|function(char: string) → boolean) → boolean</code></dt> + <dd>Repeatedly calls <code>eat</code> with the given argument, + until it fails. Returns true if any characters were eaten.</dd> + <dt><code><strong>eatSpace</strong>() → boolean</code></dt> + <dd>Shortcut for <code>eatWhile</code> when matching + white-space.</dd> + <dt><code><strong>skipToEnd</strong>()</code></dt> + <dd>Moves the position to the end of the line.</dd> + <dt><code><strong>skipTo</strong>(str: string) → boolean</code></dt> + <dd>Skips to the start of the next occurrence of the given string, if + found on the current line (doesn't advance the stream if the + string does not occur on the line). Returns true if the + string was found.</dd> + <dt><code><strong>match</strong>(pattern: string, ?consume: boolean, ?caseFold: boolean) → boolean</code></dt> + <dt><code><strong>match</strong>(pattern: regexp, ?consume: boolean) → array&lt;string&gt;</code></dt> + <dd>Act like a + multi-character <code>eat</code>—if <code>consume</code> is true + or not given—or a look-ahead that doesn't update the stream + position—if it is false. <code>pattern</code> can be either a + string or a regular expression starting with <code>^</code>. + When it is a string, <code>caseFold</code> can be set to true to + make the match case-insensitive. When successfully matching a + regular expression, the returned value will be the array + returned by <code>match</code>, in case you need to extract + matched groups.</dd> + + <dt><code><strong>backUp</strong>(n: integer)</code></dt> + <dd>Backs up the stream <code>n</code> characters. Backing it up + further than the start of the current token will cause things to + break, so be careful.</dd> + <dt><code><strong>column</strong>() → integer</code></dt> + <dd>Returns the column (taking into account tabs) at which the + current token starts.</dd> + <dt><code><strong>indentation</strong>() → integer</code></dt> + <dd>Tells you how far the current line has been indented, in + spaces. Corrects for tab characters.</dd> + + <dt><code><strong>current</strong>() → string</code></dt> + <dd>Get the string between the start of the current token and + the current stream position.</dd> + + <dt><code><strong>lookAhead</strong>(n: number) → ?string</code></dt> + <dd>Get the line <code>n</code> (&gt;0) lines after the current + one, in order to scan ahead across line boundaries. Note that + you want to do this carefully, since looking far ahead will make + mode state caching much less effective.</dd> + + <dt id="baseToken"><code><strong>baseToken</strong>() → ?{type: ?string, size: number}</code></dt> + <dd>Modes added + through <a href="#addOverlay"><code>addOverlay</code></a> + (and <em>only</em> such modes) can use this method to inspect + the current token produced by the underlying mode.</dd> + </dl> + + <p id="blankLine">By default, blank lines are simply skipped when + tokenizing a document. For languages that have significant blank + lines, you can define + a <code><strong>blankLine</strong>(state)</code> method on your + mode that will get called whenever a blank line is passed over, so + that it can update the parser state.</p> + + <p id="copyState">Because state object are mutated, and CodeMirror + needs to keep valid versions of a state around so that it can + restart a parse at any line, copies must be made of state objects. + The default algorithm used is that a new state object is created, + which gets all the properties of the old object. Any properties + which hold arrays get a copy of these arrays (since arrays tend to + be used as mutable stacks). When this is not correct, for example + because a mode mutates non-array properties of its state object, a + mode object should define + a <code><strong>copyState</strong></code> method, which is given a + state and should return a safe copy of that state.</p> + + <p id="indent">If you want your mode to provide smart indentation + (through the <a href="#indentLine"><code>indentLine</code></a> + method and the <code>indentAuto</code> + and <code>newlineAndIndent</code> commands, to which keys can be + <a href="#option_extraKeys">bound</a>), you must define + an <code><strong>indent</strong>(state, textAfter)</code> method + on your mode object.</p> + + <p>The indentation method should inspect the given state object, + and optionally the <code>textAfter</code> string, which contains + the text on the line that is being indented, and return an + integer, the amount of spaces to indent. It should usually take + the <a href="#option_indentUnit"><code>indentUnit</code></a> + option into account. An indentation method may + return <code>CodeMirror.Pass</code> to indicate that it + could not come up with a precise indentation.</p> + + <p id="mode_comment">To work well with + the <a href="#addon_comment">commenting addon</a>, a mode may + define <code><strong>lineComment</strong></code> (string that + starts a line + comment), <code><strong>blockCommentStart</strong></code>, <code><strong>blockCommentEnd</strong></code> + (strings that start and end block comments), + and <code>blockCommentLead</code> (a string to put at the start of + continued lines in a block comment). All of these are + optional.</p> + + <p id="electricChars">Finally, a mode may define either + an <code>electricChars</code> or an <code>electricInput</code> + property, which are used to automatically reindent the line when + certain patterns are typed and + the <a href="#option_electricChars"><code>electricChars</code></a> + option is enabled. <code>electricChars</code> may be a string, and + will trigger a reindent whenever one of the characters in that + string are typed. Often, it is more appropriate to + use <code>electricInput</code>, which should hold a regular + expression, and will trigger indentation when the part of the + line <em>before</em> the cursor matches the expression. It should + usually end with a <code>$</code> character, so that it only + matches when the indentation-changing pattern was just typed, not when something was + typed after the pattern.</p> + + <p>So, to summarize, a mode <em>must</em> provide + a <code>token</code> method, and it <em>may</em> + provide <code>startState</code>, <code>copyState</code>, + and <code>indent</code> methods. For an example of a trivial mode, + see the <a href="../mode/diff/diff.js">diff mode</a>, for a more + involved example, see the <a href="../mode/clike/clike.js">C-like + mode</a>.</p> + + <p>Sometimes, it is useful for modes to <em>nest</em>—to have one + mode delegate work to another mode. An example of this kind of + mode is the <a href="../mode/htmlmixed/htmlmixed.js">mixed-mode HTML + mode</a>. To implement such nesting, it is usually necessary to + create mode objects and copy states yourself. To create a mode + object, there are <code>CodeMirror.getMode(options, + parserConfig)</code>, where the first argument is a configuration + object as passed to the mode constructor function, and the second + argument is a mode specification as in + the <a href="#option_mode"><code>mode</code></a> option. To copy a + state object, call <code>CodeMirror.copyState(mode, state)</code>, + where <code>mode</code> is the mode that created the given + state.</p> + + <p id="innerMode">In a nested mode, it is recommended to add an + extra method, <code><strong>innerMode</strong></code> which, given + a state object, returns a <code>{state, mode}</code> object with + the inner mode and its state for the current position. These are + used by utility scripts such as the <a href="#addon_closetag">tag + closer</a> to get context information. Use + the <code>CodeMirror.innerMode</code> helper function to, starting + from a mode and a state, recursively walk down to the innermost + mode and state.</p> + + <p>To make indentation work properly in a nested parser, it is + advisable to give the <code>startState</code> method of modes that + are intended to be nested an optional argument that provides the + base indentation for the block of code. The JavaScript and CSS + parser do this, for example, to allow JavaScript and CSS code + inside the mixed-mode HTML mode to be properly indented.</p> + + <p id="defineMIME">It is possible, and encouraged, to associate + your mode, or a certain configuration of your mode, with + a <a href="http://en.wikipedia.org/wiki/MIME">MIME</a> type. For + example, the JavaScript mode associates itself + with <code>text/javascript</code>, and its JSON variant + with <code>application/json</code>. To do this, + call <code><strong>CodeMirror.defineMIME</strong>(mime, + modeSpec)</code>, where <code>modeSpec</code> can be a string or + object specifying a mode, as in + the <a href="#option_mode"><code>mode</code></a> option.</p> + + <p>If a mode specification wants to add some properties to the + resulting mode object, typically for use + with <a href="#getHelpers"><code>getHelpers</code></a>, it may + contain a <code>modeProps</code> property, which holds an object. + This object's properties will be copied to the actual mode + object.</p> + + <p id="extendMode">Sometimes, it is useful to add or override mode + object properties from external code. + The <code><strong>CodeMirror.extendMode</strong></code> function + can be used to add properties to mode objects produced for a + specific mode. Its first argument is the name of the mode, its + second an object that specifies the properties that should be + added. This is mostly useful to add utilities that can later be + looked up through <a href="#getMode"><code>getMode</code></a>.</p> +</section> + +<section id="vimapi"> + <h2>VIM Mode API</h2> + + <p>CodeMirror has a robust VIM mode that attempts to faithfully + emulate VIM's most useful features. It can be enabled by + including <a href="../keymap/vim.js"><code>keymap/vim.js</code> + </a> and setting the <code>keyMap</code> option to + <code>"vim"</code>.</p> + + <h3 id="vimapi_configuration">Configuration</h3> + + <p>VIM mode accepts configuration options for customizing + behavior at run time. These methods can be called at any time + and will affect all existing CodeMirror instances unless + specified otherwise. The methods are exposed on the + <code><strong>CodeMirror.Vim</strong></code> object.</p> + + <dl> + <dt id="vimapi_setOption"><code><strong>setOption(name: string, value: any, ?cm: CodeMirror, ?cfg: object)</strong></code></dt> + <dd>Sets the value of a VIM option. <code>name</code> should + be the name of an option. If <code>cfg.scope</code> is not set + and <code>cm</code> is provided, then sets the global and + instance values of the option. Otherwise, sets either the + global or instance value of the option depending on whether + <code>cfg.scope</code> is <code>global</code> or + <code>local</code>.</dd> + <dt id="vimapi_getOption"><code><strong>getOption(name: string, ?cm: CodeMirror: ?cfg: object)</strong></code></dt> + <dd>Gets the current value of a VIM option. If + <code>cfg.scope</code> is not set and <code>cm</code> is + provided, then gets the instance value of the option, falling + back to the global value if not set. If <code>cfg.scope</code> is provided, then gets the <code>global</code> or + <code>local</code> value without checking the other.</dd> + + <dt id="vimapi_map"><code><strong>map(lhs: string, rhs: string, ?context: string)</strong></code></dt> + <dd>Maps a key sequence to another key sequence. Implements + VIM's <code>:map</code> command. To map ; to : in VIM would be + <code><strong>:map ; :</strong></code>. That would translate to + <code><strong>CodeMirror.Vim.map(';', ':');</strong></code>. + The <code>context</code> can be <code>normal</code>, + <code>visual</code>, or <code>insert</code>, which correspond + to <code>:nmap</code>, <code>:vmap</code>, and + <code>:imap</code> + respectively.</dd> + + <dt id="vimapi_mapCommand"><code><strong>mapCommand(keys: string, type: string, name: string, ?args: object, ?extra: object)</strong></code></dt> + <dd>Maps a key sequence to a <code>motion</code>, + <code>operator</code>, or <code>action</code> type command. + The args object is passed through to the command when it is + invoked by the provided key sequence. + <code>extras.context</code> can be <code>normal</code>, + <code>visual</code>, or <code>insert</code>, to map the key + sequence only in the corresponding mode. + <code>extras.isEdit</code> is applicable only to actions, + determining whether it is recorded for replay for the + <code>.</code> single-repeat command. + </dl> + + <h3 id="vimapi_extending">Extending VIM</h3> + + <p>CodeMirror's VIM mode implements a large subset of VIM's core + editing functionality. But since there's always more to be + desired, there is a set of APIs for extending VIM's + functionality. As with the configuration API, the methods are + exposed on <code><strong>CodeMirror.Vim</strong></code> and may + be called at any time.</p> + + <dl> + <dt id="vimapi_defineOption"><code><strong>defineOption(name: string, default: any, type: string, ?aliases: array&lt;string&gt;, ?callback: function (?value: any, ?cm: CodeMirror) → ?any)</strong></code></dt> + <dd>Defines a VIM style option and makes it available to the + <code>:set</code> command. Type can be <code>boolean</code> or + <code>string</code>, used for validation and by + <code>:set</code> to determine which syntax to accept. If a + <code>callback</code> is passed in, VIM does not store the value of the + option itself, but instead uses the callback as a setter/getter. If the + first argument to the callback is <code>undefined</code>, then the + callback should return the value of the option. Otherwise, it should set + instead. Since VIM options have global and instance values, whether a + <code>CodeMirror</code> instance is passed in denotes whether the global + or local value should be used. Consequently, it's possible for the + callback to be called twice for a single <code>setOption</code> or + <code>getOption</code> call. Note that right now, VIM does not support + defining buffer-local options that do not have global values. If an + option should not have a global value, either always ignore the + <code>cm</code> parameter in the callback, or always pass in a + <code>cfg.scope</code> to <code>setOption</code> and + <code>getOption</code>.</dd> + + <dt id="vimapi_defineMotion"><code><strong>defineMotion(name: string, fn: function(cm: CodeMirror, head: {line, ch}, ?motionArgs: object}) → {line, ch})</strong></code></dt> + <dd>Defines a motion command for VIM. The motion should return + the desired result position of the cursor. <code>head</code> + is the current position of the cursor. It can differ from + <code>cm.getCursor('head')</code> if VIM is in visual mode. + <code>motionArgs</code> is the object passed into + <strong><code>mapCommand()</code></strong>.</dd> + + <dt id="vimapi_defineOperator"><strong><code>defineOperator(name: string, fn: function(cm: CodeMirror, ?operatorArgs: object, ranges: array&lt;{anchor, head}&gt;) → ?{line, ch})</code></strong></dt> + <dd>Defines an operator command, similar to <strong><code> + defineMotion</code></strong>. <code>ranges</code> is the range + of text the operator should operate on. If the cursor should + be set to a certain position after the operation finishes, it + can return a cursor object.</dd> + + <dt id="vimapi_defineActon"><strong><code>defineAction(name: string, fn: function(cm: CodeMirror, ?actionArgs: object))</code></strong></dt> + <dd>Defines an action command, similar to + <strong><code>defineMotion</code></strong>. Action commands + can have arbitrary behavior, making them more flexible than + motions and operators, at the loss of orthogonality.</dd> + + <dt id="vimapi_defineEx"><strong><code>defineEx(name: string, ?prefix: string, fn: function(cm: CodeMirror, ?params: object))</code></strong></dt> + <dd>Defines an Ex command, and maps it to <code>:name</code>. + If a prefix is provided, it, and any prefixed substring of the + <code>name</code> beginning with the <code>prefix</code> can + be used to invoke the command. If the <code>prefix</code> is + falsy, then <code>name</code> is used as the prefix. <code> + params.argString</code> contains the part of the prompted + string after the command name. <code>params.args</code> is + <code>params.argString</code> split by whitespace. If the + command was prefixed with a + <code><strong><a href="http://vimdoc.sourceforge.net/htmldoc/cmdline.html#cmdline-ranges">line range</a></strong></code>, + <code>params.line</code> and <code>params.lineEnd</code> will + be set. + </dl> + +</section> + +</article> + +<script>setTimeout(function(){CodeMirror.colorize();}, 20);</script> diff --git a/modules/editor/codemirror/keymap/sublime.js b/modules/editor/codemirror/keymap/sublime.js @@ -0,0 +1,704 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// A rough approximation of Sublime Text's keybindings +// Depends on addon/search/searchcursor.js and optionally addon/dialog/dialogs.js + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../lib/codemirror"), require("../addon/search/searchcursor"), require("../addon/edit/matchbrackets")); + else if (typeof define == "function" && define.amd) // AMD + define(["../lib/codemirror", "../addon/search/searchcursor", "../addon/edit/matchbrackets"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + var cmds = CodeMirror.commands; + var Pos = CodeMirror.Pos; + + // This is not exactly Sublime's algorithm. I couldn't make heads or tails of that. + function findPosSubword(doc, start, dir) { + if (dir < 0 && start.ch == 0) 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)); + var state = "start", type; + for (var 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); + var cat = next != "_" && CodeMirror.isWordChar(next) ? "w" : "o"; + if (cat == "w" && next.toUpperCase() == next) cat = "W"; + if (state == "start") { + if (cat != "o") { state = "in"; type = cat; } + } else if (state == "in") { + if (type != cat) { + if (type == "w" && cat == "W" && dir < 0) pos--; + if (type == "W" && cat == "w" && dir > 0) { type = "w"; continue; } + break; + } + } + } + return Pos(start.line, pos); + } + + function moveSubword(cm, dir) { + cm.extendSelectionsBy(function(range) { + if (cm.display.shift || cm.doc.extend || range.empty()) + return findPosSubword(cm.doc, range.head, dir); + else + return dir < 0 ? range.from() : range.to(); + }); + } + + cmds.goSubwordLeft = function(cm) { moveSubword(cm, -1); }; + cmds.goSubwordRight = function(cm) { moveSubword(cm, 1); }; + + cmds.scrollLineUp = function(cm) { + var info = cm.getScrollInfo(); + if (!cm.somethingSelected()) { + var visibleBottomLine = cm.lineAtHeight(info.top + info.clientHeight, "local"); + if (cm.getCursor().line >= visibleBottomLine) + cm.execCommand("goLineUp"); + } + cm.scrollTo(null, info.top - cm.defaultTextHeight()); + }; + cmds.scrollLineDown = function(cm) { + var info = cm.getScrollInfo(); + if (!cm.somethingSelected()) { + var visibleTopLine = cm.lineAtHeight(info.top, "local")+1; + if (cm.getCursor().line <= visibleTopLine) + cm.execCommand("goLineDown"); + } + cm.scrollTo(null, info.top + cm.defaultTextHeight()); + }; + + cmds.splitSelectionByLine = function(cm) { + var ranges = cm.listSelections(), lineRanges = []; + for (var i = 0; i < ranges.length; i++) { + var from = ranges[i].from(), to = ranges[i].to(); + for (var line = from.line; line <= to.line; ++line) + if (!(to.line > from.line && line == to.line && to.ch == 0)) + lineRanges.push({anchor: line == from.line ? from : Pos(line, 0), + head: line == to.line ? to : Pos(line)}); + } + cm.setSelections(lineRanges, 0); + }; + + cmds.singleSelectionTop = function(cm) { + var range = cm.listSelections()[0]; + cm.setSelection(range.anchor, range.head, {scroll: false}); + }; + + cmds.selectLine = function(cm) { + var ranges = cm.listSelections(), extended = []; + for (var 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); + }; + + function insertLine(cm, above) { + if (cm.isReadOnly()) return CodeMirror.Pass + cm.operation(function() { + var len = cm.listSelections().length, newSelection = [], last = -1; + for (var i = 0; i < len; i++) { + var head = cm.listSelections()[i].head; + if (head.line <= last) continue; + var at = Pos(head.line + (above ? 0 : 1), 0); + cm.replaceRange("\n", at, null, "+insertLine"); + cm.indentLine(at.line, null, true); + newSelection.push({head: at, anchor: at}); + last = head.line + 1; + } + cm.setSelections(newSelection); + }); + cm.execCommand("indentAuto"); + } + + cmds.insertLineAfter = function(cm) { return insertLine(cm, false); }; + + cmds.insertLineBefore = function(cm) { return insertLine(cm, true); }; + + function wordAt(cm, pos) { + var start = pos.ch, end = start, line = cm.getLine(pos.line); + while (start && CodeMirror.isWordChar(line.charAt(start - 1))) --start; + while (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)}; + } + + cmds.selectNextOccurrence = function(cm) { + var from = cm.getCursor("from"), to = cm.getCursor("to"); + var fullWord = cm.state.sublimeFindFullWord == cm.doc.sel; + if (CodeMirror.cmpPos(from, to) == 0) { + var word = wordAt(cm, from); + if (!word.word) return; + cm.setSelection(word.from, word.to); + fullWord = true; + } else { + var text = cm.getRange(from, to); + var query = fullWord ? new RegExp("\\b" + text + "\\b") : text; + var cur = cm.getSearchCursor(query, to); + var found = cur.findNext(); + if (!found) { + cur = cm.getSearchCursor(query, Pos(cm.firstLine(), 0)); + found = cur.findNext(); + } + if (!found || isSelectedRange(cm.listSelections(), cur.from(), cur.to())) + return CodeMirror.Pass + cm.addSelection(cur.from(), cur.to()); + } + if (fullWord) + cm.state.sublimeFindFullWord = cm.doc.sel; + }; + + function addCursorToSelection(cm, dir) { + var ranges = cm.listSelections(), newRanges = []; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + var newAnchor = cm.findPosV(range.anchor, dir, "line"); + var newHead = cm.findPosV(range.head, dir, "line"); + var newRange = {anchor: newAnchor, head: newHead}; + newRanges.push(range); + newRanges.push(newRange); + } + cm.setSelections(newRanges); + } + cmds.addCursorToPrevLine = function(cm) { addCursorToSelection(cm, -1); }; + cmds.addCursorToNextLine = function(cm) { addCursorToSelection(cm, 1); }; + + function isSelectedRange(ranges, from, to) { + for (var i = 0; i < ranges.length; i++) + if (ranges[i].from() == from && ranges[i].to() == to) return true + return false + } + + var mirror = "(){}[]"; + function selectBetweenBrackets(cm) { + var ranges = cm.listSelections(), newRanges = [] + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i], pos = range.head, opening = cm.scanForBracket(pos, -1); + if (!opening) return false; + for (;;) { + var closing = cm.scanForBracket(pos, 1); + if (!closing) return false; + 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 true; + } + + cmds.selectScope = function(cm) { + selectBetweenBrackets(cm) || cm.execCommand("selectAll"); + }; + cmds.selectBetweenBrackets = function(cm) { + if (!selectBetweenBrackets(cm)) return CodeMirror.Pass; + }; + + cmds.goToBracket = function(cm) { + cm.extendSelectionsBy(function(range) { + var next = cm.scanForBracket(range.head, 1); + if (next && CodeMirror.cmpPos(next.pos, range.head) != 0) return next.pos; + var prev = cm.scanForBracket(range.head, -1); + return prev && Pos(prev.pos.line, prev.pos.ch + 1) || range.head; + }); + }; + + cmds.swapLineUp = function(cm) { + if (cm.isReadOnly()) return CodeMirror.Pass + var ranges = cm.listSelections(), linesToMove = [], at = cm.firstLine() - 1, newSels = []; + for (var 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)}); + if (range.to().ch == 0 && !range.empty()) --to; + if (from > at) linesToMove.push(from, to); + else if (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]; + var line = cm.getLine(from); + cm.replaceRange("", Pos(from, 0), Pos(from + 1, 0), "+swapLine"); + if (to > cm.lastLine()) + cm.replaceRange("\n" + line, Pos(cm.lastLine()), null, "+swapLine"); + else + cm.replaceRange(line + "\n", Pos(to, 0), null, "+swapLine"); + } + cm.setSelections(newSels); + cm.scrollIntoView(); + }); + }; + + cmds.swapLineDown = function(cm) { + if (cm.isReadOnly()) return CodeMirror.Pass + var ranges = cm.listSelections(), linesToMove = [], at = cm.lastLine() + 1; + for (var i = ranges.length - 1; i >= 0; i--) { + var range = ranges[i], from = range.to().line + 1, to = range.from().line; + if (range.to().ch == 0 && !range.empty()) from--; + if (from < at) linesToMove.push(from, to); + else if (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]; + var line = cm.getLine(from); + if (from == cm.lastLine()) + cm.replaceRange("", Pos(from - 1), Pos(from), "+swapLine"); + else + cm.replaceRange("", Pos(from, 0), Pos(from + 1, 0), "+swapLine"); + cm.replaceRange(line + "\n", Pos(to, 0), null, "+swapLine"); + } + cm.scrollIntoView(); + }); + }; + + cmds.toggleCommentIndented = function(cm) { + cm.toggleComment({ indent: true }); + } + + cmds.joinLines = function(cm) { + var ranges = cm.listSelections(), joined = []; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i], from = range.from(); + var start = from.line, end = range.to().line; + while (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() { + var offset = 0, ranges = []; + for (var i = 0; i < joined.length; i++) { + var obj = joined[i]; + var anchor = obj.anchor && Pos(obj.anchor.line - offset, obj.anchor.ch), head; + for (var line = obj.start; line <= obj.end; line++) { + var actual = line - offset; + if (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.duplicateLine = function(cm) { + cm.operation(function() { + var rangeCount = cm.listSelections().length; + for (var i = 0; i < rangeCount; i++) { + var range = cm.listSelections()[i]; + if (range.empty()) + cm.replaceRange(cm.getLine(range.head.line) + "\n", Pos(range.head.line, 0)); + else + cm.replaceRange(cm.getRange(range.from(), range.to()), range.from()); + } + cm.scrollIntoView(); + }); + }; + + + function sortLines(cm, caseSensitive) { + if (cm.isReadOnly()) return CodeMirror.Pass + var ranges = cm.listSelections(), toSort = [], selected; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (range.empty()) continue; + var from = range.from().line, to = range.to().line; + while (i < ranges.length - 1 && ranges[i + 1].from().line == to) + to = ranges[++i].to().line; + if (!ranges[i].to().ch) to--; + toSort.push(from, to); + } + if (toSort.length) selected = true; + else toSort.push(cm.firstLine(), cm.lastLine()); + + cm.operation(function() { + var ranges = []; + for (var i = 0; i < toSort.length; i += 2) { + var from = toSort[i], to = toSort[i + 1]; + var start = Pos(from, 0), end = Pos(to); + var lines = cm.getRange(start, end, false); + if (caseSensitive) + lines.sort(); + else + 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); + if (selected) ranges.push({anchor: start, head: Pos(to + 1, 0)}); + } + if (selected) cm.setSelections(ranges, 0); + }); + } + + cmds.sortLines = function(cm) { sortLines(cm, true); }; + cmds.sortLinesInsensitive = function(cm) { sortLines(cm, false); }; + + cmds.nextBookmark = function(cm) { + var marks = cm.state.sublimeBookmarks; + if (marks) while (marks.length) { + var current = marks.shift(); + var found = current.find(); + if (found) { + marks.push(current); + return cm.setSelection(found.from, found.to); + } + } + }; + + cmds.prevBookmark = function(cm) { + var marks = cm.state.sublimeBookmarks; + if (marks) while (marks.length) { + marks.unshift(marks.pop()); + var found = marks[marks.length - 1].find(); + if (!found) + marks.pop(); + else + return cm.setSelection(found.from, found.to); + } + }; + + cmds.toggleBookmark = function(cm) { + var ranges = cm.listSelections(); + var marks = cm.state.sublimeBookmarks || (cm.state.sublimeBookmarks = []); + for (var i = 0; i < ranges.length; i++) { + var from = ranges[i].from(), to = ranges[i].to(); + var found = cm.findMarks(from, to); + for (var j = 0; j < found.length; j++) { + if (found[j].sublimeBookmark) { + found[j].clear(); + for (var k = 0; k < marks.length; k++) + if (marks[k] == found[j]) + marks.splice(k--, 1); + break; + } + } + if (j == found.length) + marks.push(cm.markText(from, to, {sublimeBookmark: true, clearWhenEmpty: false})); + } + }; + + cmds.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.selectBookmarks = function(cm) { + var marks = cm.state.sublimeBookmarks, ranges = []; + if (marks) for (var i = 0; i < marks.length; i++) { + var found = marks[i].find(); + if (!found) + marks.splice(i--, 0); + else + ranges.push({anchor: found.from, head: found.to}); + } + if (ranges.length) + cm.setSelections(ranges, 0); + }; + + function modifyWordOrSelection(cm, mod) { + cm.operation(function() { + var ranges = cm.listSelections(), indices = [], replacements = []; + for (var 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 i = indices.length - 1, at; i >= 0; i--) { + var range = ranges[indices[i]]; + if (at && CodeMirror.cmpPos(range.head, at) > 0) continue; + var word = wordAt(cm, range.head); + at = word.from; + cm.replaceRange(mod(word.word), word.from, word.to); + } + }); + } + + cmds.smartBackspace = function(cm) { + if (cm.somethingSelected()) return CodeMirror.Pass; + + cm.operation(function() { + var cursors = cm.listSelections(); + var indentUnit = cm.getOption("indentUnit"); + + for (var i = cursors.length - 1; i >= 0; i--) { + var cursor = cursors[i].head; + var toStartOfLine = cm.getRange({line: cursor.line, ch: 0}, cursor); + var column = CodeMirror.countColumn(toStartOfLine, null, cm.getOption("tabSize")); + + // Delete by one character by default + var deletePos = cm.findPosH(cursor, -1, "char", false); + + if (toStartOfLine && !/\S/.test(toStartOfLine) && column % indentUnit == 0) { + var prevIndent = new Pos(cursor.line, + CodeMirror.findColumn(toStartOfLine, column - indentUnit, indentUnit)); + + // Smart delete only if we found a valid prevIndent location + if (prevIndent.ch != cursor.ch) deletePos = prevIndent; + } + + cm.replaceRange("", deletePos, cursor, "+delete"); + } + }); + }; + + cmds.delLineRight = function(cm) { + cm.operation(function() { + var ranges = cm.listSelections(); + for (var i = ranges.length - 1; i >= 0; i--) + cm.replaceRange("", ranges[i].anchor, Pos(ranges[i].to().line), "+delete"); + cm.scrollIntoView(); + }); + }; + + cmds.upcaseAtCursor = function(cm) { + modifyWordOrSelection(cm, function(str) { return str.toUpperCase(); }); + }; + cmds.downcaseAtCursor = function(cm) { + modifyWordOrSelection(cm, function(str) { return str.toLowerCase(); }); + }; + + cmds.setSublimeMark = function(cm) { + if (cm.state.sublimeMark) cm.state.sublimeMark.clear(); + cm.state.sublimeMark = cm.setBookmark(cm.getCursor()); + }; + cmds.selectToSublimeMark = function(cm) { + var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); + if (found) cm.setSelection(cm.getCursor(), found); + }; + cmds.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.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.sublimeYank = function(cm) { + if (cm.state.sublimeKilled != null) + cm.replaceSelection(cm.state.sublimeKilled, null, "paste"); + }; + + cmds.showInCenter = function(cm) { + var pos = cm.cursorCoords(null, "local"); + cm.scrollTo(null, (pos.top + pos.bottom) / 2 - cm.getScrollInfo().clientHeight / 2); + }; + + cmds.selectLinesUpward = function(cm) { + cm.operation(function() { + var ranges = cm.listSelections(); + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (range.head.line > cm.firstLine()) + cm.addSelection(Pos(range.head.line - 1, range.head.ch)); + } + }); + }; + cmds.selectLinesDownward = function(cm) { + cm.operation(function() { + var ranges = cm.listSelections(); + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (range.head.line < cm.lastLine()) + cm.addSelection(Pos(range.head.line + 1, range.head.ch)); + } + }); + }; + + function getTarget(cm) { + var from = cm.getCursor("from"), to = cm.getCursor("to"); + if (CodeMirror.cmpPos(from, to) == 0) { + 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) return; + var query = target.query; + var 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()))); + if (forward ? cur.findNext() : cur.findPrevious()) + cm.setSelection(cur.from(), cur.to()); + else if (target.word) + cm.setSelection(target.from, target.to); + } + }; + cmds.findUnder = function(cm) { findAndGoTo(cm, true); }; + cmds.findUnderPrevious = function(cm) { findAndGoTo(cm,false); }; + cmds.findAllUnder = function(cm) { + var target = getTarget(cm); + if (!target) return; + var cur = cm.getSearchCursor(target.query); + var matches = []; + var primaryIndex = -1; + while (cur.findNext()) { + matches.push({anchor: cur.from(), head: cur.to()}); + if (cur.from().line <= target.from.line && cur.from().ch <= target.from.ch) + primaryIndex++; + } + cm.setSelections(matches, primaryIndex); + }; + + + var keyMap = CodeMirror.keyMap; + keyMap.macSublime = { + "Cmd-Left": "goLineStartSmart", + "Shift-Tab": "indentLess", + "Shift-Ctrl-K": "deleteLine", + "Alt-Q": "wrapLines", + "Ctrl-Left": "goSubwordLeft", + "Ctrl-Right": "goSubwordRight", + "Ctrl-Alt-Up": "scrollLineUp", + "Ctrl-Alt-Down": "scrollLineDown", + "Cmd-L": "selectLine", + "Shift-Cmd-L": "splitSelectionByLine", + "Esc": "singleSelectionTop", + "Cmd-Enter": "insertLineAfter", + "Shift-Cmd-Enter": "insertLineBefore", + "Cmd-D": "selectNextOccurrence", + "Shift-Cmd-Up": "addCursorToPrevLine", + "Shift-Cmd-Down": "addCursorToNextLine", + "Shift-Cmd-Space": "selectScope", + "Shift-Cmd-M": "selectBetweenBrackets", + "Cmd-M": "goToBracket", + "Cmd-Ctrl-Up": "swapLineUp", + "Cmd-Ctrl-Down": "swapLineDown", + "Cmd-/": "toggleCommentIndented", + "Cmd-J": "joinLines", + "Shift-Cmd-D": "duplicateLine", + "F9": "sortLines", + "Cmd-F9": "sortLinesInsensitive", + "F2": "nextBookmark", + "Shift-F2": "prevBookmark", + "Cmd-F2": "toggleBookmark", + "Shift-Cmd-F2": "clearBookmarks", + "Alt-F2": "selectBookmarks", + "Backspace": "smartBackspace", + "Cmd-K Cmd-K": "delLineRight", + "Cmd-K Cmd-U": "upcaseAtCursor", + "Cmd-K Cmd-L": "downcaseAtCursor", + "Cmd-K Cmd-Space": "setSublimeMark", + "Cmd-K Cmd-A": "selectToSublimeMark", + "Cmd-K Cmd-W": "deleteToSublimeMark", + "Cmd-K Cmd-X": "swapWithSublimeMark", + "Cmd-K Cmd-Y": "sublimeYank", + "Cmd-K Cmd-C": "showInCenter", + "Cmd-K Cmd-G": "clearBookmarks", + "Cmd-K Cmd-Backspace": "delLineLeft", + "Cmd-K Cmd-0": "unfoldAll", + "Cmd-K Cmd-J": "unfoldAll", + "Ctrl-Shift-Up": "selectLinesUpward", + "Ctrl-Shift-Down": "selectLinesDownward", + "Cmd-F3": "findUnder", + "Shift-Cmd-F3": "findUnderPrevious", + "Alt-F3": "findAllUnder", + "Shift-Cmd-[": "fold", + "Shift-Cmd-]": "unfold", + "Cmd-I": "findIncremental", + "Shift-Cmd-I": "findIncrementalReverse", + "Cmd-H": "replace", + "F3": "findNext", + "Shift-F3": "findPrev", + "fallthrough": "macDefault" + }; + CodeMirror.normalizeKeyMap(keyMap.macSublime); + + keyMap.pcSublime = { + "Shift-Tab": "indentLess", + "Shift-Ctrl-K": "deleteLine", + "Alt-Q": "wrapLines", + "Ctrl-T": "transposeChars", + "Alt-Left": "goSubwordLeft", + "Alt-Right": "goSubwordRight", + "Ctrl-Up": "scrollLineUp", + "Ctrl-Down": "scrollLineDown", + "Ctrl-L": "selectLine", + "Shift-Ctrl-L": "splitSelectionByLine", + "Esc": "singleSelectionTop", + "Ctrl-Enter": "insertLineAfter", + "Shift-Ctrl-Enter": "insertLineBefore", + "Ctrl-D": "selectNextOccurrence", + "Alt-CtrlUp": "addCursorToPrevLine", + "Alt-CtrlDown": "addCursorToNextLine", + "Shift-Ctrl-Space": "selectScope", + "Shift-Ctrl-M": "selectBetweenBrackets", + "Ctrl-M": "goToBracket", + "Shift-Ctrl-Up": "swapLineUp", + "Shift-Ctrl-Down": "swapLineDown", + "Ctrl-/": "toggleCommentIndented", + "Ctrl-J": "joinLines", + "Shift-Ctrl-D": "duplicateLine", + "F9": "sortLines", + "Ctrl-F9": "sortLinesInsensitive", + "F2": "nextBookmark", + "Shift-F2": "prevBookmark", + "Ctrl-F2": "toggleBookmark", + "Shift-Ctrl-F2": "clearBookmarks", + "Alt-F2": "selectBookmarks", + "Backspace": "smartBackspace", + "Ctrl-K Ctrl-K": "delLineRight", + "Ctrl-K Ctrl-U": "upcaseAtCursor", + "Ctrl-K Ctrl-L": "downcaseAtCursor", + "Ctrl-K Ctrl-Space": "setSublimeMark", + "Ctrl-K Ctrl-A": "selectToSublimeMark", + "Ctrl-K Ctrl-W": "deleteToSublimeMark", + "Ctrl-K Ctrl-X": "swapWithSublimeMark", + "Ctrl-K Ctrl-Y": "sublimeYank", + "Ctrl-K Ctrl-C": "showInCenter", + "Ctrl-K Ctrl-G": "clearBookmarks", + "Ctrl-K Ctrl-Backspace": "delLineLeft", + "Ctrl-K Ctrl-0": "unfoldAll", + "Ctrl-K Ctrl-J": "unfoldAll", + "Ctrl-Alt-Up": "selectLinesUpward", + "Ctrl-Alt-Down": "selectLinesDownward", + "Ctrl-F3": "findUnder", + "Shift-Ctrl-F3": "findUnderPrevious", + "Alt-F3": "findAllUnder", + "Shift-Ctrl-[": "fold", + "Shift-Ctrl-]": "unfold", + "Ctrl-I": "findIncremental", + "Shift-Ctrl-I": "findIncrementalReverse", + "Ctrl-H": "replace", + "F3": "findNext", + "Shift-F3": "findPrev", + "fallthrough": "pcDefault" + }; + CodeMirror.normalizeKeyMap(keyMap.pcSublime); + + var mac = keyMap.default == keyMap.macDefault; + keyMap.sublime = mac ? keyMap.macSublime : keyMap.pcSublime; +}); diff --git a/modules/editor/codemirror/keymap/sublime.min.js b/modules/editor/codemirror/keymap/sublime.min.js @@ -0,0 +1,704 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// A rough approximation of Sublime Text's keybindings +// Depends on addon/search/searchcursor.js and optionally addon/dialog/dialogs.js + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../lib/codemirror"), require("../addon/search/searchcursor"), require("../addon/edit/matchbrackets")); + else if (typeof define == "function" && define.amd) // AMD + define(["../lib/codemirror", "../addon/search/searchcursor", "../addon/edit/matchbrackets"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + var cmds = CodeMirror.commands; + var Pos = CodeMirror.Pos; + + // This is not exactly Sublime's algorithm. I couldn't make heads or tails of that. + function findPosSubword(doc, start, dir) { + if (dir < 0 && start.ch == 0) 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)); + var state = "start", type; + for (var 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); + var cat = next != "_" && CodeMirror.isWordChar(next) ? "w" : "o"; + if (cat == "w" && next.toUpperCase() == next) cat = "W"; + if (state == "start") { + if (cat != "o") { state = "in"; type = cat; } + } else if (state == "in") { + if (type != cat) { + if (type == "w" && cat == "W" && dir < 0) pos--; + if (type == "W" && cat == "w" && dir > 0) { type = "w"; continue; } + break; + } + } + } + return Pos(start.line, pos); + } + + function moveSubword(cm, dir) { + cm.extendSelectionsBy(function(range) { + if (cm.display.shift || cm.doc.extend || range.empty()) + return findPosSubword(cm.doc, range.head, dir); + else + return dir < 0 ? range.from() : range.to(); + }); + } + + cmds.goSubwordLeft = function(cm) { moveSubword(cm, -1); }; + cmds.goSubwordRight = function(cm) { moveSubword(cm, 1); }; + + cmds.scrollLineUp = function(cm) { + var info = cm.getScrollInfo(); + if (!cm.somethingSelected()) { + var visibleBottomLine = cm.lineAtHeight(info.top + info.clientHeight, "local"); + if (cm.getCursor().line >= visibleBottomLine) + cm.execCommand("goLineUp"); + } + cm.scrollTo(null, info.top - cm.defaultTextHeight()); + }; + cmds.scrollLineDown = function(cm) { + var info = cm.getScrollInfo(); + if (!cm.somethingSelected()) { + var visibleTopLine = cm.lineAtHeight(info.top, "local")+1; + if (cm.getCursor().line <= visibleTopLine) + cm.execCommand("goLineDown"); + } + cm.scrollTo(null, info.top + cm.defaultTextHeight()); + }; + + cmds.splitSelectionByLine = function(cm) { + var ranges = cm.listSelections(), lineRanges = []; + for (var i = 0; i < ranges.length; i++) { + var from = ranges[i].from(), to = ranges[i].to(); + for (var line = from.line; line <= to.line; ++line) + if (!(to.line > from.line && line == to.line && to.ch == 0)) + lineRanges.push({anchor: line == from.line ? from : Pos(line, 0), + head: line == to.line ? to : Pos(line)}); + } + cm.setSelections(lineRanges, 0); + }; + + cmds.singleSelectionTop = function(cm) { + var range = cm.listSelections()[0]; + cm.setSelection(range.anchor, range.head, {scroll: false}); + }; + + cmds.selectLine = function(cm) { + var ranges = cm.listSelections(), extended = []; + for (var 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); + }; + + function insertLine(cm, above) { + if (cm.isReadOnly()) return CodeMirror.Pass + cm.operation(function() { + var len = cm.listSelections().length, newSelection = [], last = -1; + for (var i = 0; i < len; i++) { + var head = cm.listSelections()[i].head; + if (head.line <= last) continue; + var at = Pos(head.line + (above ? 0 : 1), 0); + cm.replaceRange("\n", at, null, "+insertLine"); + cm.indentLine(at.line, null, true); + newSelection.push({head: at, anchor: at}); + last = head.line + 1; + } + cm.setSelections(newSelection); + }); + cm.execCommand("indentAuto"); + } + + cmds.insertLineAfter = function(cm) { return insertLine(cm, false); }; + + cmds.insertLineBefore = function(cm) { return insertLine(cm, true); }; + + function wordAt(cm, pos) { + var start = pos.ch, end = start, line = cm.getLine(pos.line); + while (start && CodeMirror.isWordChar(line.charAt(start - 1))) --start; + while (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)}; + } + + cmds.selectNextOccurrence = function(cm) { + var from = cm.getCursor("from"), to = cm.getCursor("to"); + var fullWord = cm.state.sublimeFindFullWord == cm.doc.sel; + if (CodeMirror.cmpPos(from, to) == 0) { + var word = wordAt(cm, from); + if (!word.word) return; + cm.setSelection(word.from, word.to); + fullWord = true; + } else { + var text = cm.getRange(from, to); + var query = fullWord ? new RegExp("\\b" + text + "\\b") : text; + var cur = cm.getSearchCursor(query, to); + var found = cur.findNext(); + if (!found) { + cur = cm.getSearchCursor(query, Pos(cm.firstLine(), 0)); + found = cur.findNext(); + } + if (!found || isSelectedRange(cm.listSelections(), cur.from(), cur.to())) + return CodeMirror.Pass + cm.addSelection(cur.from(), cur.to()); + } + if (fullWord) + cm.state.sublimeFindFullWord = cm.doc.sel; + }; + + function addCursorToSelection(cm, dir) { + var ranges = cm.listSelections(), newRanges = []; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + var newAnchor = cm.findPosV(range.anchor, dir, "line"); + var newHead = cm.findPosV(range.head, dir, "line"); + var newRange = {anchor: newAnchor, head: newHead}; + newRanges.push(range); + newRanges.push(newRange); + } + cm.setSelections(newRanges); + } + cmds.addCursorToPrevLine = function(cm) { addCursorToSelection(cm, -1); }; + cmds.addCursorToNextLine = function(cm) { addCursorToSelection(cm, 1); }; + + function isSelectedRange(ranges, from, to) { + for (var i = 0; i < ranges.length; i++) + if (ranges[i].from() == from && ranges[i].to() == to) return true + return false + } + + var mirror = "(){}[]"; + function selectBetweenBrackets(cm) { + var ranges = cm.listSelections(), newRanges = [] + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i], pos = range.head, opening = cm.scanForBracket(pos, -1); + if (!opening) return false; + for (;;) { + var closing = cm.scanForBracket(pos, 1); + if (!closing) return false; + 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 true; + } + + cmds.selectScope = function(cm) { + selectBetweenBrackets(cm) || cm.execCommand("selectAll"); + }; + cmds.selectBetweenBrackets = function(cm) { + if (!selectBetweenBrackets(cm)) return CodeMirror.Pass; + }; + + cmds.goToBracket = function(cm) { + cm.extendSelectionsBy(function(range) { + var next = cm.scanForBracket(range.head, 1); + if (next && CodeMirror.cmpPos(next.pos, range.head) != 0) return next.pos; + var prev = cm.scanForBracket(range.head, -1); + return prev && Pos(prev.pos.line, prev.pos.ch + 1) || range.head; + }); + }; + + cmds.swapLineUp = function(cm) { + if (cm.isReadOnly()) return CodeMirror.Pass + var ranges = cm.listSelections(), linesToMove = [], at = cm.firstLine() - 1, newSels = []; + for (var 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)}); + if (range.to().ch == 0 && !range.empty()) --to; + if (from > at) linesToMove.push(from, to); + else if (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]; + var line = cm.getLine(from); + cm.replaceRange("", Pos(from, 0), Pos(from + 1, 0), "+swapLine"); + if (to > cm.lastLine()) + cm.replaceRange("\n" + line, Pos(cm.lastLine()), null, "+swapLine"); + else + cm.replaceRange(line + "\n", Pos(to, 0), null, "+swapLine"); + } + cm.setSelections(newSels); + cm.scrollIntoView(); + }); + }; + + cmds.swapLineDown = function(cm) { + if (cm.isReadOnly()) return CodeMirror.Pass + var ranges = cm.listSelections(), linesToMove = [], at = cm.lastLine() + 1; + for (var i = ranges.length - 1; i >= 0; i--) { + var range = ranges[i], from = range.to().line + 1, to = range.from().line; + if (range.to().ch == 0 && !range.empty()) from--; + if (from < at) linesToMove.push(from, to); + else if (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]; + var line = cm.getLine(from); + if (from == cm.lastLine()) + cm.replaceRange("", Pos(from - 1), Pos(from), "+swapLine"); + else + cm.replaceRange("", Pos(from, 0), Pos(from + 1, 0), "+swapLine"); + cm.replaceRange(line + "\n", Pos(to, 0), null, "+swapLine"); + } + cm.scrollIntoView(); + }); + }; + + cmds.toggleCommentIndented = function(cm) { + cm.toggleComment({ indent: true }); + } + + cmds.joinLines = function(cm) { + var ranges = cm.listSelections(), joined = []; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i], from = range.from(); + var start = from.line, end = range.to().line; + while (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() { + var offset = 0, ranges = []; + for (var i = 0; i < joined.length; i++) { + var obj = joined[i]; + var anchor = obj.anchor && Pos(obj.anchor.line - offset, obj.anchor.ch), head; + for (var line = obj.start; line <= obj.end; line++) { + var actual = line - offset; + if (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.duplicateLine = function(cm) { + cm.operation(function() { + var rangeCount = cm.listSelections().length; + for (var i = 0; i < rangeCount; i++) { + var range = cm.listSelections()[i]; + if (range.empty()) + cm.replaceRange(cm.getLine(range.head.line) + "\n", Pos(range.head.line, 0)); + else + cm.replaceRange(cm.getRange(range.from(), range.to()), range.from()); + } + cm.scrollIntoView(); + }); + }; + + + function sortLines(cm, caseSensitive) { + if (cm.isReadOnly()) return CodeMirror.Pass + var ranges = cm.listSelections(), toSort = [], selected; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (range.empty()) continue; + var from = range.from().line, to = range.to().line; + while (i < ranges.length - 1 && ranges[i + 1].from().line == to) + to = ranges[++i].to().line; + if (!ranges[i].to().ch) to--; + toSort.push(from, to); + } + if (toSort.length) selected = true; + else toSort.push(cm.firstLine(), cm.lastLine()); + + cm.operation(function() { + var ranges = []; + for (var i = 0; i < toSort.length; i += 2) { + var from = toSort[i], to = toSort[i + 1]; + var start = Pos(from, 0), end = Pos(to); + var lines = cm.getRange(start, end, false); + if (caseSensitive) + lines.sort(); + else + 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); + if (selected) ranges.push({anchor: start, head: Pos(to + 1, 0)}); + } + if (selected) cm.setSelections(ranges, 0); + }); + } + + cmds.sortLines = function(cm) { sortLines(cm, true); }; + cmds.sortLinesInsensitive = function(cm) { sortLines(cm, false); }; + + cmds.nextBookmark = function(cm) { + var marks = cm.state.sublimeBookmarks; + if (marks) while (marks.length) { + var current = marks.shift(); + var found = current.find(); + if (found) { + marks.push(current); + return cm.setSelection(found.from, found.to); + } + } + }; + + cmds.prevBookmark = function(cm) { + var marks = cm.state.sublimeBookmarks; + if (marks) while (marks.length) { + marks.unshift(marks.pop()); + var found = marks[marks.length - 1].find(); + if (!found) + marks.pop(); + else + return cm.setSelection(found.from, found.to); + } + }; + + cmds.toggleBookmark = function(cm) { + var ranges = cm.listSelections(); + var marks = cm.state.sublimeBookmarks || (cm.state.sublimeBookmarks = []); + for (var i = 0; i < ranges.length; i++) { + var from = ranges[i].from(), to = ranges[i].to(); + var found = cm.findMarks(from, to); + for (var j = 0; j < found.length; j++) { + if (found[j].sublimeBookmark) { + found[j].clear(); + for (var k = 0; k < marks.length; k++) + if (marks[k] == found[j]) + marks.splice(k--, 1); + break; + } + } + if (j == found.length) + marks.push(cm.markText(from, to, {sublimeBookmark: true, clearWhenEmpty: false})); + } + }; + + cmds.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.selectBookmarks = function(cm) { + var marks = cm.state.sublimeBookmarks, ranges = []; + if (marks) for (var i = 0; i < marks.length; i++) { + var found = marks[i].find(); + if (!found) + marks.splice(i--, 0); + else + ranges.push({anchor: found.from, head: found.to}); + } + if (ranges.length) + cm.setSelections(ranges, 0); + }; + + function modifyWordOrSelection(cm, mod) { + cm.operation(function() { + var ranges = cm.listSelections(), indices = [], replacements = []; + for (var 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 i = indices.length - 1, at; i >= 0; i--) { + var range = ranges[indices[i]]; + if (at && CodeMirror.cmpPos(range.head, at) > 0) continue; + var word = wordAt(cm, range.head); + at = word.from; + cm.replaceRange(mod(word.word), word.from, word.to); + } + }); + } + + cmds.smartBackspace = function(cm) { + if (cm.somethingSelected()) return CodeMirror.Pass; + + cm.operation(function() { + var cursors = cm.listSelections(); + var indentUnit = cm.getOption("indentUnit"); + + for (var i = cursors.length - 1; i >= 0; i--) { + var cursor = cursors[i].head; + var toStartOfLine = cm.getRange({line: cursor.line, ch: 0}, cursor); + var column = CodeMirror.countColumn(toStartOfLine, null, cm.getOption("tabSize")); + + // Delete by one character by default + var deletePos = cm.findPosH(cursor, -1, "char", false); + + if (toStartOfLine && !/\S/.test(toStartOfLine) && column % indentUnit == 0) { + var prevIndent = new Pos(cursor.line, + CodeMirror.findColumn(toStartOfLine, column - indentUnit, indentUnit)); + + // Smart delete only if we found a valid prevIndent location + if (prevIndent.ch != cursor.ch) deletePos = prevIndent; + } + + cm.replaceRange("", deletePos, cursor, "+delete"); + } + }); + }; + + cmds.delLineRight = function(cm) { + cm.operation(function() { + var ranges = cm.listSelections(); + for (var i = ranges.length - 1; i >= 0; i--) + cm.replaceRange("", ranges[i].anchor, Pos(ranges[i].to().line), "+delete"); + cm.scrollIntoView(); + }); + }; + + cmds.upcaseAtCursor = function(cm) { + modifyWordOrSelection(cm, function(str) { return str.toUpperCase(); }); + }; + cmds.downcaseAtCursor = function(cm) { + modifyWordOrSelection(cm, function(str) { return str.toLowerCase(); }); + }; + + cmds.setSublimeMark = function(cm) { + if (cm.state.sublimeMark) cm.state.sublimeMark.clear(); + cm.state.sublimeMark = cm.setBookmark(cm.getCursor()); + }; + cmds.selectToSublimeMark = function(cm) { + var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); + if (found) cm.setSelection(cm.getCursor(), found); + }; + cmds.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.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.sublimeYank = function(cm) { + if (cm.state.sublimeKilled != null) + cm.replaceSelection(cm.state.sublimeKilled, null, "paste"); + }; + + cmds.showInCenter = function(cm) { + var pos = cm.cursorCoords(null, "local"); + cm.scrollTo(null, (pos.top + pos.bottom) / 2 - cm.getScrollInfo().clientHeight / 2); + }; + + cmds.selectLinesUpward = function(cm) { + cm.operation(function() { + var ranges = cm.listSelections(); + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (range.head.line > cm.firstLine()) + cm.addSelection(Pos(range.head.line - 1, range.head.ch)); + } + }); + }; + cmds.selectLinesDownward = function(cm) { + cm.operation(function() { + var ranges = cm.listSelections(); + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (range.head.line < cm.lastLine()) + cm.addSelection(Pos(range.head.line + 1, range.head.ch)); + } + }); + }; + + function getTarget(cm) { + var from = cm.getCursor("from"), to = cm.getCursor("to"); + if (CodeMirror.cmpPos(from, to) == 0) { + 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) return; + var query = target.query; + var 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()))); + if (forward ? cur.findNext() : cur.findPrevious()) + cm.setSelection(cur.from(), cur.to()); + else if (target.word) + cm.setSelection(target.from, target.to); + } + }; + cmds.findUnder = function(cm) { findAndGoTo(cm, true); }; + cmds.findUnderPrevious = function(cm) { findAndGoTo(cm,false); }; + cmds.findAllUnder = function(cm) { + var target = getTarget(cm); + if (!target) return; + var cur = cm.getSearchCursor(target.query); + var matches = []; + var primaryIndex = -1; + while (cur.findNext()) { + matches.push({anchor: cur.from(), head: cur.to()}); + if (cur.from().line <= target.from.line && cur.from().ch <= target.from.ch) + primaryIndex++; + } + cm.setSelections(matches, primaryIndex); + }; + + + var keyMap = CodeMirror.keyMap; + keyMap.macSublime = { + "Cmd-Left": "goLineStartSmart", + "Shift-Tab": "indentLess", + "Shift-Ctrl-K": "deleteLine", + "Alt-Q": "wrapLines", + "Ctrl-Left": "goSubwordLeft", + "Ctrl-Right": "goSubwordRight", + "Ctrl-Alt-Up": "scrollLineUp", + "Ctrl-Alt-Down": "scrollLineDown", + "Cmd-L": "selectLine", + "Shift-Cmd-L": "splitSelectionByLine", + "Esc": "singleSelectionTop", + "Cmd-Enter": "insertLineAfter", + "Shift-Cmd-Enter": "insertLineBefore", + "Cmd-D": "selectNextOccurrence", + "Shift-Cmd-Up": "addCursorToPrevLine", + "Shift-Cmd-Down": "addCursorToNextLine", + "Shift-Cmd-Space": "selectScope", + "Shift-Cmd-M": "selectBetweenBrackets", + "Cmd-M": "goToBracket", + "Cmd-Ctrl-Up": "swapLineUp", + "Cmd-Ctrl-Down": "swapLineDown", + "Cmd-/": "toggleCommentIndented", + "Cmd-J": "joinLines", + "Shift-Cmd-D": "duplicateLine", + "F9": "sortLines", + "Cmd-F9": "sortLinesInsensitive", + "F2": "nextBookmark", + "Shift-F2": "prevBookmark", + "Cmd-F2": "toggleBookmark", + "Shift-Cmd-F2": "clearBookmarks", + "Alt-F2": "selectBookmarks", + "Backspace": "smartBackspace", + "Cmd-K Cmd-K": "delLineRight", + "Cmd-K Cmd-U": "upcaseAtCursor", + "Cmd-K Cmd-L": "downcaseAtCursor", + "Cmd-K Cmd-Space": "setSublimeMark", + "Cmd-K Cmd-A": "selectToSublimeMark", + "Cmd-K Cmd-W": "deleteToSublimeMark", + "Cmd-K Cmd-X": "swapWithSublimeMark", + "Cmd-K Cmd-Y": "sublimeYank", + "Cmd-K Cmd-C": "showInCenter", + "Cmd-K Cmd-G": "clearBookmarks", + "Cmd-K Cmd-Backspace": "delLineLeft", + "Cmd-K Cmd-0": "unfoldAll", + "Cmd-K Cmd-J": "unfoldAll", + "Ctrl-Shift-Up": "selectLinesUpward", + "Ctrl-Shift-Down": "selectLinesDownward", + "Cmd-F3": "findUnder", + "Shift-Cmd-F3": "findUnderPrevious", + "Alt-F3": "findAllUnder", + "Shift-Cmd-[": "fold", + "Shift-Cmd-]": "unfold", + "Cmd-I": "findIncremental", + "Shift-Cmd-I": "findIncrementalReverse", + "Cmd-H": "replace", + "F3": "findNext", + "Shift-F3": "findPrev", + "fallthrough": "macDefault" + }; + CodeMirror.normalizeKeyMap(keyMap.macSublime); + + keyMap.pcSublime = { + "Shift-Tab": "indentLess", + "Shift-Ctrl-K": "deleteLine", + "Alt-Q": "wrapLines", + "Ctrl-T": "transposeChars", + "Alt-Left": "goSubwordLeft", + "Alt-Right": "goSubwordRight", + "Ctrl-Up": "scrollLineUp", + "Ctrl-Down": "scrollLineDown", + "Ctrl-L": "selectLine", + "Shift-Ctrl-L": "splitSelectionByLine", + "Esc": "singleSelectionTop", + "Ctrl-Enter": "insertLineAfter", + "Shift-Ctrl-Enter": "insertLineBefore", + "Ctrl-D": "selectNextOccurrence", + "Alt-CtrlUp": "addCursorToPrevLine", + "Alt-CtrlDown": "addCursorToNextLine", + "Shift-Ctrl-Space": "selectScope", + "Shift-Ctrl-M": "selectBetweenBrackets", + "Ctrl-M": "goToBracket", + "Shift-Ctrl-Up": "swapLineUp", + "Shift-Ctrl-Down": "swapLineDown", + "Ctrl-/": "toggleCommentIndented", + "Ctrl-J": "joinLines", + "Shift-Ctrl-D": "duplicateLine", + "F9": "sortLines", + "Ctrl-F9": "sortLinesInsensitive", + "F2": "nextBookmark", + "Shift-F2": "prevBookmark", + "Ctrl-F2": "toggleBookmark", + "Shift-Ctrl-F2": "clearBookmarks", + "Alt-F2": "selectBookmarks", + "Backspace": "smartBackspace", + "Ctrl-K Ctrl-K": "delLineRight", + "Ctrl-K Ctrl-U": "upcaseAtCursor", + "Ctrl-K Ctrl-L": "downcaseAtCursor", + "Ctrl-K Ctrl-Space": "setSublimeMark", + "Ctrl-K Ctrl-A": "selectToSublimeMark", + "Ctrl-K Ctrl-W": "deleteToSublimeMark", + "Ctrl-K Ctrl-X": "swapWithSublimeMark", + "Ctrl-K Ctrl-Y": "sublimeYank", + "Ctrl-K Ctrl-C": "showInCenter", + "Ctrl-K Ctrl-G": "clearBookmarks", + "Ctrl-K Ctrl-Backspace": "delLineLeft", + "Ctrl-K Ctrl-0": "unfoldAll", + "Ctrl-K Ctrl-J": "unfoldAll", + "Ctrl-Alt-Up": "selectLinesUpward", + "Ctrl-Alt-Down": "selectLinesDownward", + "Ctrl-F3": "findUnder", + "Shift-Ctrl-F3": "findUnderPrevious", + "Alt-F3": "findAllUnder", + "Shift-Ctrl-[": "fold", + "Shift-Ctrl-]": "unfold", + "Ctrl-I": "findIncremental", + "Shift-Ctrl-I": "findIncrementalReverse", + "Ctrl-H": "replace", + "F3": "findNext", + "Shift-F3": "findPrev", + "fallthrough": "pcDefault" + }; + CodeMirror.normalizeKeyMap(keyMap.pcSublime); + + var mac = keyMap.default == keyMap.macDefault; + keyMap.sublime = mac ? keyMap.macSublime : keyMap.pcSublime; +}); diff --git a/modules/editor/codemirror/mode/apl/apl.min.js b/modules/editor/codemirror/mode/apl/apl.min.js @@ -0,0 +1,174 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode("apl", function() { + var builtInOps = { + ".": "innerProduct", + "\\": "scan", + "/": "reduce", + "⌿": "reduce1Axis", + "⍀": "scan1Axis", + "¨": "each", + "⍣": "power" + }; + var builtInFuncs = { + "+": ["conjugate", "add"], + "−": ["negate", "subtract"], + "×": ["signOf", "multiply"], + "÷": ["reciprocal", "divide"], + "⌈": ["ceiling", "greaterOf"], + "⌊": ["floor", "lesserOf"], + "∣": ["absolute", "residue"], + "⍳": ["indexGenerate", "indexOf"], + "?": ["roll", "deal"], + "⋆": ["exponentiate", "toThePowerOf"], + "⍟": ["naturalLog", "logToTheBase"], + "○": ["piTimes", "circularFuncs"], + "!": ["factorial", "binomial"], + "⌹": ["matrixInverse", "matrixDivide"], + "<": [null, "lessThan"], + "≤": [null, "lessThanOrEqual"], + "=": [null, "equals"], + ">": [null, "greaterThan"], + "≥": [null, "greaterThanOrEqual"], + "≠": [null, "notEqual"], + "≡": ["depth", "match"], + "≢": [null, "notMatch"], + "∈": ["enlist", "membership"], + "⍷": [null, "find"], + "∪": ["unique", "union"], + "∩": [null, "intersection"], + "∼": ["not", "without"], + "∨": [null, "or"], + "∧": [null, "and"], + "⍱": [null, "nor"], + "⍲": [null, "nand"], + "⍴": ["shapeOf", "reshape"], + ",": ["ravel", "catenate"], + "⍪": [null, "firstAxisCatenate"], + "⌽": ["reverse", "rotate"], + "⊖": ["axis1Reverse", "axis1Rotate"], + "⍉": ["transpose", null], + "↑": ["first", "take"], + "↓": [null, "drop"], + "⊂": ["enclose", "partitionWithAxis"], + "⊃": ["diclose", "pick"], + "⌷": [null, "index"], + "⍋": ["gradeUp", null], + "⍒": ["gradeDown", null], + "⊤": ["encode", null], + "⊥": ["decode", null], + "⍕": ["format", "formatByExample"], + "⍎": ["execute", null], + "⊣": ["stop", "left"], + "⊢": ["pass", "right"] + }; + + var isOperator = /[\.\/⌿⍀¨⍣]/; + var isNiladic = /⍬/; + var isFunction = /[\+−×÷⌈⌊∣⍳\?⋆⍟○!⌹<≤=>≥≠≡≢∈⍷∪∩∼∨∧⍱⍲⍴,⍪⌽⊖⍉↑↓⊂⊃⌷⍋⍒⊤⊥⍕⍎⊣⊢]/; + var isArrow = /←/; + var isComment = /[⍝#].*$/; + + var stringEater = function(type) { + var prev; + prev = false; + return function(c) { + prev = c; + if (c === type) { + return prev === "\\"; + } + return true; + }; + }; + return { + startState: function() { + return { + prev: false, + func: false, + op: false, + string: false, + escape: false + }; + }, + token: function(stream, state) { + var ch, funcName; + if (stream.eatSpace()) { + return null; + } + ch = stream.next(); + if (ch === '"' || ch === "'") { + stream.eatWhile(stringEater(ch)); + stream.next(); + state.prev = true; + return "string"; + } + if (/[\[{\(]/.test(ch)) { + state.prev = false; + return null; + } + if (/[\]}\)]/.test(ch)) { + state.prev = true; + return null; + } + if (isNiladic.test(ch)) { + state.prev = false; + return "niladic"; + } + if (/[¯\d]/.test(ch)) { + if (state.func) { + state.func = false; + state.prev = false; + } else { + state.prev = true; + } + stream.eatWhile(/[\w\.]/); + return "number"; + } + if (isOperator.test(ch)) { + return "operator apl-" + builtInOps[ch]; + } + if (isArrow.test(ch)) { + return "apl-arrow"; + } + if (isFunction.test(ch)) { + funcName = "apl-"; + if (builtInFuncs[ch] != null) { + if (state.prev) { + funcName += builtInFuncs[ch][1]; + } else { + funcName += builtInFuncs[ch][0]; + } + } + state.func = true; + state.prev = false; + return "function " + funcName; + } + if (isComment.test(ch)) { + stream.skipToEnd(); + return "comment"; + } + if (ch === "∘" && stream.peek() === ".") { + stream.next(); + return "function jot-dot"; + } + stream.eatWhile(/[\w\$_]/); + state.prev = true; + return "keyword"; + } + }; +}); + +CodeMirror.defineMIME("text/apl", "apl"); + +}); diff --git a/modules/editor/codemirror/mode/asterisk/asterisk.min.js b/modules/editor/codemirror/mode/asterisk/asterisk.min.js @@ -0,0 +1,196 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +/* + * ===================================================================================== + * + * Filename: mode/asterisk/asterisk.js + * + * Description: CodeMirror mode for Asterisk dialplan + * + * Created: 05/17/2012 09:20:25 PM + * Revision: none + * + * Author: Stas Kobzar (stas@modulis.ca), + * Company: Modulis.ca Inc. + * + * ===================================================================================== + */ + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode("asterisk", function() { + var atoms = ["exten", "same", "include","ignorepat","switch"], + dpcmd = ["#include","#exec"], + apps = [ + "addqueuemember","adsiprog","aelsub","agentlogin","agentmonitoroutgoing","agi", + "alarmreceiver","amd","answer","authenticate","background","backgrounddetect", + "bridge","busy","callcompletioncancel","callcompletionrequest","celgenuserevent", + "changemonitor","chanisavail","channelredirect","chanspy","clearhash","confbridge", + "congestion","continuewhile","controlplayback","dahdiacceptr2call","dahdibarge", + "dahdiras","dahdiscan","dahdisendcallreroutingfacility","dahdisendkeypadfacility", + "datetime","dbdel","dbdeltree","deadagi","dial","dictate","directory","disa", + "dumpchan","eagi","echo","endwhile","exec","execif","execiftime","exitwhile","extenspy", + "externalivr","festival","flash","followme","forkcdr","getcpeid","gosub","gosubif", + "goto","gotoif","gotoiftime","hangup","iax2provision","ices","importvar","incomplete", + "ivrdemo","jabberjoin","jabberleave","jabbersend","jabbersendgroup","jabberstatus", + "jack","log","macro","macroexclusive","macroexit","macroif","mailboxexists","meetme", + "meetmeadmin","meetmechanneladmin","meetmecount","milliwatt","minivmaccmess","minivmdelete", + "minivmgreet","minivmmwi","minivmnotify","minivmrecord","mixmonitor","monitor","morsecode", + "mp3player","mset","musiconhold","nbscat","nocdr","noop","odbc","odbc","odbcfinish", + "originate","ospauth","ospfinish","osplookup","ospnext","page","park","parkandannounce", + "parkedcall","pausemonitor","pausequeuemember","pickup","pickupchan","playback","playtones", + "privacymanager","proceeding","progress","queue","queuelog","raiseexception","read","readexten", + "readfile","receivefax","receivefax","receivefax","record","removequeuemember", + "resetcdr","retrydial","return","ringing","sayalpha","saycountedadj","saycountednoun", + "saycountpl","saydigits","saynumber","sayphonetic","sayunixtime","senddtmf","sendfax", + "sendfax","sendfax","sendimage","sendtext","sendurl","set","setamaflags", + "setcallerpres","setmusiconhold","sipaddheader","sipdtmfmode","sipremoveheader","skel", + "slastation","slatrunk","sms","softhangup","speechactivategrammar","speechbackground", + "speechcreate","speechdeactivategrammar","speechdestroy","speechloadgrammar","speechprocessingsound", + "speechstart","speechunloadgrammar","stackpop","startmusiconhold","stopmixmonitor","stopmonitor", + "stopmusiconhold","stopplaytones","system","testclient","testserver","transfer","tryexec", + "trysystem","unpausemonitor","unpausequeuemember","userevent","verbose","vmauthenticate", + "vmsayname","voicemail","voicemailmain","wait","waitexten","waitfornoise","waitforring", + "waitforsilence","waitmusiconhold","waituntil","while","zapateller" + ]; + + function basicToken(stream,state){ + var cur = ''; + var ch = stream.next(); + // comment + if(ch == ";") { + stream.skipToEnd(); + return "comment"; + } + // context + if(ch == '[') { + stream.skipTo(']'); + stream.eat(']'); + return "header"; + } + // string + if(ch == '"') { + stream.skipTo('"'); + return "string"; + } + if(ch == "'") { + stream.skipTo("'"); + return "string-2"; + } + // dialplan commands + if(ch == '#') { + stream.eatWhile(/\w/); + cur = stream.current(); + if(dpcmd.indexOf(cur) !== -1) { + stream.skipToEnd(); + return "strong"; + } + } + // application args + if(ch == '$'){ + var ch1 = stream.peek(); + if(ch1 == '{'){ + stream.skipTo('}'); + stream.eat('}'); + return "variable-3"; + } + } + // extension + stream.eatWhile(/\w/); + cur = stream.current(); + if(atoms.indexOf(cur) !== -1) { + state.extenStart = true; + switch(cur) { + case 'same': state.extenSame = true; break; + case 'include': + case 'switch': + case 'ignorepat': + state.extenInclude = true;break; + default:break; + } + return "atom"; + } + } + + return { + startState: function() { + return { + extenStart: false, + extenSame: false, + extenInclude: false, + extenExten: false, + extenPriority: false, + extenApplication: false + }; + }, + token: function(stream, state) { + + var cur = ''; + if(stream.eatSpace()) return null; + // extension started + if(state.extenStart){ + stream.eatWhile(/[^\s]/); + cur = stream.current(); + if(/^=>?$/.test(cur)){ + state.extenExten = true; + state.extenStart = false; + return "strong"; + } else { + state.extenStart = false; + stream.skipToEnd(); + return "error"; + } + } else if(state.extenExten) { + // set exten and priority + state.extenExten = false; + state.extenPriority = true; + stream.eatWhile(/[^,]/); + if(state.extenInclude) { + stream.skipToEnd(); + state.extenPriority = false; + state.extenInclude = false; + } + if(state.extenSame) { + state.extenPriority = false; + state.extenSame = false; + state.extenApplication = true; + } + return "tag"; + } else if(state.extenPriority) { + state.extenPriority = false; + state.extenApplication = true; + stream.next(); // get comma + if(state.extenSame) return null; + stream.eatWhile(/[^,]/); + return "number"; + } else if(state.extenApplication) { + stream.eatWhile(/,/); + cur = stream.current(); + if(cur === ',') return null; + stream.eatWhile(/\w/); + cur = stream.current().toLowerCase(); + state.extenApplication = false; + if(apps.indexOf(cur) !== -1){ + return "def strong"; + } + } else{ + return basicToken(stream,state); + } + + return null; + } + }; +}); + +CodeMirror.defineMIME("text/x-asterisk", "asterisk"); + +}); diff --git a/modules/editor/codemirror/mode/clike/clike.min.js b/modules/editor/codemirror/mode/clike/clike.min.js @@ -0,0 +1,790 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +function Context(indented, column, type, info, align, prev) { + this.indented = indented; + this.column = column; + this.type = type; + this.info = info; + this.align = align; + this.prev = prev; +} +function pushContext(state, col, type, info) { + var indent = state.indented; + if (state.context && state.context.type == "statement" && type != "statement") + indent = state.context.indented; + return state.context = new Context(indent, col, type, info, null, state.context); +} +function popContext(state) { + var t = state.context.type; + if (t == ")" || t == "]" || t == "}") + state.indented = state.context.indented; + return state.context = state.context.prev; +} + +function typeBefore(stream, state, pos) { + if (state.prevToken == "variable" || state.prevToken == "type") return true; + if (/\S(?:[^- ]>|[*\]])\s*$|\*$/.test(stream.string.slice(0, pos))) return true; + if (state.typeAtEndOfLine && stream.column() == stream.indentation()) return true; +} + +function isTopScope(context) { + for (;;) { + if (!context || context.type == "top") return true; + if (context.type == "}" && context.prev.info != "namespace") return false; + context = context.prev; + } +} + +CodeMirror.defineMode("clike", function(config, parserConfig) { + var indentUnit = config.indentUnit, + statementIndentUnit = parserConfig.statementIndentUnit || indentUnit, + dontAlignCalls = parserConfig.dontAlignCalls, + keywords = parserConfig.keywords || {}, + types = parserConfig.types || {}, + builtin = parserConfig.builtin || {}, + blockKeywords = parserConfig.blockKeywords || {}, + defKeywords = parserConfig.defKeywords || {}, + atoms = parserConfig.atoms || {}, + hooks = parserConfig.hooks || {}, + multiLineStrings = parserConfig.multiLineStrings, + indentStatements = parserConfig.indentStatements !== false, + indentSwitch = parserConfig.indentSwitch !== false, + namespaceSeparator = parserConfig.namespaceSeparator, + isPunctuationChar = parserConfig.isPunctuationChar || /[\[\]{}\(\),;\:\.]/, + numberStart = parserConfig.numberStart || /[\d\.]/, + number = parserConfig.number || /^(?:0x[a-f\d]+|0b[01]+|(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)(u|ll?|l|f)?/i, + isOperatorChar = parserConfig.isOperatorChar || /[+\-*&%=<>!?|\/]/, + isIdentifierChar = parserConfig.isIdentifierChar || /[\w\$_\xa1-\uffff]/; + + var curPunc, isDefKeyword; + + function tokenBase(stream, state) { + var ch = stream.next(); + if (hooks[ch]) { + var result = hooks[ch](stream, state); + if (result !== false) return result; + } + if (ch == '"' || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } + if (isPunctuationChar.test(ch)) { + curPunc = ch; + return null; + } + if (numberStart.test(ch)) { + stream.backUp(1) + if (stream.match(number)) return "number" + stream.next() + } + if (ch == "/") { + if (stream.eat("*")) { + state.tokenize = tokenComment; + return tokenComment(stream, state); + } + if (stream.eat("/")) { + stream.skipToEnd(); + return "comment"; + } + } + if (isOperatorChar.test(ch)) { + while (!stream.match(/^\/[\/*]/, false) && stream.eat(isOperatorChar)) {} + return "operator"; + } + stream.eatWhile(isIdentifierChar); + if (namespaceSeparator) while (stream.match(namespaceSeparator)) + stream.eatWhile(isIdentifierChar); + + var cur = stream.current(); + if (contains(keywords, cur)) { + if (contains(blockKeywords, cur)) curPunc = "newstatement"; + if (contains(defKeywords, cur)) isDefKeyword = true; + return "keyword"; + } + if (contains(types, cur)) return "type"; + if (contains(builtin, cur)) { + if (contains(blockKeywords, cur)) curPunc = "newstatement"; + return "builtin"; + } + if (contains(atoms, cur)) return "atom"; + return "variable"; + } + + function tokenString(quote) { + return function(stream, state) { + var escaped = false, next, end = false; + while ((next = stream.next()) != null) { + if (next == quote && !escaped) {end = true; break;} + escaped = !escaped && next == "\\"; + } + if (end || !(escaped || multiLineStrings)) + state.tokenize = null; + return "string"; + }; + } + + function tokenComment(stream, state) { + var maybeEnd = false, ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize = null; + break; + } + maybeEnd = (ch == "*"); + } + return "comment"; + } + + function maybeEOL(stream, state) { + if (parserConfig.typeFirstDefinitions && stream.eol() && isTopScope(state.context)) + state.typeAtEndOfLine = typeBefore(stream, state, stream.pos) + } + + // Interface + + return { + startState: function(basecolumn) { + return { + tokenize: null, + context: new Context((basecolumn || 0) - indentUnit, 0, "top", null, false), + indented: 0, + startOfLine: true, + prevToken: null + }; + }, + + token: function(stream, state) { + var ctx = state.context; + if (stream.sol()) { + if (ctx.align == null) ctx.align = false; + state.indented = stream.indentation(); + state.startOfLine = true; + } + if (stream.eatSpace()) { maybeEOL(stream, state); return null; } + curPunc = isDefKeyword = null; + var style = (state.tokenize || tokenBase)(stream, state); + if (style == "comment" || style == "meta") return style; + if (ctx.align == null) ctx.align = true; + + if (curPunc == ";" || curPunc == ":" || (curPunc == "," && stream.match(/^\s*(?:\/\/.*)?$/, false))) + while (state.context.type == "statement") popContext(state); + else if (curPunc == "{") pushContext(state, stream.column(), "}"); + else if (curPunc == "[") pushContext(state, stream.column(), "]"); + else if (curPunc == "(") pushContext(state, stream.column(), ")"); + else if (curPunc == "}") { + while (ctx.type == "statement") ctx = popContext(state); + if (ctx.type == "}") ctx = popContext(state); + while (ctx.type == "statement") ctx = popContext(state); + } + else if (curPunc == ctx.type) popContext(state); + else if (indentStatements && + (((ctx.type == "}" || ctx.type == "top") && curPunc != ";") || + (ctx.type == "statement" && curPunc == "newstatement"))) { + pushContext(state, stream.column(), "statement", stream.current()); + } + + if (style == "variable" && + ((state.prevToken == "def" || + (parserConfig.typeFirstDefinitions && typeBefore(stream, state, stream.start) && + isTopScope(state.context) && stream.match(/^\s*\(/, false))))) + style = "def"; + + if (hooks.token) { + var result = hooks.token(stream, state, style); + if (result !== undefined) style = result; + } + + if (style == "def" && parserConfig.styleDefs === false) style = "variable"; + + state.startOfLine = false; + state.prevToken = isDefKeyword ? "def" : style || curPunc; + maybeEOL(stream, state); + return style; + }, + + indent: function(state, textAfter) { + if (state.tokenize != tokenBase && state.tokenize != null || state.typeAtEndOfLine) return CodeMirror.Pass; + var ctx = state.context, firstChar = textAfter && textAfter.charAt(0); + if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev; + if (parserConfig.dontIndentStatements) + while (ctx.type == "statement" && parserConfig.dontIndentStatements.test(ctx.info)) + ctx = ctx.prev + if (hooks.indent) { + var hook = hooks.indent(state, ctx, textAfter); + if (typeof hook == "number") return hook + } + var closing = firstChar == ctx.type; + var switchBlock = ctx.prev && ctx.prev.info == "switch"; + if (parserConfig.allmanIndentation && /[{(]/.test(firstChar)) { + while (ctx.type != "top" && ctx.type != "}") ctx = ctx.prev + return ctx.indented + } + if (ctx.type == "statement") + return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit); + if (ctx.align && (!dontAlignCalls || ctx.type != ")")) + return ctx.column + (closing ? 0 : 1); + if (ctx.type == ")" && !closing) + return ctx.indented + statementIndentUnit; + + return ctx.indented + (closing ? 0 : indentUnit) + + (!closing && switchBlock && !/^(?:case|default)\b/.test(textAfter) ? indentUnit : 0); + }, + + electricInput: indentSwitch ? /^\s*(?:case .*?:|default:|\{\}?|\})$/ : /^\s*[{}]$/, + blockCommentStart: "/*", + blockCommentEnd: "*/", + blockCommentContinue: " * ", + lineComment: "//", + fold: "brace" + }; +}); + + function words(str) { + var obj = {}, words = str.split(" "); + for (var i = 0; i < words.length; ++i) obj[words[i]] = true; + return obj; + } + function contains(words, word) { + if (typeof words === "function") { + return words(word); + } else { + return words.propertyIsEnumerable(word); + } + } + var cKeywords = "auto if break case register continue return default do sizeof " + + "static else struct switch extern typedef union for goto while enum const volatile"; + var cTypes = "int long char short double float unsigned signed void size_t ptrdiff_t"; + + function cppHook(stream, state) { + if (!state.startOfLine) return false + for (var ch, next = null; ch = stream.peek();) { + if (ch == "\\" && stream.match(/^.$/)) { + next = cppHook + break + } else if (ch == "/" && stream.match(/^\/[\/\*]/, false)) { + break + } + stream.next() + } + state.tokenize = next + return "meta" + } + + function pointerHook(_stream, state) { + if (state.prevToken == "type") return "type"; + return false; + } + + function cpp14Literal(stream) { + stream.eatWhile(/[\w\.']/); + return "number"; + } + + function cpp11StringHook(stream, state) { + stream.backUp(1); + // Raw strings. + if (stream.match(/(R|u8R|uR|UR|LR)/)) { + var match = stream.match(/"([^\s\\()]{0,16})\(/); + if (!match) { + return false; + } + state.cpp11RawStringDelim = match[1]; + state.tokenize = tokenRawString; + return tokenRawString(stream, state); + } + // Unicode strings/chars. + if (stream.match(/(u8|u|U|L)/)) { + if (stream.match(/["']/, /* eat */ false)) { + return "string"; + } + return false; + } + // Ignore this hook. + stream.next(); + return false; + } + + function cppLooksLikeConstructor(word) { + var lastTwo = /(\w+)::~?(\w+)$/.exec(word); + return lastTwo && lastTwo[1] == lastTwo[2]; + } + + // C#-style strings where "" escapes a quote. + function tokenAtString(stream, state) { + var next; + while ((next = stream.next()) != null) { + if (next == '"' && !stream.eat('"')) { + state.tokenize = null; + break; + } + } + return "string"; + } + + // C++11 raw string literal is <prefix>"<delim>( anything )<delim>", where + // <delim> can be a string up to 16 characters long. + function tokenRawString(stream, state) { + // Escape characters that have special regex meanings. + var delim = state.cpp11RawStringDelim.replace(/[^\w\s]/g, '\\$&'); + var match = stream.match(new RegExp(".*?\\)" + delim + '"')); + if (match) + state.tokenize = null; + else + stream.skipToEnd(); + return "string"; + } + + function def(mimes, mode) { + if (typeof mimes == "string") mimes = [mimes]; + var words = []; + function add(obj) { + if (obj) for (var prop in obj) if (obj.hasOwnProperty(prop)) + words.push(prop); + } + add(mode.keywords); + add(mode.types); + add(mode.builtin); + add(mode.atoms); + if (words.length) { + mode.helperType = mimes[0]; + CodeMirror.registerHelper("hintWords", mimes[0], words); + } + + for (var i = 0; i < mimes.length; ++i) + CodeMirror.defineMIME(mimes[i], mode); + } + + def(["text/x-csrc", "text/x-c", "text/x-chdr"], { + name: "clike", + keywords: words(cKeywords), + types: words(cTypes + " bool _Complex _Bool float_t double_t intptr_t intmax_t " + + "int8_t int16_t int32_t int64_t uintptr_t uintmax_t uint8_t uint16_t " + + "uint32_t uint64_t"), + blockKeywords: words("case do else for if switch while struct"), + defKeywords: words("struct"), + typeFirstDefinitions: true, + atoms: words("null true false"), + hooks: {"#": cppHook, "*": pointerHook}, + modeProps: {fold: ["brace", "include"]} + }); + + def(["text/x-c++src", "text/x-c++hdr"], { + name: "clike", + keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try explicit new " + + "static_cast typeid catch operator template typename class friend private " + + "this using const_cast inline public throw virtual delete mutable protected " + + "alignas alignof constexpr decltype nullptr noexcept thread_local final " + + "static_assert override"), + types: words(cTypes + " bool wchar_t"), + blockKeywords: words("catch class do else finally for if struct switch try while"), + defKeywords: words("class namespace struct enum union"), + typeFirstDefinitions: true, + atoms: words("true false null"), + dontIndentStatements: /^template$/, + isIdentifierChar: /[\w\$_~\xa1-\uffff]/, + hooks: { + "#": cppHook, + "*": pointerHook, + "u": cpp11StringHook, + "U": cpp11StringHook, + "L": cpp11StringHook, + "R": cpp11StringHook, + "0": cpp14Literal, + "1": cpp14Literal, + "2": cpp14Literal, + "3": cpp14Literal, + "4": cpp14Literal, + "5": cpp14Literal, + "6": cpp14Literal, + "7": cpp14Literal, + "8": cpp14Literal, + "9": cpp14Literal, + token: function(stream, state, style) { + if (style == "variable" && stream.peek() == "(" && + (state.prevToken == ";" || state.prevToken == null || + state.prevToken == "}") && + cppLooksLikeConstructor(stream.current())) + return "def"; + } + }, + namespaceSeparator: "::", + modeProps: {fold: ["brace", "include"]} + }); + + def("text/x-java", { + name: "clike", + keywords: words("abstract assert break case catch class const continue default " + + "do else enum extends final finally float for goto if implements import " + + "instanceof interface native new package private protected public " + + "return static strictfp super switch synchronized this throw throws transient " + + "try volatile while @interface"), + types: words("byte short int long float double boolean char void Boolean Byte Character Double Float " + + "Integer Long Number Object Short String StringBuffer StringBuilder Void"), + blockKeywords: words("catch class do else finally for if switch try while"), + defKeywords: words("class interface enum @interface"), + typeFirstDefinitions: true, + atoms: words("true false null"), + number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+\.?\d*|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i, + hooks: { + "@": function(stream) { + // Don't match the @interface keyword. + if (stream.match('interface', false)) return false; + + stream.eatWhile(/[\w\$_]/); + return "meta"; + } + }, + modeProps: {fold: ["brace", "import"]} + }); + + def("text/x-csharp", { + name: "clike", + keywords: words("abstract as async await base break case catch checked class const continue" + + " default delegate do else enum event explicit extern finally fixed for" + + " foreach goto if implicit in interface internal is lock namespace new" + + " operator out override params private protected public readonly ref return sealed" + + " sizeof stackalloc static struct switch this throw try typeof unchecked" + + " unsafe using virtual void volatile while add alias ascending descending dynamic from get" + + " global group into join let orderby partial remove select set value var yield"), + types: words("Action Boolean Byte Char DateTime DateTimeOffset Decimal Double Func" + + " Guid Int16 Int32 Int64 Object SByte Single String Task TimeSpan UInt16 UInt32" + + " UInt64 bool byte char decimal double short int long object" + + " sbyte float string ushort uint ulong"), + blockKeywords: words("catch class do else finally for foreach if struct switch try while"), + defKeywords: words("class interface namespace struct var"), + typeFirstDefinitions: true, + atoms: words("true false null"), + hooks: { + "@": function(stream, state) { + if (stream.eat('"')) { + state.tokenize = tokenAtString; + return tokenAtString(stream, state); + } + stream.eatWhile(/[\w\$_]/); + return "meta"; + } + } + }); + + function tokenTripleString(stream, state) { + var escaped = false; + while (!stream.eol()) { + if (!escaped && stream.match('"""')) { + state.tokenize = null; + break; + } + escaped = stream.next() == "\\" && !escaped; + } + return "string"; + } + + def("text/x-scala", { + name: "clike", + keywords: words( + + /* scala */ + "abstract case catch class def do else extends final finally for forSome if " + + "implicit import lazy match new null object override package private protected return " + + "sealed super this throw trait try type val var while with yield _ " + + + /* package scala */ + "assert assume require print println printf readLine readBoolean readByte readShort " + + "readChar readInt readLong readFloat readDouble" + ), + types: words( + "AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " + + "Enumeration Equiv Error Exception Fractional Function IndexedSeq Int Integral Iterable " + + "Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " + + "Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " + + "StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector " + + + /* package java.lang */ + "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " + + "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " + + "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " + + "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void" + ), + multiLineStrings: true, + blockKeywords: words("catch class enum do else finally for forSome if match switch try while"), + defKeywords: words("class enum def object package trait type val var"), + atoms: words("true false null"), + indentStatements: false, + indentSwitch: false, + isOperatorChar: /[+\-*&%=<>!?|\/#:@]/, + hooks: { + "@": function(stream) { + stream.eatWhile(/[\w\$_]/); + return "meta"; + }, + '"': function(stream, state) { + if (!stream.match('""')) return false; + state.tokenize = tokenTripleString; + return state.tokenize(stream, state); + }, + "'": function(stream) { + stream.eatWhile(/[\w\$_\xa1-\uffff]/); + return "atom"; + }, + "=": function(stream, state) { + var cx = state.context + if (cx.type == "}" && cx.align && stream.eat(">")) { + state.context = new Context(cx.indented, cx.column, cx.type, cx.info, null, cx.prev) + return "operator" + } else { + return false + } + } + }, + modeProps: {closeBrackets: {triples: '"'}} + }); + + function tokenKotlinString(tripleString){ + return function (stream, state) { + var escaped = false, next, end = false; + while (!stream.eol()) { + if (!tripleString && !escaped && stream.match('"') ) {end = true; break;} + if (tripleString && stream.match('"""')) {end = true; break;} + next = stream.next(); + if(!escaped && next == "$" && stream.match('{')) + stream.skipTo("}"); + escaped = !escaped && next == "\\" && !tripleString; + } + if (end || !tripleString) + state.tokenize = null; + return "string"; + } + } + + def("text/x-kotlin", { + name: "clike", + keywords: words( + /*keywords*/ + "package as typealias class interface this super val " + + "var fun for is in This throw return " + + "break continue object if else while do try when !in !is as? " + + + /*soft keywords*/ + "file import where by get set abstract enum open inner override private public internal " + + "protected catch finally out final vararg reified dynamic companion constructor init " + + "sealed field property receiver param sparam lateinit data inline noinline tailrec " + + "external annotation crossinline const operator infix suspend" + ), + types: words( + /* package java.lang */ + "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " + + "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " + + "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " + + "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void" + ), + intendSwitch: false, + indentStatements: false, + multiLineStrings: true, + number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+\.?\d*|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i, + blockKeywords: words("catch class do else finally for if where try while enum"), + defKeywords: words("class val var object interface fun"), + atoms: words("true false null this"), + hooks: { + '"': function(stream, state) { + state.tokenize = tokenKotlinString(stream.match('""')); + return state.tokenize(stream, state); + } + }, + modeProps: {closeBrackets: {triples: '"'}} + }); + + def(["x-shader/x-vertex", "x-shader/x-fragment"], { + name: "clike", + keywords: words("sampler1D sampler2D sampler3D samplerCube " + + "sampler1DShadow sampler2DShadow " + + "const attribute uniform varying " + + "break continue discard return " + + "for while do if else struct " + + "in out inout"), + types: words("float int bool void " + + "vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 " + + "mat2 mat3 mat4"), + blockKeywords: words("for while do if else struct"), + builtin: words("radians degrees sin cos tan asin acos atan " + + "pow exp log exp2 sqrt inversesqrt " + + "abs sign floor ceil fract mod min max clamp mix step smoothstep " + + "length distance dot cross normalize ftransform faceforward " + + "reflect refract matrixCompMult " + + "lessThan lessThanEqual greaterThan greaterThanEqual " + + "equal notEqual any all not " + + "texture1D texture1DProj texture1DLod texture1DProjLod " + + "texture2D texture2DProj texture2DLod texture2DProjLod " + + "texture3D texture3DProj texture3DLod texture3DProjLod " + + "textureCube textureCubeLod " + + "shadow1D shadow2D shadow1DProj shadow2DProj " + + "shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod " + + "dFdx dFdy fwidth " + + "noise1 noise2 noise3 noise4"), + atoms: words("true false " + + "gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex " + + "gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 " + + "gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 " + + "gl_FogCoord gl_PointCoord " + + "gl_Position gl_PointSize gl_ClipVertex " + + "gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor " + + "gl_TexCoord gl_FogFragCoord " + + "gl_FragCoord gl_FrontFacing " + + "gl_FragData gl_FragDepth " + + "gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix " + + "gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse " + + "gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse " + + "gl_TexureMatrixTranspose gl_ModelViewMatrixInverseTranspose " + + "gl_ProjectionMatrixInverseTranspose " + + "gl_ModelViewProjectionMatrixInverseTranspose " + + "gl_TextureMatrixInverseTranspose " + + "gl_NormalScale gl_DepthRange gl_ClipPlane " + + "gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel " + + "gl_FrontLightModelProduct gl_BackLightModelProduct " + + "gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ " + + "gl_FogParameters " + + "gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords " + + "gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats " + + "gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits " + + "gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits " + + "gl_MaxDrawBuffers"), + indentSwitch: false, + hooks: {"#": cppHook}, + modeProps: {fold: ["brace", "include"]} + }); + + def("text/x-nesc", { + name: "clike", + keywords: words(cKeywords + "as atomic async call command component components configuration event generic " + + "implementation includes interface module new norace nx_struct nx_union post provides " + + "signal task uses abstract extends"), + types: words(cTypes), + blockKeywords: words("case do else for if switch while struct"), + atoms: words("null true false"), + hooks: {"#": cppHook}, + modeProps: {fold: ["brace", "include"]} + }); + + def("text/x-objectivec", { + name: "clike", + keywords: words(cKeywords + "inline restrict _Bool _Complex _Imaginary BOOL Class bycopy byref id IMP in " + + "inout nil oneway out Protocol SEL self super atomic nonatomic retain copy readwrite readonly"), + types: words(cTypes), + atoms: words("YES NO NULL NILL ON OFF true false"), + hooks: { + "@": function(stream) { + stream.eatWhile(/[\w\$]/); + return "keyword"; + }, + "#": cppHook, + indent: function(_state, ctx, textAfter) { + if (ctx.type == "statement" && /^@\w/.test(textAfter)) return ctx.indented + } + }, + modeProps: {fold: "brace"} + }); + + def("text/x-squirrel", { + name: "clike", + keywords: words("base break clone continue const default delete enum extends function in class" + + " foreach local resume return this throw typeof yield constructor instanceof static"), + types: words(cTypes), + blockKeywords: words("case catch class else for foreach if switch try while"), + defKeywords: words("function local class"), + typeFirstDefinitions: true, + atoms: words("true false null"), + hooks: {"#": cppHook}, + modeProps: {fold: ["brace", "include"]} + }); + + // Ceylon Strings need to deal with interpolation + var stringTokenizer = null; + function tokenCeylonString(type) { + return function(stream, state) { + var escaped = false, next, end = false; + while (!stream.eol()) { + if (!escaped && stream.match('"') && + (type == "single" || stream.match('""'))) { + end = true; + break; + } + if (!escaped && stream.match('``')) { + stringTokenizer = tokenCeylonString(type); + end = true; + break; + } + next = stream.next(); + escaped = type == "single" && !escaped && next == "\\"; + } + if (end) + state.tokenize = null; + return "string"; + } + } + + def("text/x-ceylon", { + name: "clike", + keywords: words("abstracts alias assembly assert assign break case catch class continue dynamic else" + + " exists extends finally for function given if import in interface is let module new" + + " nonempty object of out outer package return satisfies super switch then this throw" + + " try value void while"), + types: function(word) { + // In Ceylon all identifiers that start with an uppercase are types + var first = word.charAt(0); + return (first === first.toUpperCase() && first !== first.toLowerCase()); + }, + blockKeywords: words("case catch class dynamic else finally for function if interface module new object switch try while"), + defKeywords: words("class dynamic function interface module object package value"), + builtin: words("abstract actual aliased annotation by default deprecated doc final formal late license" + + " native optional sealed see serializable shared suppressWarnings tagged throws variable"), + isPunctuationChar: /[\[\]{}\(\),;\:\.`]/, + isOperatorChar: /[+\-*&%=<>!?|^~:\/]/, + numberStart: /[\d#$]/, + number: /^(?:#[\da-fA-F_]+|\$[01_]+|[\d_]+[kMGTPmunpf]?|[\d_]+\.[\d_]+(?:[eE][-+]?\d+|[kMGTPmunpf]|)|)/i, + multiLineStrings: true, + typeFirstDefinitions: true, + atoms: words("true false null larger smaller equal empty finished"), + indentSwitch: false, + styleDefs: false, + hooks: { + "@": function(stream) { + stream.eatWhile(/[\w\$_]/); + return "meta"; + }, + '"': function(stream, state) { + state.tokenize = tokenCeylonString(stream.match('""') ? "triple" : "single"); + return state.tokenize(stream, state); + }, + '`': function(stream, state) { + if (!stringTokenizer || !stream.match('`')) return false; + state.tokenize = stringTokenizer; + stringTokenizer = null; + return state.tokenize(stream, state); + }, + "'": function(stream) { + stream.eatWhile(/[\w\$_\xa1-\uffff]/); + return "atom"; + }, + token: function(_stream, state, style) { + if ((style == "variable" || style == "type") && + state.prevToken == ".") { + return "variable-2"; + } + } + }, + modeProps: { + fold: ["brace", "import"], + closeBrackets: {triples: '"'} + } + }); + +}); diff --git a/modules/editor/codemirror/mode/clike/test.min.js b/modules/editor/codemirror/mode/clike/test.min.js @@ -0,0 +1,59 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function() { + var mode = CodeMirror.getMode({indentUnit: 2}, "text/x-c"); + function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } + + MT("indent", + "[type void] [def foo]([type void*] [variable a], [type int] [variable b]) {", + " [type int] [variable c] [operator =] [variable b] [operator +]", + " [number 1];", + " [keyword return] [operator *][variable a];", + "}"); + + MT("indent_switch", + "[keyword switch] ([variable x]) {", + " [keyword case] [number 10]:", + " [keyword return] [number 20];", + " [keyword default]:", + " [variable printf]([string \"foo %c\"], [variable x]);", + "}"); + + MT("def", + "[type void] [def foo]() {}", + "[keyword struct] [def bar]{}", + "[type int] [type *][def baz]() {}"); + + MT("def_new_line", + "::[variable std]::[variable SomeTerribleType][operator <][variable T][operator >]", + "[def SomeLongMethodNameThatDoesntFitIntoOneLine]([keyword const] [variable MyType][operator &] [variable param]) {}") + + MT("double_block", + "[keyword for] (;;)", + " [keyword for] (;;)", + " [variable x][operator ++];", + "[keyword return];"); + + MT("preprocessor", + "[meta #define FOO 3]", + "[type int] [variable foo];", + "[meta #define BAR\\]", + "[meta 4]", + "[type unsigned] [type int] [variable bar] [operator =] [number 8];", + "[meta #include <baz> ][comment // comment]") + + + var mode_cpp = CodeMirror.getMode({indentUnit: 2}, "text/x-c++src"); + function MTCPP(name) { test.mode(name, mode_cpp, Array.prototype.slice.call(arguments, 1)); } + + MTCPP("cpp14_literal", + "[number 10'000];", + "[number 0b10'000];", + "[number 0x10'000];", + "[string '100000'];"); + + MTCPP("ctor_dtor", + "[def Foo::Foo]() {}", + "[def Foo::~Foo]() {}"); +})(); diff --git a/modules/editor/codemirror/mode/coffeescript/coffeescript.min.js b/modules/editor/codemirror/mode/coffeescript/coffeescript.min.js @@ -0,0 +1,359 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +/** + * Link to the project's GitHub page: + * https://github.com/pickhardt/coffeescript-codemirror-mode + */ +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode("coffeescript", function(conf, parserConf) { + var ERRORCLASS = "error"; + + function wordRegexp(words) { + return new RegExp("^((" + words.join(")|(") + "))\\b"); + } + + var operators = /^(?:->|=>|\+[+=]?|-[\-=]?|\*[\*=]?|\/[\/=]?|[=!]=|<[><]?=?|>>?=?|%=?|&=?|\|=?|\^=?|\~|!|\?|(or|and|\|\||&&|\?)=)/; + var delimiters = /^(?:[()\[\]{},:`=;]|\.\.?\.?)/; + var identifiers = /^[_A-Za-z$][_A-Za-z$0-9]*/; + var atProp = /^@[_A-Za-z$][_A-Za-z$0-9]*/; + + var wordOperators = wordRegexp(["and", "or", "not", + "is", "isnt", "in", + "instanceof", "typeof"]); + var indentKeywords = ["for", "while", "loop", "if", "unless", "else", + "switch", "try", "catch", "finally", "class"]; + var commonKeywords = ["break", "by", "continue", "debugger", "delete", + "do", "in", "of", "new", "return", "then", + "this", "@", "throw", "when", "until", "extends"]; + + var keywords = wordRegexp(indentKeywords.concat(commonKeywords)); + + indentKeywords = wordRegexp(indentKeywords); + + + var stringPrefixes = /^('{3}|\"{3}|['\"])/; + var regexPrefixes = /^(\/{3}|\/)/; + var commonConstants = ["Infinity", "NaN", "undefined", "null", "true", "false", "on", "off", "yes", "no"]; + var constants = wordRegexp(commonConstants); + + // Tokenizers + function tokenBase(stream, state) { + // Handle scope changes + if (stream.sol()) { + if (state.scope.align === null) state.scope.align = false; + var scopeOffset = state.scope.offset; + if (stream.eatSpace()) { + var lineOffset = stream.indentation(); + if (lineOffset > scopeOffset && state.scope.type == "coffee") { + return "indent"; + } else if (lineOffset < scopeOffset) { + return "dedent"; + } + return null; + } else { + if (scopeOffset > 0) { + dedent(stream, state); + } + } + } + if (stream.eatSpace()) { + return null; + } + + var ch = stream.peek(); + + // Handle docco title comment (single line) + if (stream.match("####")) { + stream.skipToEnd(); + return "comment"; + } + + // Handle multi line comments + if (stream.match("###")) { + state.tokenize = longComment; + return state.tokenize(stream, state); + } + + // Single line comment + if (ch === "#") { + stream.skipToEnd(); + return "comment"; + } + + // Handle number literals + if (stream.match(/^-?[0-9\.]/, false)) { + var floatLiteral = false; + // Floats + if (stream.match(/^-?\d*\.\d+(e[\+\-]?\d+)?/i)) { + floatLiteral = true; + } + if (stream.match(/^-?\d+\.\d*/)) { + floatLiteral = true; + } + if (stream.match(/^-?\.\d+/)) { + floatLiteral = true; + } + + if (floatLiteral) { + // prevent from getting extra . on 1.. + if (stream.peek() == "."){ + stream.backUp(1); + } + return "number"; + } + // Integers + var intLiteral = false; + // Hex + if (stream.match(/^-?0x[0-9a-f]+/i)) { + intLiteral = true; + } + // Decimal + if (stream.match(/^-?[1-9]\d*(e[\+\-]?\d+)?/)) { + intLiteral = true; + } + // Zero by itself with no other piece of number. + if (stream.match(/^-?0(?![\dx])/i)) { + intLiteral = true; + } + if (intLiteral) { + return "number"; + } + } + + // Handle strings + if (stream.match(stringPrefixes)) { + state.tokenize = tokenFactory(stream.current(), false, "string"); + return state.tokenize(stream, state); + } + // Handle regex literals + if (stream.match(regexPrefixes)) { + if (stream.current() != "/" || stream.match(/^.*\//, false)) { // prevent highlight of division + state.tokenize = tokenFactory(stream.current(), true, "string-2"); + return state.tokenize(stream, state); + } else { + stream.backUp(1); + } + } + + + + // Handle operators and delimiters + if (stream.match(operators) || stream.match(wordOperators)) { + return "operator"; + } + if (stream.match(delimiters)) { + return "punctuation"; + } + + if (stream.match(constants)) { + return "atom"; + } + + if (stream.match(atProp) || state.prop && stream.match(identifiers)) { + return "property"; + } + + if (stream.match(keywords)) { + return "keyword"; + } + + if (stream.match(identifiers)) { + return "variable"; + } + + // Handle non-detected items + stream.next(); + return ERRORCLASS; + } + + function tokenFactory(delimiter, singleline, outclass) { + return function(stream, state) { + while (!stream.eol()) { + stream.eatWhile(/[^'"\/\\]/); + if (stream.eat("\\")) { + stream.next(); + if (singleline && stream.eol()) { + return outclass; + } + } else if (stream.match(delimiter)) { + state.tokenize = tokenBase; + return outclass; + } else { + stream.eat(/['"\/]/); + } + } + if (singleline) { + if (parserConf.singleLineStringErrors) { + outclass = ERRORCLASS; + } else { + state.tokenize = tokenBase; + } + } + return outclass; + }; + } + + function longComment(stream, state) { + while (!stream.eol()) { + stream.eatWhile(/[^#]/); + if (stream.match("###")) { + state.tokenize = tokenBase; + break; + } + stream.eatWhile("#"); + } + return "comment"; + } + + function indent(stream, state, type) { + type = type || "coffee"; + var offset = 0, align = false, alignOffset = null; + for (var scope = state.scope; scope; scope = scope.prev) { + if (scope.type === "coffee" || scope.type == "}") { + offset = scope.offset + conf.indentUnit; + break; + } + } + if (type !== "coffee") { + align = null; + alignOffset = stream.column() + stream.current().length; + } else if (state.scope.align) { + state.scope.align = false; + } + state.scope = { + offset: offset, + type: type, + prev: state.scope, + align: align, + alignOffset: alignOffset + }; + } + + function dedent(stream, state) { + if (!state.scope.prev) return; + if (state.scope.type === "coffee") { + var _indent = stream.indentation(); + var matched = false; + for (var scope = state.scope; scope; scope = scope.prev) { + if (_indent === scope.offset) { + matched = true; + break; + } + } + if (!matched) { + return true; + } + while (state.scope.prev && state.scope.offset !== _indent) { + state.scope = state.scope.prev; + } + return false; + } else { + state.scope = state.scope.prev; + return false; + } + } + + function tokenLexer(stream, state) { + var style = state.tokenize(stream, state); + var current = stream.current(); + + // Handle scope changes. + if (current === "return") { + state.dedent = true; + } + if (((current === "->" || current === "=>") && stream.eol()) + || style === "indent") { + indent(stream, state); + } + var delimiter_index = "[({".indexOf(current); + if (delimiter_index !== -1) { + indent(stream, state, "])}".slice(delimiter_index, delimiter_index+1)); + } + if (indentKeywords.exec(current)){ + indent(stream, state); + } + if (current == "then"){ + dedent(stream, state); + } + + + if (style === "dedent") { + if (dedent(stream, state)) { + return ERRORCLASS; + } + } + delimiter_index = "])}".indexOf(current); + if (delimiter_index !== -1) { + while (state.scope.type == "coffee" && state.scope.prev) + state.scope = state.scope.prev; + if (state.scope.type == current) + state.scope = state.scope.prev; + } + if (state.dedent && stream.eol()) { + if (state.scope.type == "coffee" && state.scope.prev) + state.scope = state.scope.prev; + state.dedent = false; + } + + return style; + } + + var external = { + startState: function(basecolumn) { + return { + tokenize: tokenBase, + scope: {offset:basecolumn || 0, type:"coffee", prev: null, align: false}, + prop: false, + dedent: 0 + }; + }, + + token: function(stream, state) { + var fillAlign = state.scope.align === null && state.scope; + if (fillAlign && stream.sol()) fillAlign.align = false; + + var style = tokenLexer(stream, state); + if (style && style != "comment") { + if (fillAlign) fillAlign.align = true; + state.prop = style == "punctuation" && stream.current() == "." + } + + return style; + }, + + indent: function(state, text) { + if (state.tokenize != tokenBase) return 0; + var scope = state.scope; + var closer = text && "])}".indexOf(text.charAt(0)) > -1; + if (closer) while (scope.type == "coffee" && scope.prev) scope = scope.prev; + var closes = closer && scope.type === text.charAt(0); + if (scope.align) + return scope.alignOffset - (closes ? 1 : 0); + else + return (closes ? scope.prev : scope).offset; + }, + + lineComment: "#", + fold: "indent" + }; + return external; +}); + +// IANA registered media type +// https://www.iana.org/assignments/media-types/ +CodeMirror.defineMIME("application/vnd.coffeescript", "coffeescript"); + +CodeMirror.defineMIME("text/x-coffeescript", "coffeescript"); +CodeMirror.defineMIME("text/coffeescript", "coffeescript"); + +}); diff --git a/modules/editor/codemirror/mode/css/test.min.js b/modules/editor/codemirror/mode/css/test.min.js @@ -0,0 +1,206 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function() { + var mode = CodeMirror.getMode({indentUnit: 2}, "css"); + function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } + + // Error, because "foobarhello" is neither a known type or property, but + // property was expected (after "and"), and it should be in parentheses. + MT("atMediaUnknownType", + "[def @media] [attribute screen] [keyword and] [error foobarhello] { }"); + + // Soft error, because "foobarhello" is not a known property or type. + MT("atMediaUnknownProperty", + "[def @media] [attribute screen] [keyword and] ([error foobarhello]) { }"); + + // Make sure nesting works with media queries + MT("atMediaMaxWidthNested", + "[def @media] [attribute screen] [keyword and] ([property max-width]: [number 25px]) { [tag foo] { } }"); + + MT("atMediaFeatureValueKeyword", + "[def @media] ([property orientation]: [keyword landscape]) { }"); + + MT("atMediaUnknownFeatureValueKeyword", + "[def @media] ([property orientation]: [error upsidedown]) { }"); + + MT("tagSelector", + "[tag foo] { }"); + + MT("classSelector", + "[qualifier .foo-bar_hello] { }"); + + MT("idSelector", + "[builtin #foo] { [error #foo] }"); + + MT("tagSelectorUnclosed", + "[tag foo] { [property margin]: [number 0] } [tag bar] { }"); + + MT("tagStringNoQuotes", + "[tag foo] { [property font-family]: [variable hello] [variable world]; }"); + + MT("tagStringDouble", + "[tag foo] { [property font-family]: [string \"hello world\"]; }"); + + MT("tagStringSingle", + "[tag foo] { [property font-family]: [string 'hello world']; }"); + + MT("tagColorKeyword", + "[tag foo] {", + " [property color]: [keyword black];", + " [property color]: [keyword navy];", + " [property color]: [keyword yellow];", + "}"); + + MT("tagColorHex3", + "[tag foo] { [property background]: [atom #fff]; }"); + + MT("tagColorHex4", + "[tag foo] { [property background]: [atom #ffff]; }"); + + MT("tagColorHex6", + "[tag foo] { [property background]: [atom #ffffff]; }"); + + MT("tagColorHex8", + "[tag foo] { [property background]: [atom #ffffffff]; }"); + + MT("tagColorHex5Invalid", + "[tag foo] { [property background]: [atom&error #fffff]; }"); + + MT("tagColorHexInvalid", + "[tag foo] { [property background]: [atom&error #ffg]; }"); + + MT("tagNegativeNumber", + "[tag foo] { [property margin]: [number -5px]; }"); + + MT("tagPositiveNumber", + "[tag foo] { [property padding]: [number 5px]; }"); + + MT("tagVendor", + "[tag foo] { [meta -foo-][property box-sizing]: [meta -foo-][atom border-box]; }"); + + MT("tagBogusProperty", + "[tag foo] { [property&error barhelloworld]: [number 0]; }"); + + MT("tagTwoProperties", + "[tag foo] { [property margin]: [number 0]; [property padding]: [number 0]; }"); + + MT("tagTwoPropertiesURL", + "[tag foo] { [property background]: [atom url]([string //example.com/foo.png]); [property padding]: [number 0]; }"); + + MT("indent_tagSelector", + "[tag strong], [tag em] {", + " [property background]: [atom rgba](", + " [number 255], [number 255], [number 0], [number .2]", + " );", + "}"); + + MT("indent_atMedia", + "[def @media] {", + " [tag foo] {", + " [property color]:", + " [keyword yellow];", + " }", + "}"); + + MT("indent_comma", + "[tag foo] {", + " [property font-family]: [variable verdana],", + " [atom sans-serif];", + "}"); + + MT("indent_parentheses", + "[tag foo]:[variable-3 before] {", + " [property background]: [atom url](", + "[string blahblah]", + "[string etc]", + "[string ]) [keyword !important];", + "}"); + + MT("font_face", + "[def @font-face] {", + " [property font-family]: [string 'myfont'];", + " [error nonsense]: [string 'abc'];", + " [property src]: [atom url]([string http://blah]),", + " [atom url]([string http://foo]);", + "}"); + + MT("empty_url", + "[def @import] [atom url]() [attribute screen];"); + + MT("parens", + "[qualifier .foo] {", + " [property background-image]: [variable fade]([atom #000], [number 20%]);", + " [property border-image]: [atom linear-gradient](", + " [atom to] [atom bottom],", + " [variable fade]([atom #000], [number 20%]) [number 0%],", + " [variable fade]([atom #000], [number 20%]) [number 100%]", + " );", + "}"); + + MT("css_variable", + ":[variable-3 root] {", + " [variable-2 --main-color]: [atom #06c];", + "}", + "[tag h1][builtin #foo] {", + " [property color]: [atom var]([variable-2 --main-color]);", + "}"); + + MT("supports", + "[def @supports] ([keyword not] (([property text-align-last]: [atom justify]) [keyword or] ([meta -moz-][property text-align-last]: [atom justify])) {", + " [property text-align-last]: [atom justify];", + "}"); + + MT("document", + "[def @document] [tag url]([string http://blah]),", + " [tag url-prefix]([string https://]),", + " [tag domain]([string blah.com]),", + " [tag regexp]([string \".*blah.+\"]) {", + " [builtin #id] {", + " [property background-color]: [keyword white];", + " }", + " [tag foo] {", + " [property font-family]: [variable Verdana], [atom sans-serif];", + " }", + "}"); + + MT("document_url", + "[def @document] [tag url]([string http://blah]) { [qualifier .class] { } }"); + + MT("document_urlPrefix", + "[def @document] [tag url-prefix]([string https://]) { [builtin #id] { } }"); + + MT("document_domain", + "[def @document] [tag domain]([string blah.com]) { [tag foo] { } }"); + + MT("document_regexp", + "[def @document] [tag regexp]([string \".*blah.+\"]) { [builtin #id] { } }"); + + MT("counter-style", + "[def @counter-style] [variable binary] {", + " [property system]: [atom numeric];", + " [property symbols]: [number 0] [number 1];", + " [property suffix]: [string \".\"];", + " [property range]: [atom infinite];", + " [property speak-as]: [atom numeric];", + "}"); + + MT("counter-style-additive-symbols", + "[def @counter-style] [variable simple-roman] {", + " [property system]: [atom additive];", + " [property additive-symbols]: [number 10] [variable X], [number 5] [variable V], [number 1] [variable I];", + " [property range]: [number 1] [number 49];", + "}"); + + MT("counter-style-use", + "[tag ol][qualifier .roman] { [property list-style]: [variable simple-roman]; }"); + + MT("counter-style-symbols", + "[tag ol] { [property list-style]: [atom symbols]([atom cyclic] [string \"*\"] [string \"\\2020\"] [string \"\\2021\"] [string \"\\A7\"]); }"); + + MT("comment-does-not-disrupt", + "[def @font-face] [comment /* foo */] {", + " [property src]: [atom url]([string x]);", + " [property font-family]: [variable One];", + "}") +})(); diff --git a/modules/editor/codemirror/mode/cypher/cypher.min.js b/modules/editor/codemirror/mode/cypher/cypher.min.js @@ -0,0 +1,150 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// By the Neo4j Team and contributors. +// https://github.com/neo4j-contrib/CodeMirror + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + var wordRegexp = function(words) { + return new RegExp("^(?:" + words.join("|") + ")$", "i"); + }; + + CodeMirror.defineMode("cypher", function(config) { + var tokenBase = function(stream/*, state*/) { + var ch = stream.next(); + if (ch ==='"') { + stream.match(/.*?"/); + return "string"; + } + if (ch === "'") { + stream.match(/.*?'/); + return "string"; + } + if (/[{}\(\),\.;\[\]]/.test(ch)) { + curPunc = ch; + return "node"; + } else if (ch === "/" && stream.eat("/")) { + stream.skipToEnd(); + return "comment"; + } else if (operatorChars.test(ch)) { + stream.eatWhile(operatorChars); + return null; + } else { + stream.eatWhile(/[_\w\d]/); + if (stream.eat(":")) { + stream.eatWhile(/[\w\d_\-]/); + return "atom"; + } + var word = stream.current(); + if (funcs.test(word)) return "builtin"; + if (preds.test(word)) return "def"; + if (keywords.test(word)) return "keyword"; + return "variable"; + } + }; + var pushContext = function(state, type, col) { + return state.context = { + prev: state.context, + indent: state.indent, + col: col, + type: type + }; + }; + var popContext = function(state) { + state.indent = state.context.indent; + return state.context = state.context.prev; + }; + var indentUnit = config.indentUnit; + var curPunc; + var funcs = wordRegexp(["abs", "acos", "allShortestPaths", "asin", "atan", "atan2", "avg", "ceil", "coalesce", "collect", "cos", "cot", "count", "degrees", "e", "endnode", "exp", "extract", "filter", "floor", "haversin", "head", "id", "keys", "labels", "last", "left", "length", "log", "log10", "lower", "ltrim", "max", "min", "node", "nodes", "percentileCont", "percentileDisc", "pi", "radians", "rand", "range", "reduce", "rel", "relationship", "relationships", "replace", "reverse", "right", "round", "rtrim", "shortestPath", "sign", "sin", "size", "split", "sqrt", "startnode", "stdev", "stdevp", "str", "substring", "sum", "tail", "tan", "timestamp", "toFloat", "toInt", "toString", "trim", "type", "upper"]); + var preds = wordRegexp(["all", "and", "any", "contains", "exists", "has", "in", "none", "not", "or", "single", "xor"]); + var keywords = wordRegexp(["as", "asc", "ascending", "assert", "by", "case", "commit", "constraint", "create", "csv", "cypher", "delete", "desc", "descending", "detach", "distinct", "drop", "else", "end", "ends", "explain", "false", "fieldterminator", "foreach", "from", "headers", "in", "index", "is", "join", "limit", "load", "match", "merge", "null", "on", "optional", "order", "periodic", "profile", "remove", "return", "scan", "set", "skip", "start", "starts", "then", "true", "union", "unique", "unwind", "using", "when", "where", "with", "call", "yield"]); + var operatorChars = /[*+\-<>=&|~%^]/; + + return { + startState: function(/*base*/) { + return { + tokenize: tokenBase, + context: null, + indent: 0, + col: 0 + }; + }, + token: function(stream, state) { + if (stream.sol()) { + if (state.context && (state.context.align == null)) { + state.context.align = false; + } + state.indent = stream.indentation(); + } + if (stream.eatSpace()) { + return null; + } + var style = state.tokenize(stream, state); + if (style !== "comment" && state.context && (state.context.align == null) && state.context.type !== "pattern") { + state.context.align = true; + } + if (curPunc === "(") { + pushContext(state, ")", stream.column()); + } else if (curPunc === "[") { + pushContext(state, "]", stream.column()); + } else if (curPunc === "{") { + pushContext(state, "}", stream.column()); + } else if (/[\]\}\)]/.test(curPunc)) { + while (state.context && state.context.type === "pattern") { + popContext(state); + } + if (state.context && curPunc === state.context.type) { + popContext(state); + } + } else if (curPunc === "." && state.context && state.context.type === "pattern") { + popContext(state); + } else if (/atom|string|variable/.test(style) && state.context) { + if (/[\}\]]/.test(state.context.type)) { + pushContext(state, "pattern", stream.column()); + } else if (state.context.type === "pattern" && !state.context.align) { + state.context.align = true; + state.context.col = stream.column(); + } + } + return style; + }, + indent: function(state, textAfter) { + var firstChar = textAfter && textAfter.charAt(0); + var context = state.context; + if (/[\]\}]/.test(firstChar)) { + while (context && context.type === "pattern") { + context = context.prev; + } + } + var closing = context && firstChar === context.type; + if (!context) return 0; + if (context.type === "keywords") return CodeMirror.commands.newlineAndIndent; + if (context.align) return context.col + (closing ? 0 : 1); + return context.indent + (closing ? 0 : indentUnit); + } + }; + }); + + CodeMirror.modeExtensions["cypher"] = { + autoFormatLineBreaks: function(text) { + var i, lines, reProcessedPortion; + var lines = text.split("\n"); + var reProcessedPortion = /\s+\b(return|where|order by|match|with|skip|limit|create|delete|set)\b\s/g; + for (var i = 0; i < lines.length; i++) + lines[i] = lines[i].replace(reProcessedPortion, " \n$1 ").trim(); + return lines.join("\n"); + } + }; + + CodeMirror.defineMIME("application/x-cypher-query", "cypher"); + +}); diff --git a/modules/editor/codemirror/mode/cypher/test.min.js b/modules/editor/codemirror/mode/cypher/test.min.js @@ -0,0 +1,37 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function() { + var mode = CodeMirror.getMode({tabSize: 4, indentUnit: 2}, "cypher"); + function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } + + MT("unbalancedDoubledQuotedString", + "[string \"a'b\"][variable c]"); + + MT("unbalancedSingleQuotedString", + "[string 'a\"b'][variable c]"); + + MT("doubleQuotedString", + "[string \"a\"][variable b]"); + + MT("singleQuotedString", + "[string 'a'][variable b]"); + + MT("single attribute (with content)", + "[node {][atom a:][string 'a'][node }]"); + + MT("multiple attribute, singleQuotedString (with content)", + "[node {][atom a:][string 'a'][node ,][atom b:][string 'b'][node }]"); + + MT("multiple attribute, doubleQuotedString (with content)", + "[node {][atom a:][string \"a\"][node ,][atom b:][string \"b\"][node }]"); + + MT("single attribute (without content)", + "[node {][atom a:][string 'a'][node }]"); + + MT("multiple attribute, singleQuotedString (without content)", + "[node {][atom a:][string ''][node ,][atom b:][string ''][node }]"); + + MT("multiple attribute, doubleQuotedString (without content)", + "[node {][atom a:][string \"\"][node ,][atom b:][string \"\"][node }]"); + })(); diff --git a/modules/editor/codemirror/mode/django/django.min.js b/modules/editor/codemirror/mode/django/django.min.js @@ -0,0 +1,356 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror"), require("../htmlmixed/htmlmixed"), + require("../../addon/mode/overlay")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror", "../htmlmixed/htmlmixed", + "../../addon/mode/overlay"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + CodeMirror.defineMode("django:inner", function() { + var keywords = ["block", "endblock", "for", "endfor", "true", "false", "filter", "endfilter", + "loop", "none", "self", "super", "if", "elif", "endif", "as", "else", "import", + "with", "endwith", "without", "context", "ifequal", "endifequal", "ifnotequal", + "endifnotequal", "extends", "include", "load", "comment", "endcomment", + "empty", "url", "static", "trans", "blocktrans", "endblocktrans", "now", + "regroup", "lorem", "ifchanged", "endifchanged", "firstof", "debug", "cycle", + "csrf_token", "autoescape", "endautoescape", "spaceless", "endspaceless", + "ssi", "templatetag", "verbatim", "endverbatim", "widthratio"], + filters = ["add", "addslashes", "capfirst", "center", "cut", "date", + "default", "default_if_none", "dictsort", + "dictsortreversed", "divisibleby", "escape", "escapejs", + "filesizeformat", "first", "floatformat", "force_escape", + "get_digit", "iriencode", "join", "last", "length", + "length_is", "linebreaks", "linebreaksbr", "linenumbers", + "ljust", "lower", "make_list", "phone2numeric", "pluralize", + "pprint", "random", "removetags", "rjust", "safe", + "safeseq", "slice", "slugify", "stringformat", "striptags", + "time", "timesince", "timeuntil", "title", "truncatechars", + "truncatechars_html", "truncatewords", "truncatewords_html", + "unordered_list", "upper", "urlencode", "urlize", + "urlizetrunc", "wordcount", "wordwrap", "yesno"], + operators = ["==", "!=", "<", ">", "<=", ">="], + wordOperators = ["in", "not", "or", "and"]; + + keywords = new RegExp("^\\b(" + keywords.join("|") + ")\\b"); + filters = new RegExp("^\\b(" + filters.join("|") + ")\\b"); + operators = new RegExp("^\\b(" + operators.join("|") + ")\\b"); + wordOperators = new RegExp("^\\b(" + wordOperators.join("|") + ")\\b"); + + // We have to return "null" instead of null, in order to avoid string + // styling as the default, when using Django templates inside HTML + // element attributes + function tokenBase (stream, state) { + // Attempt to identify a variable, template or comment tag respectively + if (stream.match("{{")) { + state.tokenize = inVariable; + return "tag"; + } else if (stream.match("{%")) { + state.tokenize = inTag; + return "tag"; + } else if (stream.match("{#")) { + state.tokenize = inComment; + return "comment"; + } + + // Ignore completely any stream series that do not match the + // Django template opening tags. + while (stream.next() != null && !stream.match(/\{[{%#]/, false)) {} + return null; + } + + // A string can be included in either single or double quotes (this is + // the delimiter). Mark everything as a string until the start delimiter + // occurs again. + function inString (delimiter, previousTokenizer) { + return function (stream, state) { + if (!state.escapeNext && stream.eat(delimiter)) { + state.tokenize = previousTokenizer; + } else { + if (state.escapeNext) { + state.escapeNext = false; + } + + var ch = stream.next(); + + // Take into account the backslash for escaping characters, such as + // the string delimiter. + if (ch == "\\") { + state.escapeNext = true; + } + } + + return "string"; + }; + } + + // Apply Django template variable syntax highlighting + function inVariable (stream, state) { + // Attempt to match a dot that precedes a property + if (state.waitDot) { + state.waitDot = false; + + if (stream.peek() != ".") { + return "null"; + } + + // Dot followed by a non-word character should be considered an error. + if (stream.match(/\.\W+/)) { + return "error"; + } else if (stream.eat(".")) { + state.waitProperty = true; + return "null"; + } else { + throw Error ("Unexpected error while waiting for property."); + } + } + + // Attempt to match a pipe that precedes a filter + if (state.waitPipe) { + state.waitPipe = false; + + if (stream.peek() != "|") { + return "null"; + } + + // Pipe followed by a non-word character should be considered an error. + if (stream.match(/\.\W+/)) { + return "error"; + } else if (stream.eat("|")) { + state.waitFilter = true; + return "null"; + } else { + throw Error ("Unexpected error while waiting for filter."); + } + } + + // Highlight properties + if (state.waitProperty) { + state.waitProperty = false; + if (stream.match(/\b(\w+)\b/)) { + state.waitDot = true; // A property can be followed by another property + state.waitPipe = true; // A property can be followed by a filter + return "property"; + } + } + + // Highlight filters + if (state.waitFilter) { + state.waitFilter = false; + if (stream.match(filters)) { + return "variable-2"; + } + } + + // Ignore all white spaces + if (stream.eatSpace()) { + state.waitProperty = false; + return "null"; + } + + // Identify numbers + if (stream.match(/\b\d+(\.\d+)?\b/)) { + return "number"; + } + + // Identify strings + if (stream.match("'")) { + state.tokenize = inString("'", state.tokenize); + return "string"; + } else if (stream.match('"')) { + state.tokenize = inString('"', state.tokenize); + return "string"; + } + + // Attempt to find the variable + if (stream.match(/\b(\w+)\b/) && !state.foundVariable) { + state.waitDot = true; + state.waitPipe = true; // A property can be followed by a filter + return "variable"; + } + + // If found closing tag reset + if (stream.match("}}")) { + state.waitProperty = null; + state.waitFilter = null; + state.waitDot = null; + state.waitPipe = null; + state.tokenize = tokenBase; + return "tag"; + } + + // If nothing was found, advance to the next character + stream.next(); + return "null"; + } + + function inTag (stream, state) { + // Attempt to match a dot that precedes a property + if (state.waitDot) { + state.waitDot = false; + + if (stream.peek() != ".") { + return "null"; + } + + // Dot followed by a non-word character should be considered an error. + if (stream.match(/\.\W+/)) { + return "error"; + } else if (stream.eat(".")) { + state.waitProperty = true; + return "null"; + } else { + throw Error ("Unexpected error while waiting for property."); + } + } + + // Attempt to match a pipe that precedes a filter + if (state.waitPipe) { + state.waitPipe = false; + + if (stream.peek() != "|") { + return "null"; + } + + // Pipe followed by a non-word character should be considered an error. + if (stream.match(/\.\W+/)) { + return "error"; + } else if (stream.eat("|")) { + state.waitFilter = true; + return "null"; + } else { + throw Error ("Unexpected error while waiting for filter."); + } + } + + // Highlight properties + if (state.waitProperty) { + state.waitProperty = false; + if (stream.match(/\b(\w+)\b/)) { + state.waitDot = true; // A property can be followed by another property + state.waitPipe = true; // A property can be followed by a filter + return "property"; + } + } + + // Highlight filters + if (state.waitFilter) { + state.waitFilter = false; + if (stream.match(filters)) { + return "variable-2"; + } + } + + // Ignore all white spaces + if (stream.eatSpace()) { + state.waitProperty = false; + return "null"; + } + + // Identify numbers + if (stream.match(/\b\d+(\.\d+)?\b/)) { + return "number"; + } + + // Identify strings + if (stream.match("'")) { + state.tokenize = inString("'", state.tokenize); + return "string"; + } else if (stream.match('"')) { + state.tokenize = inString('"', state.tokenize); + return "string"; + } + + // Attempt to match an operator + if (stream.match(operators)) { + return "operator"; + } + + // Attempt to match a word operator + if (stream.match(wordOperators)) { + return "keyword"; + } + + // Attempt to match a keyword + var keywordMatch = stream.match(keywords); + if (keywordMatch) { + if (keywordMatch[0] == "comment") { + state.blockCommentTag = true; + } + return "keyword"; + } + + // Attempt to match a variable + if (stream.match(/\b(\w+)\b/)) { + state.waitDot = true; + state.waitPipe = true; // A property can be followed by a filter + return "variable"; + } + + // If found closing tag reset + if (stream.match("%}")) { + state.waitProperty = null; + state.waitFilter = null; + state.waitDot = null; + state.waitPipe = null; + // If the tag that closes is a block comment tag, we want to mark the + // following code as comment, until the tag closes. + if (state.blockCommentTag) { + state.blockCommentTag = false; // Release the "lock" + state.tokenize = inBlockComment; + } else { + state.tokenize = tokenBase; + } + return "tag"; + } + + // If nothing was found, advance to the next character + stream.next(); + return "null"; + } + + // Mark everything as comment inside the tag and the tag itself. + function inComment (stream, state) { + if (stream.match(/^.*?#\}/)) state.tokenize = tokenBase + else stream.skipToEnd() + return "comment"; + } + + // Mark everything as a comment until the `blockcomment` tag closes. + function inBlockComment (stream, state) { + if (stream.match(/\{%\s*endcomment\s*%\}/, false)) { + state.tokenize = inTag; + stream.match("{%"); + return "tag"; + } else { + stream.next(); + return "comment"; + } + } + + return { + startState: function () { + return {tokenize: tokenBase}; + }, + token: function (stream, state) { + return state.tokenize(stream, state); + }, + blockCommentStart: "{% comment %}", + blockCommentEnd: "{% endcomment %}" + }; + }); + + CodeMirror.defineMode("django", function(config) { + var htmlBase = CodeMirror.getMode(config, "text/html"); + var djangoInner = CodeMirror.getMode(config, "django:inner"); + return CodeMirror.overlayMode(htmlBase, djangoInner); + }); + + CodeMirror.defineMIME("text/x-django", "django"); +}); diff --git a/modules/editor/codemirror/mode/erlang/erlang.min.js b/modules/editor/codemirror/mode/erlang/erlang.min.js @@ -0,0 +1,619 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +/*jshint unused:true, eqnull:true, curly:true, bitwise:true */ +/*jshint undef:true, latedef:true, trailing:true */ +/*global CodeMirror:true */ + +// erlang mode. +// tokenizer -> token types -> CodeMirror styles +// tokenizer maintains a parse stack +// indenter uses the parse stack + +// TODO indenter: +// bit syntax +// old guard/bif/conversion clashes (e.g. "float/1") +// type/spec/opaque + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMIME("text/x-erlang", "erlang"); + +CodeMirror.defineMode("erlang", function(cmCfg) { + "use strict"; + +///////////////////////////////////////////////////////////////////////////// +// constants + + var typeWords = [ + "-type", "-spec", "-export_type", "-opaque"]; + + var keywordWords = [ + "after","begin","catch","case","cond","end","fun","if", + "let","of","query","receive","try","when"]; + + var separatorRE = /[\->,;]/; + var separatorWords = [ + "->",";",","]; + + var operatorAtomWords = [ + "and","andalso","band","bnot","bor","bsl","bsr","bxor", + "div","not","or","orelse","rem","xor"]; + + var operatorSymbolRE = /[\+\-\*\/<>=\|:!]/; + var operatorSymbolWords = [ + "=","+","-","*","/",">",">=","<","=<","=:=","==","=/=","/=","||","<-","!"]; + + var openParenRE = /[<\(\[\{]/; + var openParenWords = [ + "<<","(","[","{"]; + + var closeParenRE = /[>\)\]\}]/; + var closeParenWords = [ + "}","]",")",">>"]; + + var guardWords = [ + "is_atom","is_binary","is_bitstring","is_boolean","is_float", + "is_function","is_integer","is_list","is_number","is_pid", + "is_port","is_record","is_reference","is_tuple", + "atom","binary","bitstring","boolean","function","integer","list", + "number","pid","port","record","reference","tuple"]; + + var bifWords = [ + "abs","adler32","adler32_combine","alive","apply","atom_to_binary", + "atom_to_list","binary_to_atom","binary_to_existing_atom", + "binary_to_list","binary_to_term","bit_size","bitstring_to_list", + "byte_size","check_process_code","contact_binary","crc32", + "crc32_combine","date","decode_packet","delete_module", + "disconnect_node","element","erase","exit","float","float_to_list", + "garbage_collect","get","get_keys","group_leader","halt","hd", + "integer_to_list","internal_bif","iolist_size","iolist_to_binary", + "is_alive","is_atom","is_binary","is_bitstring","is_boolean", + "is_float","is_function","is_integer","is_list","is_number","is_pid", + "is_port","is_process_alive","is_record","is_reference","is_tuple", + "length","link","list_to_atom","list_to_binary","list_to_bitstring", + "list_to_existing_atom","list_to_float","list_to_integer", + "list_to_pid","list_to_tuple","load_module","make_ref","module_loaded", + "monitor_node","node","node_link","node_unlink","nodes","notalive", + "now","open_port","pid_to_list","port_close","port_command", + "port_connect","port_control","pre_loaded","process_flag", + "process_info","processes","purge_module","put","register", + "registered","round","self","setelement","size","spawn","spawn_link", + "spawn_monitor","spawn_opt","split_binary","statistics", + "term_to_binary","time","throw","tl","trunc","tuple_size", + "tuple_to_list","unlink","unregister","whereis"]; + +// upper case: [A-Z] [Ø-Þ] [À-Ö] +// lower case: [a-z] [ß-ö] [ø-ÿ] + var anumRE = /[\w@Ø-ÞÀ-Öß-öø-ÿ]/; + var escapesRE = + /[0-7]{1,3}|[bdefnrstv\\"']|\^[a-zA-Z]|x[0-9a-zA-Z]{2}|x{[0-9a-zA-Z]+}/; + +///////////////////////////////////////////////////////////////////////////// +// tokenizer + + function tokenizer(stream,state) { + // in multi-line string + if (state.in_string) { + state.in_string = (!doubleQuote(stream)); + return rval(state,stream,"string"); + } + + // in multi-line atom + if (state.in_atom) { + state.in_atom = (!singleQuote(stream)); + return rval(state,stream,"atom"); + } + + // whitespace + if (stream.eatSpace()) { + return rval(state,stream,"whitespace"); + } + + // attributes and type specs + if (!peekToken(state) && + stream.match(/-\s*[a-zß-öø-ÿ][\wØ-ÞÀ-Öß-öø-ÿ]*/)) { + if (is_member(stream.current(),typeWords)) { + return rval(state,stream,"type"); + }else{ + return rval(state,stream,"attribute"); + } + } + + var ch = stream.next(); + + // comment + if (ch == '%') { + stream.skipToEnd(); + return rval(state,stream,"comment"); + } + + // colon + if (ch == ":") { + return rval(state,stream,"colon"); + } + + // macro + if (ch == '?') { + stream.eatSpace(); + stream.eatWhile(anumRE); + return rval(state,stream,"macro"); + } + + // record + if (ch == "#") { + stream.eatSpace(); + stream.eatWhile(anumRE); + return rval(state,stream,"record"); + } + + // dollar escape + if (ch == "$") { + if (stream.next() == "\\" && !stream.match(escapesRE)) { + return rval(state,stream,"error"); + } + return rval(state,stream,"number"); + } + + // dot + if (ch == ".") { + return rval(state,stream,"dot"); + } + + // quoted atom + if (ch == '\'') { + if (!(state.in_atom = (!singleQuote(stream)))) { + if (stream.match(/\s*\/\s*[0-9]/,false)) { + stream.match(/\s*\/\s*[0-9]/,true); + return rval(state,stream,"fun"); // 'f'/0 style fun + } + if (stream.match(/\s*\(/,false) || stream.match(/\s*:/,false)) { + return rval(state,stream,"function"); + } + } + return rval(state,stream,"atom"); + } + + // string + if (ch == '"') { + state.in_string = (!doubleQuote(stream)); + return rval(state,stream,"string"); + } + + // variable + if (/[A-Z_Ø-ÞÀ-Ö]/.test(ch)) { + stream.eatWhile(anumRE); + return rval(state,stream,"variable"); + } + + // atom/keyword/BIF/function + if (/[a-z_ß-öø-ÿ]/.test(ch)) { + stream.eatWhile(anumRE); + + if (stream.match(/\s*\/\s*[0-9]/,false)) { + stream.match(/\s*\/\s*[0-9]/,true); + return rval(state,stream,"fun"); // f/0 style fun + } + + var w = stream.current(); + + if (is_member(w,keywordWords)) { + return rval(state,stream,"keyword"); + }else if (is_member(w,operatorAtomWords)) { + return rval(state,stream,"operator"); + }else if (stream.match(/\s*\(/,false)) { + // 'put' and 'erlang:put' are bifs, 'foo:put' is not + if (is_member(w,bifWords) && + ((peekToken(state).token != ":") || + (peekToken(state,2).token == "erlang"))) { + return rval(state,stream,"builtin"); + }else if (is_member(w,guardWords)) { + return rval(state,stream,"guard"); + }else{ + return rval(state,stream,"function"); + } + }else if (lookahead(stream) == ":") { + if (w == "erlang") { + return rval(state,stream,"builtin"); + } else { + return rval(state,stream,"function"); + } + }else if (is_member(w,["true","false"])) { + return rval(state,stream,"boolean"); + }else{ + return rval(state,stream,"atom"); + } + } + + // number + var digitRE = /[0-9]/; + var radixRE = /[0-9a-zA-Z]/; // 36#zZ style int + if (digitRE.test(ch)) { + stream.eatWhile(digitRE); + if (stream.eat('#')) { // 36#aZ style integer + if (!stream.eatWhile(radixRE)) { + stream.backUp(1); //"36#" - syntax error + } + } else if (stream.eat('.')) { // float + if (!stream.eatWhile(digitRE)) { + stream.backUp(1); // "3." - probably end of function + } else { + if (stream.eat(/[eE]/)) { // float with exponent + if (stream.eat(/[-+]/)) { + if (!stream.eatWhile(digitRE)) { + stream.backUp(2); // "2e-" - syntax error + } + } else { + if (!stream.eatWhile(digitRE)) { + stream.backUp(1); // "2e" - syntax error + } + } + } + } + } + return rval(state,stream,"number"); // normal integer + } + + // open parens + if (nongreedy(stream,openParenRE,openParenWords)) { + return rval(state,stream,"open_paren"); + } + + // close parens + if (nongreedy(stream,closeParenRE,closeParenWords)) { + return rval(state,stream,"close_paren"); + } + + // separators + if (greedy(stream,separatorRE,separatorWords)) { + return rval(state,stream,"separator"); + } + + // operators + if (greedy(stream,operatorSymbolRE,operatorSymbolWords)) { + return rval(state,stream,"operator"); + } + + return rval(state,stream,null); + } + +///////////////////////////////////////////////////////////////////////////// +// utilities + function nongreedy(stream,re,words) { + if (stream.current().length == 1 && re.test(stream.current())) { + stream.backUp(1); + while (re.test(stream.peek())) { + stream.next(); + if (is_member(stream.current(),words)) { + return true; + } + } + stream.backUp(stream.current().length-1); + } + return false; + } + + function greedy(stream,re,words) { + if (stream.current().length == 1 && re.test(stream.current())) { + while (re.test(stream.peek())) { + stream.next(); + } + while (0 < stream.current().length) { + if (is_member(stream.current(),words)) { + return true; + }else{ + stream.backUp(1); + } + } + stream.next(); + } + return false; + } + + function doubleQuote(stream) { + return quote(stream, '"', '\\'); + } + + function singleQuote(stream) { + return quote(stream,'\'','\\'); + } + + function quote(stream,quoteChar,escapeChar) { + while (!stream.eol()) { + var ch = stream.next(); + if (ch == quoteChar) { + return true; + }else if (ch == escapeChar) { + stream.next(); + } + } + return false; + } + + function lookahead(stream) { + var m = stream.match(/([\n\s]+|%[^\n]*\n)*(.)/,false); + return m ? m.pop() : ""; + } + + function is_member(element,list) { + return (-1 < list.indexOf(element)); + } + + function rval(state,stream,type) { + + // parse stack + pushToken(state,realToken(type,stream)); + + // map erlang token type to CodeMirror style class + // erlang -> CodeMirror tag + switch (type) { + case "atom": return "atom"; + case "attribute": return "attribute"; + case "boolean": return "atom"; + case "builtin": return "builtin"; + case "close_paren": return null; + case "colon": return null; + case "comment": return "comment"; + case "dot": return null; + case "error": return "error"; + case "fun": return "meta"; + case "function": return "tag"; + case "guard": return "property"; + case "keyword": return "keyword"; + case "macro": return "variable-2"; + case "number": return "number"; + case "open_paren": return null; + case "operator": return "operator"; + case "record": return "bracket"; + case "separator": return null; + case "string": return "string"; + case "type": return "def"; + case "variable": return "variable"; + default: return null; + } + } + + function aToken(tok,col,ind,typ) { + return {token: tok, + column: col, + indent: ind, + type: typ}; + } + + function realToken(type,stream) { + return aToken(stream.current(), + stream.column(), + stream.indentation(), + type); + } + + function fakeToken(type) { + return aToken(type,0,0,type); + } + + function peekToken(state,depth) { + var len = state.tokenStack.length; + var dep = (depth ? depth : 1); + + if (len < dep) { + return false; + }else{ + return state.tokenStack[len-dep]; + } + } + + function pushToken(state,token) { + + if (!(token.type == "comment" || token.type == "whitespace")) { + state.tokenStack = maybe_drop_pre(state.tokenStack,token); + state.tokenStack = maybe_drop_post(state.tokenStack); + } + } + + function maybe_drop_pre(s,token) { + var last = s.length-1; + + if (0 < last && s[last].type === "record" && token.type === "dot") { + s.pop(); + }else if (0 < last && s[last].type === "group") { + s.pop(); + s.push(token); + }else{ + s.push(token); + } + return s; + } + + function maybe_drop_post(s) { + if (!s.length) return s + var last = s.length-1; + + if (s[last].type === "dot") { + return []; + } + if (last > 1 && s[last].type === "fun" && s[last-1].token === "fun") { + return s.slice(0,last-1); + } + switch (s[last].token) { + case "}": return d(s,{g:["{"]}); + case "]": return d(s,{i:["["]}); + case ")": return d(s,{i:["("]}); + case ">>": return d(s,{i:["<<"]}); + case "end": return d(s,{i:["begin","case","fun","if","receive","try"]}); + case ",": return d(s,{e:["begin","try","when","->", + ",","(","[","{","<<"]}); + case "->": return d(s,{r:["when"], + m:["try","if","case","receive"]}); + case ";": return d(s,{E:["case","fun","if","receive","try","when"]}); + case "catch":return d(s,{e:["try"]}); + case "of": return d(s,{e:["case"]}); + case "after":return d(s,{e:["receive","try"]}); + default: return s; + } + } + + function d(stack,tt) { + // stack is a stack of Token objects. + // tt is an object; {type:tokens} + // type is a char, tokens is a list of token strings. + // The function returns (possibly truncated) stack. + // It will descend the stack, looking for a Token such that Token.token + // is a member of tokens. If it does not find that, it will normally (but + // see "E" below) return stack. If it does find a match, it will remove + // all the Tokens between the top and the matched Token. + // If type is "m", that is all it does. + // If type is "i", it will also remove the matched Token and the top Token. + // If type is "g", like "i", but add a fake "group" token at the top. + // If type is "r", it will remove the matched Token, but not the top Token. + // If type is "e", it will keep the matched Token but not the top Token. + // If type is "E", it behaves as for type "e", except if there is no match, + // in which case it will return an empty stack. + + for (var type in tt) { + var len = stack.length-1; + var tokens = tt[type]; + for (var i = len-1; -1 < i ; i--) { + if (is_member(stack[i].token,tokens)) { + var ss = stack.slice(0,i); + switch (type) { + case "m": return ss.concat(stack[i]).concat(stack[len]); + case "r": return ss.concat(stack[len]); + case "i": return ss; + case "g": return ss.concat(fakeToken("group")); + case "E": return ss.concat(stack[i]); + case "e": return ss.concat(stack[i]); + } + } + } + } + return (type == "E" ? [] : stack); + } + +///////////////////////////////////////////////////////////////////////////// +// indenter + + function indenter(state,textAfter) { + var t; + var unit = cmCfg.indentUnit; + var wordAfter = wordafter(textAfter); + var currT = peekToken(state,1); + var prevT = peekToken(state,2); + + if (state.in_string || state.in_atom) { + return CodeMirror.Pass; + }else if (!prevT) { + return 0; + }else if (currT.token == "when") { + return currT.column+unit; + }else if (wordAfter === "when" && prevT.type === "function") { + return prevT.indent+unit; + }else if (wordAfter === "(" && currT.token === "fun") { + return currT.column+3; + }else if (wordAfter === "catch" && (t = getToken(state,["try"]))) { + return t.column; + }else if (is_member(wordAfter,["end","after","of"])) { + t = getToken(state,["begin","case","fun","if","receive","try"]); + return t ? t.column : CodeMirror.Pass; + }else if (is_member(wordAfter,closeParenWords)) { + t = getToken(state,openParenWords); + return t ? t.column : CodeMirror.Pass; + }else if (is_member(currT.token,[",","|","||"]) || + is_member(wordAfter,[",","|","||"])) { + t = postcommaToken(state); + return t ? t.column+t.token.length : unit; + }else if (currT.token == "->") { + if (is_member(prevT.token, ["receive","case","if","try"])) { + return prevT.column+unit+unit; + }else{ + return prevT.column+unit; + } + }else if (is_member(currT.token,openParenWords)) { + return currT.column+currT.token.length; + }else{ + t = defaultToken(state); + return truthy(t) ? t.column+unit : 0; + } + } + + function wordafter(str) { + var m = str.match(/,|[a-z]+|\}|\]|\)|>>|\|+|\(/); + + return truthy(m) && (m.index === 0) ? m[0] : ""; + } + + function postcommaToken(state) { + var objs = state.tokenStack.slice(0,-1); + var i = getTokenIndex(objs,"type",["open_paren"]); + + return truthy(objs[i]) ? objs[i] : false; + } + + function defaultToken(state) { + var objs = state.tokenStack; + var stop = getTokenIndex(objs,"type",["open_paren","separator","keyword"]); + var oper = getTokenIndex(objs,"type",["operator"]); + + if (truthy(stop) && truthy(oper) && stop < oper) { + return objs[stop+1]; + } else if (truthy(stop)) { + return objs[stop]; + } else { + return false; + } + } + + function getToken(state,tokens) { + var objs = state.tokenStack; + var i = getTokenIndex(objs,"token",tokens); + + return truthy(objs[i]) ? objs[i] : false; + } + + function getTokenIndex(objs,propname,propvals) { + + for (var i = objs.length-1; -1 < i ; i--) { + if (is_member(objs[i][propname],propvals)) { + return i; + } + } + return false; + } + + function truthy(x) { + return (x !== false) && (x != null); + } + +///////////////////////////////////////////////////////////////////////////// +// this object defines the mode + + return { + startState: + function() { + return {tokenStack: [], + in_string: false, + in_atom: false}; + }, + + token: + function(stream, state) { + return tokenizer(stream, state); + }, + + indent: + function(state, textAfter) { + return indenter(state,textAfter); + }, + + lineComment: "%" + }; +}); + +}); diff --git a/modules/editor/codemirror/mode/gfm/test.min.js b/modules/editor/codemirror/mode/gfm/test.min.js @@ -0,0 +1,198 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function() { + var config = {tabSize: 4, indentUnit: 2} + var mode = CodeMirror.getMode(config, "gfm"); + function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } + var modeHighlightFormatting = CodeMirror.getMode(config, {name: "gfm", highlightFormatting: true}); + function FT(name) { test.mode(name, modeHighlightFormatting, Array.prototype.slice.call(arguments, 1)); } + + FT("codeBackticks", + "[comment&formatting&formatting-code `][comment foo][comment&formatting&formatting-code `]"); + + FT("doubleBackticks", + "[comment&formatting&formatting-code ``][comment foo ` bar][comment&formatting&formatting-code ``]"); + + FT("taskList", + "[variable-2&formatting&formatting-list&formatting-list-ul - ][meta&formatting&formatting-task [ ]]][variable-2 foo]", + "[variable-2&formatting&formatting-list&formatting-list-ul - ][property&formatting&formatting-task [x]]][variable-2 foo]"); + + FT("formatting_strikethrough", + "[strikethrough&formatting&formatting-strikethrough ~~][strikethrough foo][strikethrough&formatting&formatting-strikethrough ~~]"); + + FT("formatting_strikethrough", + "foo [strikethrough&formatting&formatting-strikethrough ~~][strikethrough bar][strikethrough&formatting&formatting-strikethrough ~~]"); + + FT("formatting_emoji", + "foo [builtin&formatting&formatting-emoji :smile:] foo"); + + MT("emInWordAsterisk", + "foo[em *bar*]hello"); + + MT("emInWordUnderscore", + "foo_bar_hello"); + + MT("emStrongUnderscore", + "[em&strong ___foo___] bar"); + + MT("taskListAsterisk", + "[variable-2 * ][link&variable-2 [[]]][variable-2 foo]", // Invalid; must have space or x between [] + "[variable-2 * ][link&variable-2 [[ ]]][variable-2 bar]", // Invalid; must have space after ] + "[variable-2 * ][link&variable-2 [[x]]][variable-2 hello]", // Invalid; must have space after ] + "[variable-2 * ][meta [ ]]][variable-2 ][link&variable-2 [[world]]]", // Valid; tests reference style links + " [variable-3 * ][property [x]]][variable-3 foo]"); // Valid; can be nested + + MT("taskListPlus", + "[variable-2 + ][link&variable-2 [[]]][variable-2 foo]", // Invalid; must have space or x between [] + "[variable-2 + ][link&variable-2 [[x]]][variable-2 hello]", // Invalid; must have space after ] + "[variable-2 + ][meta [ ]]][variable-2 ][link&variable-2 [[world]]]", // Valid; tests reference style links + " [variable-3 + ][property [x]]][variable-3 foo]"); // Valid; can be nested + + MT("taskListDash", + "[variable-2 - ][link&variable-2 [[]]][variable-2 foo]", // Invalid; must have space or x between [] + "[variable-2 - ][link&variable-2 [[x]]][variable-2 hello]", // Invalid; must have space after ] + "[variable-2 - ][meta [ ]]][variable-2 world]", // Valid; tests reference style links + " [variable-3 - ][property [x]]][variable-3 foo]"); // Valid; can be nested + + MT("taskListNumber", + "[variable-2 1. ][link&variable-2 [[]]][variable-2 foo]", // Invalid; must have space or x between [] + "[variable-2 2. ][link&variable-2 [[ ]]][variable-2 bar]", // Invalid; must have space after ] + "[variable-2 3. ][meta [ ]]][variable-2 world]", // Valid; tests reference style links + " [variable-3 1. ][property [x]]][variable-3 foo]"); // Valid; can be nested + + MT("SHA", + "foo [link be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2] bar"); + + MT("SHAEmphasis", + "[em *foo ][em&link be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2][em *]"); + + MT("shortSHA", + "foo [link be6a8cc] bar"); + + MT("tooShortSHA", + "foo be6a8c bar"); + + MT("longSHA", + "foo be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd22 bar"); + + MT("badSHA", + "foo be6a8cc1c1ecfe9489fb51e4869af15a13fc2cg2 bar"); + + MT("userSHA", + "foo [link bar@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2] hello"); + + MT("userSHAEmphasis", + "[em *foo ][em&link bar@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2][em *]"); + + MT("userProjectSHA", + "foo [link bar/hello@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2] world"); + + MT("userProjectSHAEmphasis", + "[em *foo ][em&link bar/hello@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2][em *]"); + + MT("wordSHA", + "ask for feedbac") + + MT("num", + "foo [link #1] bar"); + + MT("numEmphasis", + "[em *foo ][em&link #1][em *]"); + + MT("badNum", + "foo #1bar hello"); + + MT("userNum", + "foo [link bar#1] hello"); + + MT("userNumEmphasis", + "[em *foo ][em&link bar#1][em *]"); + + MT("userProjectNum", + "foo [link bar/hello#1] world"); + + MT("userProjectNumEmphasis", + "[em *foo ][em&link bar/hello#1][em *]"); + + MT("vanillaLink", + "foo [link http://www.example.com/] bar"); + + MT("vanillaLinkNoScheme", + "foo [link www.example.com] bar"); + + MT("vanillaLinkHttps", + "foo [link https://www.example.com/] bar"); + + MT("vanillaLinkDataSchema", + "foo [link data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==] bar"); + + MT("vanillaLinkPunctuation", + "foo [link http://www.example.com/]. bar"); + + MT("vanillaLinkExtension", + "foo [link http://www.example.com/index.html] bar"); + + MT("vanillaLinkEmphasis", + "foo [em *][em&link http://www.example.com/index.html][em *] bar"); + + MT("notALink", + "foo asfd:asdf bar"); + + MT("notALink", + "[comment ``foo `bar` http://www.example.com/``] hello"); + + MT("notALink", + "[comment `foo]", + "[comment&link http://www.example.com/]", + "[comment `] foo", + "", + "[link http://www.example.com/]"); + + MT("strikethrough", + "[strikethrough ~~foo~~]"); + + MT("strikethroughWithStartingSpace", + "~~ foo~~"); + + MT("strikethroughUnclosedStrayTildes", + "[strikethrough ~~foo~~~]"); + + MT("strikethroughUnclosedStrayTildes", + "[strikethrough ~~foo ~~]"); + + MT("strikethroughUnclosedStrayTildes", + "[strikethrough ~~foo ~~ bar]"); + + MT("strikethroughUnclosedStrayTildes", + "[strikethrough ~~foo ~~ bar~~]hello"); + + MT("strikethroughOneLetter", + "[strikethrough ~~a~~]"); + + MT("strikethroughWrapped", + "[strikethrough ~~foo]", + "[strikethrough foo~~]"); + + MT("strikethroughParagraph", + "[strikethrough ~~foo]", + "", + "foo[strikethrough ~~bar]"); + + MT("strikethroughEm", + "[strikethrough ~~foo][em&strikethrough *bar*][strikethrough ~~]"); + + MT("strikethroughEm", + "[em *][em&strikethrough ~~foo~~][em *]"); + + MT("strikethroughStrong", + "[strikethrough ~~][strong&strikethrough **foo**][strikethrough ~~]"); + + MT("strikethroughStrong", + "[strong **][strong&strikethrough ~~foo~~][strong **]"); + + MT("emoji", + "text [builtin :blush:] text [builtin :v:] text [builtin :+1:] text", + ":text text: [builtin :smiley_cat:]"); + +})(); diff --git a/modules/editor/codemirror/mode/gherkin/gherkin.min.js b/modules/editor/codemirror/mode/gherkin/gherkin.min.js @@ -0,0 +1,178 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +/* +Gherkin mode - http://www.cukes.info/ +Report bugs/issues here: https://github.com/codemirror/CodeMirror/issues +*/ + +// Following Objs from Brackets implementation: https://github.com/tregusti/brackets-gherkin/blob/master/main.js +//var Quotes = { +// SINGLE: 1, +// DOUBLE: 2 +//}; + +//var regex = { +// keywords: /(Feature| {2}(Scenario|In order to|As|I)| {4}(Given|When|Then|And))/ +//}; + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode("gherkin", function () { + return { + startState: function () { + return { + lineNumber: 0, + tableHeaderLine: false, + allowFeature: true, + allowBackground: false, + allowScenario: false, + allowSteps: false, + allowPlaceholders: false, + allowMultilineArgument: false, + inMultilineString: false, + inMultilineTable: false, + inKeywordLine: false + }; + }, + token: function (stream, state) { + if (stream.sol()) { + state.lineNumber++; + state.inKeywordLine = false; + if (state.inMultilineTable) { + state.tableHeaderLine = false; + if (!stream.match(/\s*\|/, false)) { + state.allowMultilineArgument = false; + state.inMultilineTable = false; + } + } + } + + stream.eatSpace(); + + if (state.allowMultilineArgument) { + + // STRING + if (state.inMultilineString) { + if (stream.match('"""')) { + state.inMultilineString = false; + state.allowMultilineArgument = false; + } else { + stream.match(/.*/); + } + return "string"; + } + + // TABLE + if (state.inMultilineTable) { + if (stream.match(/\|\s*/)) { + return "bracket"; + } else { + stream.match(/[^\|]*/); + return state.tableHeaderLine ? "header" : "string"; + } + } + + // DETECT START + if (stream.match('"""')) { + // String + state.inMultilineString = true; + return "string"; + } else if (stream.match("|")) { + // Table + state.inMultilineTable = true; + state.tableHeaderLine = true; + return "bracket"; + } + + } + + // LINE COMMENT + if (stream.match(/#.*/)) { + return "comment"; + + // TAG + } else if (!state.inKeywordLine && stream.match(/@\S+/)) { + return "tag"; + + // FEATURE + } else if (!state.inKeywordLine && state.allowFeature && stream.match(/(機能|功能|フィーチャ|기능|โครงหลัก|ความสามารถ|ความต้องการทางธุรกิจ|ಹೆಚ್ಚಳ|గుణము|ਮੁਹਾਂਦਰਾ|ਨਕਸ਼ ਨੁਹਾਰ|ਖਾਸੀਅਤ|रूप लेख|وِیژگی|خاصية|תכונה|Функціонал|Функция|Функционалност|Функционал|Үзенчәлеклелек|Свойство|Особина|Мөмкинлек|Могућност|Λειτουργία|Δυνατότητα|Właściwość|Vlastnosť|Trajto|Tính năng|Savybė|Pretty much|Požiadavka|Požadavek|Potrzeba biznesowa|Özellik|Osobina|Ominaisuus|Omadus|OH HAI|Mogućnost|Mogucnost|Jellemző|Hwæt|Hwaet|Funzionalità|Funktionalitéit|Funktionalität|Funkcja|Funkcionalnost|Funkcionalitāte|Funkcia|Fungsi|Functionaliteit|Funcționalitate|Funcţionalitate|Functionalitate|Funcionalitat|Funcionalidade|Fonctionnalité|Fitur|Fīča|Feature|Eiginleiki|Egenskap|Egenskab|Característica|Caracteristica|Business Need|Aspekt|Arwedd|Ahoy matey!|Ability):/)) { + state.allowScenario = true; + state.allowBackground = true; + state.allowPlaceholders = false; + state.allowSteps = false; + state.allowMultilineArgument = false; + state.inKeywordLine = true; + return "keyword"; + + // BACKGROUND + } else if (!state.inKeywordLine && state.allowBackground && stream.match(/(背景|배경|แนวคิด|ಹಿನ್ನೆಲೆ|నేపథ్యం|ਪਿਛੋਕੜ|पृष्ठभूमि|زمینه|الخلفية|רקע|Тарих|Предыстория|Предистория|Позадина|Передумова|Основа|Контекст|Кереш|Υπόβαθρο|Założenia|Yo\-ho\-ho|Tausta|Taust|Situācija|Rerefons|Pozadina|Pozadie|Pozadí|Osnova|Latar Belakang|Kontext|Konteksts|Kontekstas|Kontekst|Háttér|Hannergrond|Grundlage|Geçmiş|Fundo|Fono|First off|Dis is what went down|Dasar|Contexto|Contexte|Context|Contesto|Cenário de Fundo|Cenario de Fundo|Cefndir|Bối cảnh|Bakgrunnur|Bakgrunn|Bakgrund|Baggrund|Background|B4|Antecedents|Antecedentes|Ær|Aer|Achtergrond):/)) { + state.allowPlaceholders = false; + state.allowSteps = true; + state.allowBackground = false; + state.allowMultilineArgument = false; + state.inKeywordLine = true; + return "keyword"; + + // SCENARIO OUTLINE + } else if (!state.inKeywordLine && state.allowScenario && stream.match(/(場景大綱|场景大纲|劇本大綱|剧本大纲|テンプレ|シナリオテンプレート|シナリオテンプレ|シナリオアウトライン|시나리오 개요|สรุปเหตุการณ์|โครงสร้างของเหตุการณ์|ವಿವರಣೆ|కథనం|ਪਟਕਥਾ ਰੂਪ ਰੇਖਾ|ਪਟਕਥਾ ਢਾਂਚਾ|परिदृश्य रूपरेखा|سيناريو مخطط|الگوی سناریو|תבנית תרחיש|Сценарийның төзелеше|Сценарий структураси|Структура сценарію|Структура сценария|Структура сценарија|Скица|Рамка на сценарий|Концепт|Περιγραφή Σεναρίου|Wharrimean is|Template Situai|Template Senario|Template Keadaan|Tapausaihio|Szenariogrundriss|Szablon scenariusza|Swa hwær swa|Swa hwaer swa|Struktura scenarija|Structură scenariu|Structura scenariu|Skica|Skenario konsep|Shiver me timbers|Senaryo taslağı|Schema dello scenario|Scenariomall|Scenariomal|Scenario Template|Scenario Outline|Scenario Amlinellol|Scenārijs pēc parauga|Scenarijaus šablonas|Reckon it's like|Raamstsenaarium|Plang vum Szenario|Plan du Scénario|Plan du scénario|Osnova scénáře|Osnova Scenára|Náčrt Scenáru|Náčrt Scénáře|Náčrt Scenára|MISHUN SRSLY|Menggariskan Senario|Lýsing Dæma|Lýsing Atburðarásar|Konturo de la scenaro|Koncept|Khung tình huống|Khung kịch bản|Forgatókönyv vázlat|Esquema do Cenário|Esquema do Cenario|Esquema del escenario|Esquema de l'escenari|Esbozo do escenario|Delineação do Cenário|Delineacao do Cenario|All y'all|Abstrakt Scenario|Abstract Scenario):/)) { + state.allowPlaceholders = true; + state.allowSteps = true; + state.allowMultilineArgument = false; + state.inKeywordLine = true; + return "keyword"; + + // EXAMPLES + } else if (state.allowScenario && stream.match(/(例子|例|サンプル|예|ชุดของเหตุการณ์|ชุดของตัวอย่าง|ಉದಾಹರಣೆಗಳು|ఉదాహరణలు|ਉਦਾਹਰਨਾਂ|उदाहरण|نمونه ها|امثلة|דוגמאות|Үрнәкләр|Сценарији|Примеры|Примери|Приклади|Мисоллар|Мисаллар|Σενάρια|Παραδείγματα|You'll wanna|Voorbeelden|Variantai|Tapaukset|Se þe|Se the|Se ðe|Scenarios|Scenariji|Scenarijai|Przykłady|Primjeri|Primeri|Příklady|Príklady|Piemēri|Példák|Pavyzdžiai|Paraugs|Örnekler|Juhtumid|Exemplos|Exemples|Exemple|Exempel|EXAMPLZ|Examples|Esempi|Enghreifftiau|Ekzemploj|Eksempler|Ejemplos|Dữ liệu|Dead men tell no tales|Dæmi|Contoh|Cenários|Cenarios|Beispiller|Beispiele|Atburðarásir):/)) { + state.allowPlaceholders = false; + state.allowSteps = true; + state.allowBackground = false; + state.allowMultilineArgument = true; + return "keyword"; + + // SCENARIO + } else if (!state.inKeywordLine && state.allowScenario && stream.match(/(場景|场景|劇本|剧本|シナリオ|시나리오|เหตุการณ์|ಕಥಾಸಾರಾಂಶ|సన్నివేశం|ਪਟਕਥਾ|परिदृश्य|سيناريو|سناریو|תרחיש|Сценарій|Сценарио|Сценарий|Пример|Σενάριο|Tình huống|The thing of it is|Tapaus|Szenario|Swa|Stsenaarium|Skenario|Situai|Senaryo|Senario|Scenaro|Scenariusz|Scenariu|Scénario|Scenario|Scenarijus|Scenārijs|Scenarij|Scenarie|Scénář|Scenár|Primer|MISHUN|Kịch bản|Keadaan|Heave to|Forgatókönyv|Escenario|Escenari|Cenário|Cenario|Awww, look mate|Atburðarás):/)) { + state.allowPlaceholders = false; + state.allowSteps = true; + state.allowBackground = false; + state.allowMultilineArgument = false; + state.inKeywordLine = true; + return "keyword"; + + // STEPS + } else if (!state.inKeywordLine && state.allowSteps && stream.match(/(那麼|那么|而且|當|当|并且|同時|同时|前提|假设|假設|假定|假如|但是|但し|並且|もし|ならば|ただし|しかし|かつ|하지만|조건|먼저|만일|만약|단|그리고|그러면|และ |เมื่อ |แต่ |ดังนั้น |กำหนดให้ |ಸ್ಥಿತಿಯನ್ನು |ಮತ್ತು |ನೀಡಿದ |ನಂತರ |ಆದರೆ |మరియు |చెప్పబడినది |కాని |ఈ పరిస్థితిలో |అప్పుడు |ਪਰ |ਤਦ |ਜੇਕਰ |ਜਿਵੇਂ ਕਿ |ਜਦੋਂ |ਅਤੇ |यदि |परन्तु |पर |तब |तदा |तथा |जब |चूंकि |किन्तु |कदा |और |अगर |و |هنگامی |متى |لكن |عندما |ثم |بفرض |با فرض |اما |اذاً |آنگاه |כאשר |וגם |בהינתן |אזי |אז |אבל |Якщо |Һәм |Унда |Тоді |Тогда |То |Также |Та |Пусть |Припустимо, що |Припустимо |Онда |Но |Нехай |Нәтиҗәдә |Лекин |Ләкин |Коли |Когда |Когато |Када |Кад |К тому же |І |И |Задато |Задати |Задате |Если |Допустим |Дано |Дадено |Вә |Ва |Бирок |Әмма |Әйтик |Әгәр |Аммо |Али |Але |Агар |А також |А |Τότε |Όταν |Και |Δεδομένου |Αλλά |Þurh |Þegar |Þa þe |Þá |Þa |Zatati |Zakładając |Zadato |Zadate |Zadano |Zadani |Zadan |Za předpokladu |Za predpokladu |Youse know when youse got |Youse know like when |Yna |Yeah nah |Y'know |Y |Wun |Wtedy |When y'all |When |Wenn |WEN |wann |Ve |Và |Und |Un |ugeholl |Too right |Thurh |Thì |Then y'all |Then |Tha the |Tha |Tetapi |Tapi |Tak |Tada |Tad |Stel |Soit |Siis |Și |Şi |Si |Sed |Se |Så |Quando |Quand |Quan |Pryd |Potom |Pokud |Pokiaľ |Però |Pero |Pak |Oraz |Onda |Ond |Oletetaan |Og |Och |O zaman |Niin |Nhưng |När |Når |Mutta |Men |Mas |Maka |Majd |Mając |Mais |Maar |mä |Ma |Lorsque |Lorsqu'|Logo |Let go and haul |Kun |Kuid |Kui |Kiedy |Khi |Ketika |Kemudian |Keď |Když |Kaj |Kai |Kada |Kad |Jeżeli |Jeśli |Ja |It's just unbelievable |Ir |I CAN HAZ |I |Ha |Givun |Givet |Given y'all |Given |Gitt |Gegeven |Gegeben seien |Gegeben sei |Gdy |Gangway! |Fakat |Étant donnés |Etant donnés |Étant données |Etant données |Étant donnée |Etant donnée |Étant donné |Etant donné |Et |És |Entonces |Entón |Então |Entao |En |Eğer ki |Ef |Eeldades |E |Ðurh |Duota |Dun |Donitaĵo |Donat |Donada |Do |Diyelim ki |Diberi |Dengan |Den youse gotta |DEN |De |Dato |Dați fiind |Daţi fiind |Dati fiind |Dati |Date fiind |Date |Data |Dat fiind |Dar |Dann |dann |Dan |Dados |Dado |Dadas |Dada |Ða ðe |Ða |Cuando |Cho |Cando |Când |Cand |Cal |But y'all |But at the end of the day I reckon |BUT |But |Buh |Blimey! |Biết |Bet |Bagi |Aye |awer |Avast! |Atunci |Atesa |Atès |Apabila |Anrhegedig a |Angenommen |And y'all |And |AN |An |an |Amikor |Amennyiben |Ama |Als |Alors |Allora |Ali |Aleshores |Ale |Akkor |Ak |Adott |Ac |Aber |A zároveň |A tiež |A taktiež |A také |A |a |7 |\* )/)) { + state.inStep = true; + state.allowPlaceholders = true; + state.allowMultilineArgument = true; + state.inKeywordLine = true; + return "keyword"; + + // INLINE STRING + } else if (stream.match(/"[^"]*"?/)) { + return "string"; + + // PLACEHOLDER + } else if (state.allowPlaceholders && stream.match(/<[^>]*>?/)) { + return "variable"; + + // Fall through + } else { + stream.next(); + stream.eatWhile(/[^@"<#]/); + return null; + } + } + }; +}); + +CodeMirror.defineMIME("text/x-feature", "gherkin"); + +}); diff --git a/modules/editor/codemirror/mode/go/go.min.js b/modules/editor/codemirror/mode/go/go.min.js @@ -0,0 +1,187 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode("go", function(config) { + var indentUnit = config.indentUnit; + + var keywords = { + "break":true, "case":true, "chan":true, "const":true, "continue":true, + "default":true, "defer":true, "else":true, "fallthrough":true, "for":true, + "func":true, "go":true, "goto":true, "if":true, "import":true, + "interface":true, "map":true, "package":true, "range":true, "return":true, + "select":true, "struct":true, "switch":true, "type":true, "var":true, + "bool":true, "byte":true, "complex64":true, "complex128":true, + "float32":true, "float64":true, "int8":true, "int16":true, "int32":true, + "int64":true, "string":true, "uint8":true, "uint16":true, "uint32":true, + "uint64":true, "int":true, "uint":true, "uintptr":true, "error": true, + "rune":true + }; + + var atoms = { + "true":true, "false":true, "iota":true, "nil":true, "append":true, + "cap":true, "close":true, "complex":true, "copy":true, "delete":true, "imag":true, + "len":true, "make":true, "new":true, "panic":true, "print":true, + "println":true, "real":true, "recover":true + }; + + var isOperatorChar = /[+\-*&^%:=<>!|\/]/; + + var curPunc; + + function tokenBase(stream, state) { + var ch = stream.next(); + if (ch == '"' || ch == "'" || ch == "`") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } + if (/[\d\.]/.test(ch)) { + if (ch == ".") { + stream.match(/^[0-9]+([eE][\-+]?[0-9]+)?/); + } else if (ch == "0") { + stream.match(/^[xX][0-9a-fA-F]+/) || stream.match(/^0[0-7]+/); + } else { + stream.match(/^[0-9]*\.?[0-9]*([eE][\-+]?[0-9]+)?/); + } + return "number"; + } + if (/[\[\]{}\(\),;\:\.]/.test(ch)) { + curPunc = ch; + return null; + } + if (ch == "/") { + if (stream.eat("*")) { + state.tokenize = tokenComment; + return tokenComment(stream, state); + } + if (stream.eat("/")) { + stream.skipToEnd(); + return "comment"; + } + } + if (isOperatorChar.test(ch)) { + stream.eatWhile(isOperatorChar); + return "operator"; + } + stream.eatWhile(/[\w\$_\xa1-\uffff]/); + var cur = stream.current(); + if (keywords.propertyIsEnumerable(cur)) { + if (cur == "case" || cur == "default") curPunc = "case"; + return "keyword"; + } + if (atoms.propertyIsEnumerable(cur)) return "atom"; + return "variable"; + } + + function tokenString(quote) { + return function(stream, state) { + var escaped = false, next, end = false; + while ((next = stream.next()) != null) { + if (next == quote && !escaped) {end = true; break;} + escaped = !escaped && quote != "`" && next == "\\"; + } + if (end || !(escaped || quote == "`")) + state.tokenize = tokenBase; + return "string"; + }; + } + + function tokenComment(stream, state) { + var maybeEnd = false, ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize = tokenBase; + break; + } + maybeEnd = (ch == "*"); + } + return "comment"; + } + + function Context(indented, column, type, align, prev) { + this.indented = indented; + this.column = column; + this.type = type; + this.align = align; + this.prev = prev; + } + function pushContext(state, col, type) { + return state.context = new Context(state.indented, col, type, null, state.context); + } + function popContext(state) { + if (!state.context.prev) return; + var t = state.context.type; + if (t == ")" || t == "]" || t == "}") + state.indented = state.context.indented; + return state.context = state.context.prev; + } + + // Interface + + return { + startState: function(basecolumn) { + return { + tokenize: null, + context: new Context((basecolumn || 0) - indentUnit, 0, "top", false), + indented: 0, + startOfLine: true + }; + }, + + token: function(stream, state) { + var ctx = state.context; + if (stream.sol()) { + if (ctx.align == null) ctx.align = false; + state.indented = stream.indentation(); + state.startOfLine = true; + if (ctx.type == "case") ctx.type = "}"; + } + if (stream.eatSpace()) return null; + curPunc = null; + var style = (state.tokenize || tokenBase)(stream, state); + if (style == "comment") return style; + if (ctx.align == null) ctx.align = true; + + if (curPunc == "{") pushContext(state, stream.column(), "}"); + else if (curPunc == "[") pushContext(state, stream.column(), "]"); + else if (curPunc == "(") pushContext(state, stream.column(), ")"); + else if (curPunc == "case") ctx.type = "case"; + else if (curPunc == "}" && ctx.type == "}") popContext(state); + else if (curPunc == ctx.type) popContext(state); + state.startOfLine = false; + return style; + }, + + indent: function(state, textAfter) { + if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass; + var ctx = state.context, firstChar = textAfter && textAfter.charAt(0); + if (ctx.type == "case" && /^(?:case|default)\b/.test(textAfter)) { + state.context.type = "}"; + return ctx.indented; + } + var closing = firstChar == ctx.type; + if (ctx.align) return ctx.column + (closing ? 0 : 1); + else return ctx.indented + (closing ? 0 : indentUnit); + }, + + electricChars: "{}):", + closeBrackets: "()[]{}''\"\"``", + fold: "brace", + blockCommentStart: "/*", + blockCommentEnd: "*/", + lineComment: "//" + }; +}); + +CodeMirror.defineMIME("text/x-go", "go"); + +}); diff --git a/modules/editor/codemirror/mode/groovy/groovy.min.js b/modules/editor/codemirror/mode/groovy/groovy.min.js @@ -0,0 +1,230 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode("groovy", function(config) { + function words(str) { + var obj = {}, words = str.split(" "); + for (var i = 0; i < words.length; ++i) obj[words[i]] = true; + return obj; + } + var keywords = words( + "abstract as assert boolean break byte case catch char class const continue def default " + + "do double else enum extends final finally float for goto if implements import in " + + "instanceof int interface long native new package private protected public return " + + "short static strictfp super switch synchronized threadsafe throw throws trait transient " + + "try void volatile while"); + var blockKeywords = words("catch class def do else enum finally for if interface switch trait try while"); + var standaloneKeywords = words("return break continue"); + var atoms = words("null true false this"); + + var curPunc; + function tokenBase(stream, state) { + var ch = stream.next(); + if (ch == '"' || ch == "'") { + return startString(ch, stream, state); + } + if (/[\[\]{}\(\),;\:\.]/.test(ch)) { + curPunc = ch; + return null; + } + if (/\d/.test(ch)) { + stream.eatWhile(/[\w\.]/); + if (stream.eat(/eE/)) { stream.eat(/\+\-/); stream.eatWhile(/\d/); } + return "number"; + } + if (ch == "/") { + if (stream.eat("*")) { + state.tokenize.push(tokenComment); + return tokenComment(stream, state); + } + if (stream.eat("/")) { + stream.skipToEnd(); + return "comment"; + } + if (expectExpression(state.lastToken, false)) { + return startString(ch, stream, state); + } + } + if (ch == "-" && stream.eat(">")) { + curPunc = "->"; + return null; + } + if (/[+\-*&%=<>!?|\/~]/.test(ch)) { + stream.eatWhile(/[+\-*&%=<>|~]/); + return "operator"; + } + stream.eatWhile(/[\w\$_]/); + if (ch == "@") { stream.eatWhile(/[\w\$_\.]/); return "meta"; } + if (state.lastToken == ".") return "property"; + if (stream.eat(":")) { curPunc = "proplabel"; return "property"; } + var cur = stream.current(); + if (atoms.propertyIsEnumerable(cur)) { return "atom"; } + if (keywords.propertyIsEnumerable(cur)) { + if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement"; + else if (standaloneKeywords.propertyIsEnumerable(cur)) curPunc = "standalone"; + return "keyword"; + } + return "variable"; + } + tokenBase.isBase = true; + + function startString(quote, stream, state) { + var tripleQuoted = false; + if (quote != "/" && stream.eat(quote)) { + if (stream.eat(quote)) tripleQuoted = true; + else return "string"; + } + function t(stream, state) { + var escaped = false, next, end = !tripleQuoted; + while ((next = stream.next()) != null) { + if (next == quote && !escaped) { + if (!tripleQuoted) { break; } + if (stream.match(quote + quote)) { end = true; break; } + } + if (quote == '"' && next == "$" && !escaped && stream.eat("{")) { + state.tokenize.push(tokenBaseUntilBrace()); + return "string"; + } + escaped = !escaped && next == "\\"; + } + if (end) state.tokenize.pop(); + return "string"; + } + state.tokenize.push(t); + return t(stream, state); + } + + function tokenBaseUntilBrace() { + var depth = 1; + function t(stream, state) { + if (stream.peek() == "}") { + depth--; + if (depth == 0) { + state.tokenize.pop(); + return state.tokenize[state.tokenize.length-1](stream, state); + } + } else if (stream.peek() == "{") { + depth++; + } + return tokenBase(stream, state); + } + t.isBase = true; + return t; + } + + function tokenComment(stream, state) { + var maybeEnd = false, ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize.pop(); + break; + } + maybeEnd = (ch == "*"); + } + return "comment"; + } + + function expectExpression(last, newline) { + return !last || last == "operator" || last == "->" || /[\.\[\{\(,;:]/.test(last) || + last == "newstatement" || last == "keyword" || last == "proplabel" || + (last == "standalone" && !newline); + } + + function Context(indented, column, type, align, prev) { + this.indented = indented; + this.column = column; + this.type = type; + this.align = align; + this.prev = prev; + } + function pushContext(state, col, type) { + return state.context = new Context(state.indented, col, type, null, state.context); + } + function popContext(state) { + var t = state.context.type; + if (t == ")" || t == "]" || t == "}") + state.indented = state.context.indented; + return state.context = state.context.prev; + } + + // Interface + + return { + startState: function(basecolumn) { + return { + tokenize: [tokenBase], + context: new Context((basecolumn || 0) - config.indentUnit, 0, "top", false), + indented: 0, + startOfLine: true, + lastToken: null + }; + }, + + token: function(stream, state) { + var ctx = state.context; + if (stream.sol()) { + if (ctx.align == null) ctx.align = false; + state.indented = stream.indentation(); + state.startOfLine = true; + // Automatic semicolon insertion + if (ctx.type == "statement" && !expectExpression(state.lastToken, true)) { + popContext(state); ctx = state.context; + } + } + if (stream.eatSpace()) return null; + curPunc = null; + var style = state.tokenize[state.tokenize.length-1](stream, state); + if (style == "comment") return style; + if (ctx.align == null) ctx.align = true; + + if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state); + // Handle indentation for {x -> \n ... } + else if (curPunc == "->" && ctx.type == "statement" && ctx.prev.type == "}") { + popContext(state); + state.context.align = false; + } + else if (curPunc == "{") pushContext(state, stream.column(), "}"); + else if (curPunc == "[") pushContext(state, stream.column(), "]"); + else if (curPunc == "(") pushContext(state, stream.column(), ")"); + else if (curPunc == "}") { + while (ctx.type == "statement") ctx = popContext(state); + if (ctx.type == "}") ctx = popContext(state); + while (ctx.type == "statement") ctx = popContext(state); + } + else if (curPunc == ctx.type) popContext(state); + else if (ctx.type == "}" || ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement")) + pushContext(state, stream.column(), "statement"); + state.startOfLine = false; + state.lastToken = curPunc || style; + return style; + }, + + indent: function(state, textAfter) { + if (!state.tokenize[state.tokenize.length-1].isBase) return CodeMirror.Pass; + var firstChar = textAfter && textAfter.charAt(0), ctx = state.context; + if (ctx.type == "statement" && !expectExpression(state.lastToken, true)) ctx = ctx.prev; + var closing = firstChar == ctx.type; + if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : config.indentUnit); + else if (ctx.align) return ctx.column + (closing ? 0 : 1); + else return ctx.indented + (closing ? 0 : config.indentUnit); + }, + + electricChars: "{}", + closeBrackets: {triples: "'\""}, + fold: "brace" + }; +}); + +CodeMirror.defineMIME("text/x-groovy", "groovy"); + +}); diff --git a/modules/editor/codemirror/mode/htmlembedded/htmlembedded.min.js b/modules/editor/codemirror/mode/htmlembedded/htmlembedded.min.js @@ -0,0 +1,28 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror"), require("../htmlmixed/htmlmixed"), + require("../../addon/mode/multiplex")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror", "../htmlmixed/htmlmixed", + "../../addon/mode/multiplex"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + CodeMirror.defineMode("htmlembedded", function(config, parserConfig) { + return CodeMirror.multiplexingMode(CodeMirror.getMode(config, "htmlmixed"), { + open: parserConfig.open || parserConfig.scriptStartRegex || "<%", + close: parserConfig.close || parserConfig.scriptEndRegex || "%>", + mode: CodeMirror.getMode(config, parserConfig.scriptingModeSpec) + }); + }, "htmlmixed"); + + CodeMirror.defineMIME("application/x-ejs", {name: "htmlembedded", scriptingModeSpec:"javascript"}); + CodeMirror.defineMIME("application/x-aspx", {name: "htmlembedded", scriptingModeSpec:"text/x-csharp"}); + CodeMirror.defineMIME("application/x-jsp", {name: "htmlembedded", scriptingModeSpec:"text/x-java"}); + CodeMirror.defineMIME("application/x-erb", {name: "htmlembedded", scriptingModeSpec:"ruby"}); +}); diff --git a/modules/editor/codemirror/mode/livescript/livescript.min.js b/modules/editor/codemirror/mode/livescript/livescript.min.js @@ -0,0 +1,280 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +/** + * Link to the project's GitHub page: + * https://github.com/duralog/CodeMirror + */ + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + CodeMirror.defineMode('livescript', function(){ + var tokenBase = function(stream, state) { + var next_rule = state.next || "start"; + if (next_rule) { + state.next = state.next; + var nr = Rules[next_rule]; + if (nr.splice) { + for (var i$ = 0; i$ < nr.length; ++i$) { + var r = nr[i$]; + if (r.regex && stream.match(r.regex)) { + state.next = r.next || state.next; + return r.token; + } + } + stream.next(); + return 'error'; + } + if (stream.match(r = Rules[next_rule])) { + if (r.regex && stream.match(r.regex)) { + state.next = r.next; + return r.token; + } else { + stream.next(); + return 'error'; + } + } + } + stream.next(); + return 'error'; + }; + var external = { + startState: function(){ + return { + next: 'start', + lastToken: {style: null, indent: 0, content: ""} + }; + }, + token: function(stream, state){ + while (stream.pos == stream.start) + var style = tokenBase(stream, state); + state.lastToken = { + style: style, + indent: stream.indentation(), + content: stream.current() + }; + return style.replace(/\./g, ' '); + }, + indent: function(state){ + var indentation = state.lastToken.indent; + if (state.lastToken.content.match(indenter)) { + indentation += 2; + } + return indentation; + } + }; + return external; + }); + + var identifier = '(?![\\d\\s])[$\\w\\xAA-\\uFFDC](?:(?!\\s)[$\\w\\xAA-\\uFFDC]|-[A-Za-z])*'; + var indenter = RegExp('(?:[({[=:]|[-~]>|\\b(?:e(?:lse|xport)|d(?:o|efault)|t(?:ry|hen)|finally|import(?:\\s*all)?|const|var|let|new|catch(?:\\s*' + identifier + ')?))\\s*$'); + var keywordend = '(?![$\\w]|-[A-Za-z]|\\s*:(?![:=]))'; + var stringfill = { + token: 'string', + regex: '.+' + }; + var Rules = { + start: [ + { + token: 'comment.doc', + regex: '/\\*', + next: 'comment' + }, { + token: 'comment', + regex: '#.*' + }, { + token: 'keyword', + regex: '(?:t(?:h(?:is|row|en)|ry|ypeof!?)|c(?:on(?:tinue|st)|a(?:se|tch)|lass)|i(?:n(?:stanceof)?|mp(?:ort(?:\\s+all)?|lements)|[fs])|d(?:e(?:fault|lete|bugger)|o)|f(?:or(?:\\s+own)?|inally|unction)|s(?:uper|witch)|e(?:lse|x(?:tends|port)|val)|a(?:nd|rguments)|n(?:ew|ot)|un(?:less|til)|w(?:hile|ith)|o[fr]|return|break|let|var|loop)' + keywordend + }, { + token: 'constant.language', + regex: '(?:true|false|yes|no|on|off|null|void|undefined)' + keywordend + }, { + token: 'invalid.illegal', + regex: '(?:p(?:ackage|r(?:ivate|otected)|ublic)|i(?:mplements|nterface)|enum|static|yield)' + keywordend + }, { + token: 'language.support.class', + regex: '(?:R(?:e(?:gExp|ferenceError)|angeError)|S(?:tring|yntaxError)|E(?:rror|valError)|Array|Boolean|Date|Function|Number|Object|TypeError|URIError)' + keywordend + }, { + token: 'language.support.function', + regex: '(?:is(?:NaN|Finite)|parse(?:Int|Float)|Math|JSON|(?:en|de)codeURI(?:Component)?)' + keywordend + }, { + token: 'variable.language', + regex: '(?:t(?:hat|il|o)|f(?:rom|allthrough)|it|by|e)' + keywordend + }, { + token: 'identifier', + regex: identifier + '\\s*:(?![:=])' + }, { + token: 'variable', + regex: identifier + }, { + token: 'keyword.operator', + regex: '(?:\\.{3}|\\s+\\?)' + }, { + token: 'keyword.variable', + regex: '(?:@+|::|\\.\\.)', + next: 'key' + }, { + token: 'keyword.operator', + regex: '\\.\\s*', + next: 'key' + }, { + token: 'string', + regex: '\\\\\\S[^\\s,;)}\\]]*' + }, { + token: 'string.doc', + regex: '\'\'\'', + next: 'qdoc' + }, { + token: 'string.doc', + regex: '"""', + next: 'qqdoc' + }, { + token: 'string', + regex: '\'', + next: 'qstring' + }, { + token: 'string', + regex: '"', + next: 'qqstring' + }, { + token: 'string', + regex: '`', + next: 'js' + }, { + token: 'string', + regex: '<\\[', + next: 'words' + }, { + token: 'string.regex', + regex: '//', + next: 'heregex' + }, { + token: 'string.regex', + regex: '\\/(?:[^[\\/\\n\\\\]*(?:(?:\\\\.|\\[[^\\]\\n\\\\]*(?:\\\\.[^\\]\\n\\\\]*)*\\])[^[\\/\\n\\\\]*)*)\\/[gimy$]{0,4}', + next: 'key' + }, { + token: 'constant.numeric', + regex: '(?:0x[\\da-fA-F][\\da-fA-F_]*|(?:[2-9]|[12]\\d|3[0-6])r[\\da-zA-Z][\\da-zA-Z_]*|(?:\\d[\\d_]*(?:\\.\\d[\\d_]*)?|\\.\\d[\\d_]*)(?:e[+-]?\\d[\\d_]*)?[\\w$]*)' + }, { + token: 'lparen', + regex: '[({[]' + }, { + token: 'rparen', + regex: '[)}\\]]', + next: 'key' + }, { + token: 'keyword.operator', + regex: '\\S+' + }, { + token: 'text', + regex: '\\s+' + } + ], + heregex: [ + { + token: 'string.regex', + regex: '.*?//[gimy$?]{0,4}', + next: 'start' + }, { + token: 'string.regex', + regex: '\\s*#{' + }, { + token: 'comment.regex', + regex: '\\s+(?:#.*)?' + }, { + token: 'string.regex', + regex: '\\S+' + } + ], + key: [ + { + token: 'keyword.operator', + regex: '[.?@!]+' + }, { + token: 'identifier', + regex: identifier, + next: 'start' + }, { + token: 'text', + regex: '', + next: 'start' + } + ], + comment: [ + { + token: 'comment.doc', + regex: '.*?\\*/', + next: 'start' + }, { + token: 'comment.doc', + regex: '.+' + } + ], + qdoc: [ + { + token: 'string', + regex: ".*?'''", + next: 'key' + }, stringfill + ], + qqdoc: [ + { + token: 'string', + regex: '.*?"""', + next: 'key' + }, stringfill + ], + qstring: [ + { + token: 'string', + regex: '[^\\\\\']*(?:\\\\.[^\\\\\']*)*\'', + next: 'key' + }, stringfill + ], + qqstring: [ + { + token: 'string', + regex: '[^\\\\"]*(?:\\\\.[^\\\\"]*)*"', + next: 'key' + }, stringfill + ], + js: [ + { + token: 'string', + regex: '[^\\\\`]*(?:\\\\.[^\\\\`]*)*`', + next: 'key' + }, stringfill + ], + words: [ + { + token: 'string', + regex: '.*?\\]>', + next: 'key' + }, stringfill + ] + }; + for (var idx in Rules) { + var r = Rules[idx]; + if (r.splice) { + for (var i = 0, len = r.length; i < len; ++i) { + var rr = r[i]; + if (typeof rr.regex === 'string') { + Rules[idx][i].regex = new RegExp('^' + rr.regex); + } + } + } else if (typeof rr.regex === 'string') { + Rules[idx].regex = new RegExp('^' + r.regex); + } + } + + CodeMirror.defineMIME('text/x-livescript', 'livescript'); + +}); diff --git a/modules/editor/codemirror/mode/lua/lua.min.js b/modules/editor/codemirror/mode/lua/lua.min.js @@ -0,0 +1,159 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// LUA mode. Ported to CodeMirror 2 from Franciszek Wawrzak's +// CodeMirror 1 mode. +// highlights keywords, strings, comments (no leveling supported! ("[==[")), tokens, basic indenting + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode("lua", function(config, parserConfig) { + var indentUnit = config.indentUnit; + + function prefixRE(words) { + return new RegExp("^(?:" + words.join("|") + ")", "i"); + } + function wordRE(words) { + return new RegExp("^(?:" + words.join("|") + ")$", "i"); + } + var specials = wordRE(parserConfig.specials || []); + + // long list of standard functions from lua manual + var builtins = wordRE([ + "_G","_VERSION","assert","collectgarbage","dofile","error","getfenv","getmetatable","ipairs","load", + "loadfile","loadstring","module","next","pairs","pcall","print","rawequal","rawget","rawset","require", + "select","setfenv","setmetatable","tonumber","tostring","type","unpack","xpcall", + + "coroutine.create","coroutine.resume","coroutine.running","coroutine.status","coroutine.wrap","coroutine.yield", + + "debug.debug","debug.getfenv","debug.gethook","debug.getinfo","debug.getlocal","debug.getmetatable", + "debug.getregistry","debug.getupvalue","debug.setfenv","debug.sethook","debug.setlocal","debug.setmetatable", + "debug.setupvalue","debug.traceback", + + "close","flush","lines","read","seek","setvbuf","write", + + "io.close","io.flush","io.input","io.lines","io.open","io.output","io.popen","io.read","io.stderr","io.stdin", + "io.stdout","io.tmpfile","io.type","io.write", + + "math.abs","math.acos","math.asin","math.atan","math.atan2","math.ceil","math.cos","math.cosh","math.deg", + "math.exp","math.floor","math.fmod","math.frexp","math.huge","math.ldexp","math.log","math.log10","math.max", + "math.min","math.modf","math.pi","math.pow","math.rad","math.random","math.randomseed","math.sin","math.sinh", + "math.sqrt","math.tan","math.tanh", + + "os.clock","os.date","os.difftime","os.execute","os.exit","os.getenv","os.remove","os.rename","os.setlocale", + "os.time","os.tmpname", + + "package.cpath","package.loaded","package.loaders","package.loadlib","package.path","package.preload", + "package.seeall", + + "string.byte","string.char","string.dump","string.find","string.format","string.gmatch","string.gsub", + "string.len","string.lower","string.match","string.rep","string.reverse","string.sub","string.upper", + + "table.concat","table.insert","table.maxn","table.remove","table.sort" + ]); + var keywords = wordRE(["and","break","elseif","false","nil","not","or","return", + "true","function", "end", "if", "then", "else", "do", + "while", "repeat", "until", "for", "in", "local" ]); + + var indentTokens = wordRE(["function", "if","repeat","do", "\\(", "{"]); + var dedentTokens = wordRE(["end", "until", "\\)", "}"]); + var dedentPartial = prefixRE(["end", "until", "\\)", "}", "else", "elseif"]); + + function readBracket(stream) { + var level = 0; + while (stream.eat("=")) ++level; + stream.eat("["); + return level; + } + + function normal(stream, state) { + var ch = stream.next(); + if (ch == "-" && stream.eat("-")) { + if (stream.eat("[") && stream.eat("[")) + return (state.cur = bracketed(readBracket(stream), "comment"))(stream, state); + stream.skipToEnd(); + return "comment"; + } + if (ch == "\"" || ch == "'") + return (state.cur = string(ch))(stream, state); + if (ch == "[" && /[\[=]/.test(stream.peek())) + return (state.cur = bracketed(readBracket(stream), "string"))(stream, state); + if (/\d/.test(ch)) { + stream.eatWhile(/[\w.%]/); + return "number"; + } + if (/[\w_]/.test(ch)) { + stream.eatWhile(/[\w\\\-_.]/); + return "variable"; + } + return null; + } + + function bracketed(level, style) { + return function(stream, state) { + var curlev = null, ch; + while ((ch = stream.next()) != null) { + if (curlev == null) {if (ch == "]") curlev = 0;} + else if (ch == "=") ++curlev; + else if (ch == "]" && curlev == level) { state.cur = normal; break; } + else curlev = null; + } + return style; + }; + } + + function string(quote) { + return function(stream, state) { + var escaped = false, ch; + while ((ch = stream.next()) != null) { + if (ch == quote && !escaped) break; + escaped = !escaped && ch == "\\"; + } + if (!escaped) state.cur = normal; + return "string"; + }; + } + + return { + startState: function(basecol) { + return {basecol: basecol || 0, indentDepth: 0, cur: normal}; + }, + + token: function(stream, state) { + if (stream.eatSpace()) return null; + var style = state.cur(stream, state); + var word = stream.current(); + if (style == "variable") { + if (keywords.test(word)) style = "keyword"; + else if (builtins.test(word)) style = "builtin"; + else if (specials.test(word)) style = "variable-2"; + } + if ((style != "comment") && (style != "string")){ + if (indentTokens.test(word)) ++state.indentDepth; + else if (dedentTokens.test(word)) --state.indentDepth; + } + return style; + }, + + indent: function(state, textAfter) { + var closing = dedentPartial.test(textAfter); + return state.basecol + indentUnit * (state.indentDepth - (closing ? 1 : 0)); + }, + + lineComment: "--", + blockCommentStart: "--[[", + blockCommentEnd: "]]" + }; +}); + +CodeMirror.defineMIME("text/x-lua", "lua"); + +}); diff --git a/modules/editor/codemirror/mode/mathematica/mathematica.min.js b/modules/editor/codemirror/mode/mathematica/mathematica.min.js @@ -0,0 +1,176 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// Mathematica mode copyright (c) 2015 by Calin Barbat +// Based on code by Patrick Scheibe (halirutan) +// See: https://github.com/halirutan/Mathematica-Source-Highlighting/tree/master/src/lang-mma.js + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode('mathematica', function(_config, _parserConfig) { + + // used pattern building blocks + var Identifier = '[a-zA-Z\\$][a-zA-Z0-9\\$]*'; + var pBase = "(?:\\d+)"; + var pFloat = "(?:\\.\\d+|\\d+\\.\\d*|\\d+)"; + var pFloatBase = "(?:\\.\\w+|\\w+\\.\\w*|\\w+)"; + var pPrecision = "(?:`(?:`?"+pFloat+")?)"; + + // regular expressions + var reBaseForm = new RegExp('(?:'+pBase+'(?:\\^\\^'+pFloatBase+pPrecision+'?(?:\\*\\^[+-]?\\d+)?))'); + var reFloatForm = new RegExp('(?:' + pFloat + pPrecision + '?(?:\\*\\^[+-]?\\d+)?)'); + var reIdInContext = new RegExp('(?:`?)(?:' + Identifier + ')(?:`(?:' + Identifier + '))*(?:`?)'); + + function tokenBase(stream, state) { + var ch; + + // get next character + ch = stream.next(); + + // string + if (ch === '"') { + state.tokenize = tokenString; + return state.tokenize(stream, state); + } + + // comment + if (ch === '(') { + if (stream.eat('*')) { + state.commentLevel++; + state.tokenize = tokenComment; + return state.tokenize(stream, state); + } + } + + // go back one character + stream.backUp(1); + + // look for numbers + // Numbers in a baseform + if (stream.match(reBaseForm, true, false)) { + return 'number'; + } + + // Mathematica numbers. Floats (1.2, .2, 1.) can have optionally a precision (`float) or an accuracy definition + // (``float). Note: while 1.2` is possible 1.2`` is not. At the end an exponent (float*^+12) can follow. + if (stream.match(reFloatForm, true, false)) { + return 'number'; + } + + /* In[23] and Out[34] */ + if (stream.match(/(?:In|Out)\[[0-9]*\]/, true, false)) { + return 'atom'; + } + + // usage + if (stream.match(/([a-zA-Z\$]+(?:`?[a-zA-Z0-9\$])*::usage)/, true, false)) { + return 'meta'; + } + + // message + if (stream.match(/([a-zA-Z\$]+(?:`?[a-zA-Z0-9\$])*::[a-zA-Z\$][a-zA-Z0-9\$]*):?/, true, false)) { + return 'string-2'; + } + + // this makes a look-ahead match for something like variable:{_Integer} + // the match is then forwarded to the mma-patterns tokenizer. + if (stream.match(/([a-zA-Z\$][a-zA-Z0-9\$]*\s*:)(?:(?:[a-zA-Z\$][a-zA-Z0-9\$]*)|(?:[^:=>~@\^\&\*\)\[\]'\?,\|])).*/, true, false)) { + return 'variable-2'; + } + + // catch variables which are used together with Blank (_), BlankSequence (__) or BlankNullSequence (___) + // Cannot start with a number, but can have numbers at any other position. Examples + // blub__Integer, a1_, b34_Integer32 + if (stream.match(/[a-zA-Z\$][a-zA-Z0-9\$]*_+[a-zA-Z\$][a-zA-Z0-9\$]*/, true, false)) { + return 'variable-2'; + } + if (stream.match(/[a-zA-Z\$][a-zA-Z0-9\$]*_+/, true, false)) { + return 'variable-2'; + } + if (stream.match(/_+[a-zA-Z\$][a-zA-Z0-9\$]*/, true, false)) { + return 'variable-2'; + } + + // Named characters in Mathematica, like \[Gamma]. + if (stream.match(/\\\[[a-zA-Z\$][a-zA-Z0-9\$]*\]/, true, false)) { + return 'variable-3'; + } + + // Match all braces separately + if (stream.match(/(?:\[|\]|{|}|\(|\))/, true, false)) { + return 'bracket'; + } + + // Catch Slots (#, ##, #3, ##9 and the V10 named slots #name). I have never seen someone using more than one digit after #, so we match + // only one. + if (stream.match(/(?:#[a-zA-Z\$][a-zA-Z0-9\$]*|#+[0-9]?)/, true, false)) { + return 'variable-2'; + } + + // Literals like variables, keywords, functions + if (stream.match(reIdInContext, true, false)) { + return 'keyword'; + } + + // operators. Note that operators like @@ or /; are matched separately for each symbol. + if (stream.match(/(?:\\|\+|\-|\*|\/|,|;|\.|:|@|~|=|>|<|&|\||_|`|'|\^|\?|!|%)/, true, false)) { + return 'operator'; + } + + // everything else is an error + stream.next(); // advance the stream. + return 'error'; + } + + function tokenString(stream, state) { + var next, end = false, escaped = false; + while ((next = stream.next()) != null) { + if (next === '"' && !escaped) { + end = true; + break; + } + escaped = !escaped && next === '\\'; + } + if (end && !escaped) { + state.tokenize = tokenBase; + } + return 'string'; + }; + + function tokenComment(stream, state) { + var prev, next; + while(state.commentLevel > 0 && (next = stream.next()) != null) { + if (prev === '(' && next === '*') state.commentLevel++; + if (prev === '*' && next === ')') state.commentLevel--; + prev = next; + } + if (state.commentLevel <= 0) { + state.tokenize = tokenBase; + } + return 'comment'; + } + + return { + startState: function() {return {tokenize: tokenBase, commentLevel: 0};}, + token: function(stream, state) { + if (stream.eatSpace()) return null; + return state.tokenize(stream, state); + }, + blockCommentStart: "(*", + blockCommentEnd: "*)" + }; +}); + +CodeMirror.defineMIME('text/x-mathematica', { + name: 'mathematica' +}); + +}); diff --git a/modules/editor/codemirror/mode/mirc/mirc.min.js b/modules/editor/codemirror/mode/mirc/mirc.min.js @@ -0,0 +1,193 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +//mIRC mode by Ford_Lawnmower :: Based on Velocity mode by Steve O'Hara + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMIME("text/mirc", "mirc"); +CodeMirror.defineMode("mirc", function() { + function parseWords(str) { + var obj = {}, words = str.split(" "); + for (var i = 0; i < words.length; ++i) obj[words[i]] = true; + return obj; + } + var specials = parseWords("$! $$ $& $? $+ $abook $abs $active $activecid " + + "$activewid $address $addtok $agent $agentname $agentstat $agentver " + + "$alias $and $anick $ansi2mirc $aop $appactive $appstate $asc $asctime " + + "$asin $atan $avoice $away $awaymsg $awaytime $banmask $base $bfind " + + "$binoff $biton $bnick $bvar $bytes $calc $cb $cd $ceil $chan $chanmodes " + + "$chantypes $chat $chr $cid $clevel $click $cmdbox $cmdline $cnick $color " + + "$com $comcall $comchan $comerr $compact $compress $comval $cos $count " + + "$cr $crc $creq $crlf $ctime $ctimer $ctrlenter $date $day $daylight " + + "$dbuh $dbuw $dccignore $dccport $dde $ddename $debug $decode $decompress " + + "$deltok $devent $dialog $did $didreg $didtok $didwm $disk $dlevel $dll " + + "$dllcall $dname $dns $duration $ebeeps $editbox $emailaddr $encode $error " + + "$eval $event $exist $feof $ferr $fgetc $file $filename $filtered $finddir " + + "$finddirn $findfile $findfilen $findtok $fline $floor $fopen $fread $fserve " + + "$fulladdress $fulldate $fullname $fullscreen $get $getdir $getdot $gettok $gmt " + + "$group $halted $hash $height $hfind $hget $highlight $hnick $hotline " + + "$hotlinepos $ial $ialchan $ibl $idle $iel $ifmatch $ignore $iif $iil " + + "$inelipse $ini $inmidi $inpaste $inpoly $input $inrect $inroundrect " + + "$insong $instok $int $inwave $ip $isalias $isbit $isdde $isdir $isfile " + + "$isid $islower $istok $isupper $keychar $keyrpt $keyval $knick $lactive " + + "$lactivecid $lactivewid $left $len $level $lf $line $lines $link $lock " + + "$lock $locked $log $logstamp $logstampfmt $longfn $longip $lower $ltimer " + + "$maddress $mask $matchkey $matchtok $md5 $me $menu $menubar $menucontext " + + "$menutype $mid $middir $mircdir $mircexe $mircini $mklogfn $mnick $mode " + + "$modefirst $modelast $modespl $mouse $msfile $network $newnick $nick $nofile " + + "$nopath $noqt $not $notags $notify $null $numeric $numok $oline $onpoly " + + "$opnick $or $ord $os $passivedcc $pic $play $pnick $port $portable $portfree " + + "$pos $prefix $prop $protect $puttok $qt $query $rand $r $rawmsg $read $readomo " + + "$readn $regex $regml $regsub $regsubex $remove $remtok $replace $replacex " + + "$reptok $result $rgb $right $round $scid $scon $script $scriptdir $scriptline " + + "$sdir $send $server $serverip $sfile $sha1 $shortfn $show $signal $sin " + + "$site $sline $snick $snicks $snotify $sock $sockbr $sockerr $sockname " + + "$sorttok $sound $sqrt $ssl $sreq $sslready $status $strip $str $stripped " + + "$syle $submenu $switchbar $tan $target $ticks $time $timer $timestamp " + + "$timestampfmt $timezone $tip $titlebar $toolbar $treebar $trust $ulevel " + + "$ulist $upper $uptime $url $usermode $v1 $v2 $var $vcmd $vcmdstat $vcmdver " + + "$version $vnick $vol $wid $width $wildsite $wildtok $window $wrap $xor"); + var keywords = parseWords("abook ajinvite alias aline ame amsg anick aop auser autojoin avoice " + + "away background ban bcopy beep bread break breplace bset btrunc bunset bwrite " + + "channel clear clearall cline clipboard close cnick color comclose comopen " + + "comreg continue copy creq ctcpreply ctcps dcc dccserver dde ddeserver " + + "debug dec describe dialog did didtok disable disconnect dlevel dline dll " + + "dns dqwindow drawcopy drawdot drawfill drawline drawpic drawrect drawreplace " + + "drawrot drawsave drawscroll drawtext ebeeps echo editbox emailaddr enable " + + "events exit fclose filter findtext finger firewall flash flist flood flush " + + "flushini font fopen fseek fsend fserve fullname fwrite ghide gload gmove " + + "gopts goto gplay gpoint gqreq groups gshow gsize gstop gtalk gunload hadd " + + "halt haltdef hdec hdel help hfree hinc hload hmake hop hsave ial ialclear " + + "ialmark identd if ignore iline inc invite iuser join kick linesep links list " + + "load loadbuf localinfo log mdi me menubar mkdir mnick mode msg nick noop notice " + + "notify omsg onotice part partall pdcc perform play playctrl pop protect pvoice " + + "qme qmsg query queryn quit raw reload remini remote remove rename renwin " + + "reseterror resetidle return rlevel rline rmdir run ruser save savebuf saveini " + + "say scid scon server set showmirc signam sline sockaccept sockclose socklist " + + "socklisten sockmark sockopen sockpause sockread sockrename sockudp sockwrite " + + "sound speak splay sreq strip switchbar timer timestamp titlebar tnick tokenize " + + "toolbar topic tray treebar ulist unload unset unsetall updatenl url uwho " + + "var vcadd vcmd vcrem vol while whois window winhelp write writeint if isalnum " + + "isalpha isaop isavoice isban ischan ishop isignore isin isincs isletter islower " + + "isnotify isnum ison isop isprotect isreg isupper isvoice iswm iswmcs " + + "elseif else goto menu nicklist status title icon size option text edit " + + "button check radio box scroll list combo link tab item"); + var functions = parseWords("if elseif else and not or eq ne in ni for foreach while switch"); + var isOperatorChar = /[+\-*&%=<>!?^\/\|]/; + function chain(stream, state, f) { + state.tokenize = f; + return f(stream, state); + } + function tokenBase(stream, state) { + var beforeParams = state.beforeParams; + state.beforeParams = false; + var ch = stream.next(); + if (/[\[\]{}\(\),\.]/.test(ch)) { + if (ch == "(" && beforeParams) state.inParams = true; + else if (ch == ")") state.inParams = false; + return null; + } + else if (/\d/.test(ch)) { + stream.eatWhile(/[\w\.]/); + return "number"; + } + else if (ch == "\\") { + stream.eat("\\"); + stream.eat(/./); + return "number"; + } + else if (ch == "/" && stream.eat("*")) { + return chain(stream, state, tokenComment); + } + else if (ch == ";" && stream.match(/ *\( *\(/)) { + return chain(stream, state, tokenUnparsed); + } + else if (ch == ";" && !state.inParams) { + stream.skipToEnd(); + return "comment"; + } + else if (ch == '"') { + stream.eat(/"/); + return "keyword"; + } + else if (ch == "$") { + stream.eatWhile(/[$_a-z0-9A-Z\.:]/); + if (specials && specials.propertyIsEnumerable(stream.current().toLowerCase())) { + return "keyword"; + } + else { + state.beforeParams = true; + return "builtin"; + } + } + else if (ch == "%") { + stream.eatWhile(/[^,\s()]/); + state.beforeParams = true; + return "string"; + } + else if (isOperatorChar.test(ch)) { + stream.eatWhile(isOperatorChar); + return "operator"; + } + else { + stream.eatWhile(/[\w\$_{}]/); + var word = stream.current().toLowerCase(); + if (keywords && keywords.propertyIsEnumerable(word)) + return "keyword"; + if (functions && functions.propertyIsEnumerable(word)) { + state.beforeParams = true; + return "keyword"; + } + return null; + } + } + function tokenComment(stream, state) { + var maybeEnd = false, ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize = tokenBase; + break; + } + maybeEnd = (ch == "*"); + } + return "comment"; + } + function tokenUnparsed(stream, state) { + var maybeEnd = 0, ch; + while (ch = stream.next()) { + if (ch == ";" && maybeEnd == 2) { + state.tokenize = tokenBase; + break; + } + if (ch == ")") + maybeEnd++; + else if (ch != " ") + maybeEnd = 0; + } + return "meta"; + } + return { + startState: function() { + return { + tokenize: tokenBase, + beforeParams: false, + inParams: false + }; + }, + token: function(stream, state) { + if (stream.eatSpace()) return null; + return state.tokenize(stream, state); + } + }; +}); + +}); diff --git a/modules/editor/codemirror/mode/modelica/modelica.min.js b/modules/editor/codemirror/mode/modelica/modelica.min.js @@ -0,0 +1,245 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// Modelica support for CodeMirror, copyright (c) by Lennart Ochel + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +}) + +(function(CodeMirror) { + "use strict"; + + CodeMirror.defineMode("modelica", function(config, parserConfig) { + + var indentUnit = config.indentUnit; + var keywords = parserConfig.keywords || {}; + var builtin = parserConfig.builtin || {}; + var atoms = parserConfig.atoms || {}; + + var isSingleOperatorChar = /[;=\(:\),{}.*<>+\-\/^\[\]]/; + var isDoubleOperatorChar = /(:=|<=|>=|==|<>|\.\+|\.\-|\.\*|\.\/|\.\^)/; + var isDigit = /[0-9]/; + var isNonDigit = /[_a-zA-Z]/; + + function tokenLineComment(stream, state) { + stream.skipToEnd(); + state.tokenize = null; + return "comment"; + } + + function tokenBlockComment(stream, state) { + var maybeEnd = false, ch; + while (ch = stream.next()) { + if (maybeEnd && ch == "/") { + state.tokenize = null; + break; + } + maybeEnd = (ch == "*"); + } + return "comment"; + } + + function tokenString(stream, state) { + var escaped = false, ch; + while ((ch = stream.next()) != null) { + if (ch == '"' && !escaped) { + state.tokenize = null; + state.sol = false; + break; + } + escaped = !escaped && ch == "\\"; + } + + return "string"; + } + + function tokenIdent(stream, state) { + stream.eatWhile(isDigit); + while (stream.eat(isDigit) || stream.eat(isNonDigit)) { } + + + var cur = stream.current(); + + if(state.sol && (cur == "package" || cur == "model" || cur == "when" || cur == "connector")) state.level++; + else if(state.sol && cur == "end" && state.level > 0) state.level--; + + state.tokenize = null; + state.sol = false; + + if (keywords.propertyIsEnumerable(cur)) return "keyword"; + else if (builtin.propertyIsEnumerable(cur)) return "builtin"; + else if (atoms.propertyIsEnumerable(cur)) return "atom"; + else return "variable"; + } + + function tokenQIdent(stream, state) { + while (stream.eat(/[^']/)) { } + + state.tokenize = null; + state.sol = false; + + if(stream.eat("'")) + return "variable"; + else + return "error"; + } + + function tokenUnsignedNuber(stream, state) { + stream.eatWhile(isDigit); + if (stream.eat('.')) { + stream.eatWhile(isDigit); + } + if (stream.eat('e') || stream.eat('E')) { + if (!stream.eat('-')) + stream.eat('+'); + stream.eatWhile(isDigit); + } + + state.tokenize = null; + state.sol = false; + return "number"; + } + + // Interface + return { + startState: function() { + return { + tokenize: null, + level: 0, + sol: true + }; + }, + + token: function(stream, state) { + if(state.tokenize != null) { + return state.tokenize(stream, state); + } + + if(stream.sol()) { + state.sol = true; + } + + // WHITESPACE + if(stream.eatSpace()) { + state.tokenize = null; + return null; + } + + var ch = stream.next(); + + // LINECOMMENT + if(ch == '/' && stream.eat('/')) { + state.tokenize = tokenLineComment; + } + // BLOCKCOMMENT + else if(ch == '/' && stream.eat('*')) { + state.tokenize = tokenBlockComment; + } + // TWO SYMBOL TOKENS + else if(isDoubleOperatorChar.test(ch+stream.peek())) { + stream.next(); + state.tokenize = null; + return "operator"; + } + // SINGLE SYMBOL TOKENS + else if(isSingleOperatorChar.test(ch)) { + state.tokenize = null; + return "operator"; + } + // IDENT + else if(isNonDigit.test(ch)) { + state.tokenize = tokenIdent; + } + // Q-IDENT + else if(ch == "'" && stream.peek() && stream.peek() != "'") { + state.tokenize = tokenQIdent; + } + // STRING + else if(ch == '"') { + state.tokenize = tokenString; + } + // UNSIGNED_NUBER + else if(isDigit.test(ch)) { + state.tokenize = tokenUnsignedNuber; + } + // ERROR + else { + state.tokenize = null; + return "error"; + } + + return state.tokenize(stream, state); + }, + + indent: function(state, textAfter) { + if (state.tokenize != null) return CodeMirror.Pass; + + var level = state.level; + if(/(algorithm)/.test(textAfter)) level--; + if(/(equation)/.test(textAfter)) level--; + if(/(initial algorithm)/.test(textAfter)) level--; + if(/(initial equation)/.test(textAfter)) level--; + if(/(end)/.test(textAfter)) level--; + + if(level > 0) + return indentUnit*level; + else + return 0; + }, + + blockCommentStart: "/*", + blockCommentEnd: "*/", + lineComment: "//" + }; + }); + + function words(str) { + var obj = {}, words = str.split(" "); + for (var i=0; i<words.length; ++i) + obj[words[i]] = true; + return obj; + } + + var modelicaKeywords = "algorithm and annotation assert block break class connect connector constant constrainedby der discrete each else elseif elsewhen encapsulated end enumeration equation expandable extends external false final flow for function if import impure in initial inner input loop model not operator or outer output package parameter partial protected public pure record redeclare replaceable return stream then true type when while within"; + var modelicaBuiltin = "abs acos actualStream asin atan atan2 cardinality ceil cos cosh delay div edge exp floor getInstanceName homotopy inStream integer log log10 mod pre reinit rem semiLinear sign sin sinh spatialDistribution sqrt tan tanh"; + var modelicaAtoms = "Real Boolean Integer String"; + + function def(mimes, mode) { + if (typeof mimes == "string") + mimes = [mimes]; + + var words = []; + + function add(obj) { + if (obj) + for (var prop in obj) + if (obj.hasOwnProperty(prop)) + words.push(prop); + } + + add(mode.keywords); + add(mode.builtin); + add(mode.atoms); + + if (words.length) { + mode.helperType = mimes[0]; + CodeMirror.registerHelper("hintWords", mimes[0], words); + } + + for (var i=0; i<mimes.length; ++i) + CodeMirror.defineMIME(mimes[i], mode); + } + + def(["text/x-modelica"], { + name: "modelica", + keywords: words(modelicaKeywords), + builtin: words(modelicaBuiltin), + atoms: words(modelicaAtoms) + }); +}); diff --git a/modules/editor/codemirror/mode/mscgen/mscgen.min.js b/modules/editor/codemirror/mode/mscgen/mscgen.min.js @@ -0,0 +1,175 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// mode(s) for the sequence chart dsl's mscgen, xù and msgenny +// For more information on mscgen, see the site of the original author: +// http://www.mcternan.me.uk/mscgen +// +// This mode for mscgen and the two derivative languages were +// originally made for use in the mscgen_js interpreter +// (https://sverweij.github.io/mscgen_js) + +(function(mod) { + if ( typeof exports == "object" && typeof module == "object")// CommonJS + mod(require("../../lib/codemirror")); + else if ( typeof define == "function" && define.amd)// AMD + define(["../../lib/codemirror"], mod); + else// Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + var languages = { + mscgen: { + "keywords" : ["msc"], + "options" : ["hscale", "width", "arcgradient", "wordwraparcs"], + "constants" : ["true", "false", "on", "off"], + "attributes" : ["label", "idurl", "id", "url", "linecolor", "linecolour", "textcolor", "textcolour", "textbgcolor", "textbgcolour", "arclinecolor", "arclinecolour", "arctextcolor", "arctextcolour", "arctextbgcolor", "arctextbgcolour", "arcskip"], + "brackets" : ["\\{", "\\}"], // [ and ] are brackets too, but these get handled in with lists + "arcsWords" : ["note", "abox", "rbox", "box"], + "arcsOthers" : ["\\|\\|\\|", "\\.\\.\\.", "---", "--", "<->", "==", "<<=>>", "<=>", "\\.\\.", "<<>>", "::", "<:>", "->", "=>>", "=>", ">>", ":>", "<-", "<<=", "<=", "<<", "<:", "x-", "-x"], + "singlecomment" : ["//", "#"], + "operators" : ["="] + }, + xu: { + "keywords" : ["msc", "xu"], + "options" : ["hscale", "width", "arcgradient", "wordwraparcs", "watermark"], + "constants" : ["true", "false", "on", "off", "auto"], + "attributes" : ["label", "idurl", "id", "url", "linecolor", "linecolour", "textcolor", "textcolour", "textbgcolor", "textbgcolour", "arclinecolor", "arclinecolour", "arctextcolor", "arctextcolour", "arctextbgcolor", "arctextbgcolour", "arcskip"], + "brackets" : ["\\{", "\\}"], // [ and ] are brackets too, but these get handled in with lists + "arcsWords" : ["note", "abox", "rbox", "box", "alt", "else", "opt", "break", "par", "seq", "strict", "neg", "critical", "ignore", "consider", "assert", "loop", "ref", "exc"], + "arcsOthers" : ["\\|\\|\\|", "\\.\\.\\.", "---", "--", "<->", "==", "<<=>>", "<=>", "\\.\\.", "<<>>", "::", "<:>", "->", "=>>", "=>", ">>", ":>", "<-", "<<=", "<=", "<<", "<:", "x-", "-x"], + "singlecomment" : ["//", "#"], + "operators" : ["="] + }, + msgenny: { + "keywords" : null, + "options" : ["hscale", "width", "arcgradient", "wordwraparcs", "watermark"], + "constants" : ["true", "false", "on", "off", "auto"], + "attributes" : null, + "brackets" : ["\\{", "\\}"], + "arcsWords" : ["note", "abox", "rbox", "box", "alt", "else", "opt", "break", "par", "seq", "strict", "neg", "critical", "ignore", "consider", "assert", "loop", "ref", "exc"], + "arcsOthers" : ["\\|\\|\\|", "\\.\\.\\.", "---", "--", "<->", "==", "<<=>>", "<=>", "\\.\\.", "<<>>", "::", "<:>", "->", "=>>", "=>", ">>", ":>", "<-", "<<=", "<=", "<<", "<:", "x-", "-x"], + "singlecomment" : ["//", "#"], + "operators" : ["="] + } + } + + CodeMirror.defineMode("mscgen", function(_, modeConfig) { + var language = languages[modeConfig && modeConfig.language || "mscgen"] + return { + startState: startStateFn, + copyState: copyStateFn, + token: produceTokenFunction(language), + lineComment : "#", + blockCommentStart : "/*", + blockCommentEnd : "*/" + }; + }); + + CodeMirror.defineMIME("text/x-mscgen", "mscgen"); + CodeMirror.defineMIME("text/x-xu", {name: "mscgen", language: "xu"}); + CodeMirror.defineMIME("text/x-msgenny", {name: "mscgen", language: "msgenny"}); + + function wordRegexpBoundary(pWords) { + return new RegExp("\\b(" + pWords.join("|") + ")\\b", "i"); + } + + function wordRegexp(pWords) { + return new RegExp("(" + pWords.join("|") + ")", "i"); + } + + function startStateFn() { + return { + inComment : false, + inString : false, + inAttributeList : false, + inScript : false + }; + } + + function copyStateFn(pState) { + return { + inComment : pState.inComment, + inString : pState.inString, + inAttributeList : pState.inAttributeList, + inScript : pState.inScript + }; + } + + function produceTokenFunction(pConfig) { + + return function(pStream, pState) { + if (pStream.match(wordRegexp(pConfig.brackets), true, true)) { + return "bracket"; + } + /* comments */ + if (!pState.inComment) { + if (pStream.match(/\/\*[^\*\/]*/, true, true)) { + pState.inComment = true; + return "comment"; + } + if (pStream.match(wordRegexp(pConfig.singlecomment), true, true)) { + pStream.skipToEnd(); + return "comment"; + } + } + if (pState.inComment) { + if (pStream.match(/[^\*\/]*\*\//, true, true)) + pState.inComment = false; + else + pStream.skipToEnd(); + return "comment"; + } + /* strings */ + if (!pState.inString && pStream.match(/\"(\\\"|[^\"])*/, true, true)) { + pState.inString = true; + return "string"; + } + if (pState.inString) { + if (pStream.match(/[^\"]*\"/, true, true)) + pState.inString = false; + else + pStream.skipToEnd(); + return "string"; + } + /* keywords & operators */ + if (!!pConfig.keywords && pStream.match(wordRegexpBoundary(pConfig.keywords), true, true)) + return "keyword"; + + if (pStream.match(wordRegexpBoundary(pConfig.options), true, true)) + return "keyword"; + + if (pStream.match(wordRegexpBoundary(pConfig.arcsWords), true, true)) + return "keyword"; + + if (pStream.match(wordRegexp(pConfig.arcsOthers), true, true)) + return "keyword"; + + if (!!pConfig.operators && pStream.match(wordRegexp(pConfig.operators), true, true)) + return "operator"; + + if (!!pConfig.constants && pStream.match(wordRegexp(pConfig.constants), true, true)) + return "variable"; + + /* attribute lists */ + if (!pConfig.inAttributeList && !!pConfig.attributes && pStream.match(/\[/, true, true)) { + pConfig.inAttributeList = true; + return "bracket"; + } + if (pConfig.inAttributeList) { + if (pConfig.attributes !== null && pStream.match(wordRegexpBoundary(pConfig.attributes), true, true)) { + return "attribute"; + } + if (pStream.match(/]/, true, true)) { + pConfig.inAttributeList = false; + return "bracket"; + } + } + + pStream.next(); + return "base"; + }; + } + +}); diff --git a/modules/editor/codemirror/mode/mscgen/mscgen_test.min.js b/modules/editor/codemirror/mode/mscgen/mscgen_test.min.js @@ -0,0 +1,83 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function() { + var mode = CodeMirror.getMode({indentUnit: 2}, "mscgen"); + function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } + + MT("empty chart", + "[keyword msc][bracket {]", + "[base ]", + "[bracket }]" + ); + + MT("comments", + "[comment // a single line comment]", + "[comment # another single line comment /* and */ ignored here]", + "[comment /* A multi-line comment even though it contains]", + "[comment msc keywords and \"quoted text\"*/]"); + + MT("strings", + "[string \"// a string\"]", + "[string \"a string running over]", + "[string two lines\"]", + "[string \"with \\\"escaped quote\"]" + ); + + MT("xù/ msgenny keywords classify as 'base'", + "[base watermark]", + "[base alt loop opt ref else break par seq assert]" + ); + + MT("xù/ msgenny constants classify as 'base'", + "[base auto]" + ); + + MT("mscgen constants classify as 'variable'", + "[variable true]", "[variable false]", "[variable on]", "[variable off]" + ); + + MT("mscgen options classify as keyword", + "[keyword hscale]", "[keyword width]", "[keyword arcgradient]", "[keyword wordwraparcs]" + ); + + MT("mscgen arcs classify as keyword", + "[keyword note]","[keyword abox]","[keyword rbox]","[keyword box]", + "[keyword |||...---]", "[keyword ..--==::]", + "[keyword ->]", "[keyword <-]", "[keyword <->]", + "[keyword =>]", "[keyword <=]", "[keyword <=>]", + "[keyword =>>]", "[keyword <<=]", "[keyword <<=>>]", + "[keyword >>]", "[keyword <<]", "[keyword <<>>]", + "[keyword -x]", "[keyword x-]", "[keyword -X]", "[keyword X-]", + "[keyword :>]", "[keyword <:]", "[keyword <:>]" + ); + + MT("within an attribute list, attributes classify as attribute", + "[bracket [[][attribute label]", + "[attribute id]","[attribute url]","[attribute idurl]", + "[attribute linecolor]","[attribute linecolour]","[attribute textcolor]","[attribute textcolour]","[attribute textbgcolor]","[attribute textbgcolour]", + "[attribute arclinecolor]","[attribute arclinecolour]","[attribute arctextcolor]","[attribute arctextcolour]","[attribute arctextbgcolor]","[attribute arctextbgcolour]", + "[attribute arcskip][bracket ]]]" + ); + + MT("outside an attribute list, attributes classify as base", + "[base label]", + "[base id]","[base url]","[base idurl]", + "[base linecolor]","[base linecolour]","[base textcolor]","[base textcolour]","[base textbgcolor]","[base textbgcolour]", + "[base arclinecolor]","[base arclinecolour]","[base arctextcolor]","[base arctextcolour]","[base arctextbgcolor]","[base arctextbgcolour]", + "[base arcskip]" + ); + + MT("a typical program", + "[comment # typical mscgen program]", + "[keyword msc][base ][bracket {]", + "[keyword wordwraparcs][operator =][variable true][base , ][keyword hscale][operator =][string \"0.8\"][base , ][keyword arcgradient][operator =][base 30;]", + "[base a][bracket [[][attribute label][operator =][string \"Entity A\"][bracket ]]][base ,]", + "[base b][bracket [[][attribute label][operator =][string \"Entity B\"][bracket ]]][base ,]", + "[base c][bracket [[][attribute label][operator =][string \"Entity C\"][bracket ]]][base ;]", + "[base a ][keyword =>>][base b][bracket [[][attribute label][operator =][string \"Hello entity B\"][bracket ]]][base ;]", + "[base a ][keyword <<][base b][bracket [[][attribute label][operator =][string \"Here's an answer dude!\"][bracket ]]][base ;]", + "[base c ][keyword :>][base *][bracket [[][attribute label][operator =][string \"What about me?\"][base , ][attribute textcolor][operator =][base red][bracket ]]][base ;]", + "[bracket }]" + ); +})(); diff --git a/modules/editor/codemirror/mode/mumps/mumps.min.js b/modules/editor/codemirror/mode/mumps/mumps.min.js @@ -0,0 +1,148 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +/* + This MUMPS Language script was constructed using vbscript.js as a template. +*/ + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + CodeMirror.defineMode("mumps", function() { + function wordRegexp(words) { + return new RegExp("^((" + words.join(")|(") + "))\\b", "i"); + } + + var singleOperators = new RegExp("^[\\+\\-\\*/&#!_?\\\\<>=\\'\\[\\]]"); + var doubleOperators = new RegExp("^(('=)|(<=)|(>=)|('>)|('<)|([[)|(]])|(^$))"); + var singleDelimiters = new RegExp("^[\\.,:]"); + var brackets = new RegExp("[()]"); + var identifiers = new RegExp("^[%A-Za-z][A-Za-z0-9]*"); + var commandKeywords = ["break","close","do","else","for","goto", "halt", "hang", "if", "job","kill","lock","merge","new","open", "quit", "read", "set", "tcommit", "trollback", "tstart", "use", "view", "write", "xecute", "b","c","d","e","f","g", "h", "i", "j","k","l","m","n","o", "q", "r", "s", "tc", "tro", "ts", "u", "v", "w", "x"]; + // The following list includes instrinsic functions _and_ special variables + var intrinsicFuncsWords = ["\\$ascii", "\\$char", "\\$data", "\\$ecode", "\\$estack", "\\$etrap", "\\$extract", "\\$find", "\\$fnumber", "\\$get", "\\$horolog", "\\$io", "\\$increment", "\\$job", "\\$justify", "\\$length", "\\$name", "\\$next", "\\$order", "\\$piece", "\\$qlength", "\\$qsubscript", "\\$query", "\\$quit", "\\$random", "\\$reverse", "\\$select", "\\$stack", "\\$test", "\\$text", "\\$translate", "\\$view", "\\$x", "\\$y", "\\$a", "\\$c", "\\$d", "\\$e", "\\$ec", "\\$es", "\\$et", "\\$f", "\\$fn", "\\$g", "\\$h", "\\$i", "\\$j", "\\$l", "\\$n", "\\$na", "\\$o", "\\$p", "\\$q", "\\$ql", "\\$qs", "\\$r", "\\$re", "\\$s", "\\$st", "\\$t", "\\$tr", "\\$v", "\\$z"]; + var intrinsicFuncs = wordRegexp(intrinsicFuncsWords); + var command = wordRegexp(commandKeywords); + + function tokenBase(stream, state) { + if (stream.sol()) { + state.label = true; + state.commandMode = 0; + } + + // The <space> character has meaning in MUMPS. Ignoring consecutive + // spaces would interfere with interpreting whether the next non-space + // character belongs to the command or argument context. + + // Examine each character and update a mode variable whose interpretation is: + // >0 => command 0 => argument <0 => command post-conditional + var ch = stream.peek(); + + if (ch == " " || ch == "\t") { // Pre-process <space> + state.label = false; + if (state.commandMode == 0) + state.commandMode = 1; + else if ((state.commandMode < 0) || (state.commandMode == 2)) + state.commandMode = 0; + } else if ((ch != ".") && (state.commandMode > 0)) { + if (ch == ":") + state.commandMode = -1; // SIS - Command post-conditional + else + state.commandMode = 2; + } + + // Do not color parameter list as line tag + if ((ch === "(") || (ch === "\u0009")) + state.label = false; + + // MUMPS comment starts with ";" + if (ch === ";") { + stream.skipToEnd(); + return "comment"; + } + + // Number Literals // SIS/RLM - MUMPS permits canonic number followed by concatenate operator + if (stream.match(/^[-+]?\d+(\.\d+)?([eE][-+]?\d+)?/)) + return "number"; + + // Handle Strings + if (ch == '"') { + if (stream.skipTo('"')) { + stream.next(); + return "string"; + } else { + stream.skipToEnd(); + return "error"; + } + } + + // Handle operators and Delimiters + if (stream.match(doubleOperators) || stream.match(singleOperators)) + return "operator"; + + // Prevents leading "." in DO block from falling through to error + if (stream.match(singleDelimiters)) + return null; + + if (brackets.test(ch)) { + stream.next(); + return "bracket"; + } + + if (state.commandMode > 0 && stream.match(command)) + return "variable-2"; + + if (stream.match(intrinsicFuncs)) + return "builtin"; + + if (stream.match(identifiers)) + return "variable"; + + // Detect dollar-sign when not a documented intrinsic function + // "^" may introduce a GVN or SSVN - Color same as function + if (ch === "$" || ch === "^") { + stream.next(); + return "builtin"; + } + + // MUMPS Indirection + if (ch === "@") { + stream.next(); + return "string-2"; + } + + if (/[\w%]/.test(ch)) { + stream.eatWhile(/[\w%]/); + return "variable"; + } + + // Handle non-detected items + stream.next(); + return "error"; + } + + return { + startState: function() { + return { + label: false, + commandMode: 0 + }; + }, + + token: function(stream, state) { + var style = tokenBase(stream, state); + if (state.label) return "tag"; + return style; + } + }; + }); + + CodeMirror.defineMIME("text/x-mumps", "mumps"); +}); diff --git a/modules/editor/codemirror/mode/pig/pig.min.js b/modules/editor/codemirror/mode/pig/pig.min.js @@ -0,0 +1,178 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +/* + * Pig Latin Mode for CodeMirror 2 + * @author Prasanth Jayachandran + * @link https://github.com/prasanthj/pig-codemirror-2 + * This implementation is adapted from PL/SQL mode in CodeMirror 2. + */ +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode("pig", function(_config, parserConfig) { + var keywords = parserConfig.keywords, + builtins = parserConfig.builtins, + types = parserConfig.types, + multiLineStrings = parserConfig.multiLineStrings; + + var isOperatorChar = /[*+\-%<>=&?:\/!|]/; + + function chain(stream, state, f) { + state.tokenize = f; + return f(stream, state); + } + + function tokenComment(stream, state) { + var isEnd = false; + var ch; + while(ch = stream.next()) { + if(ch == "/" && isEnd) { + state.tokenize = tokenBase; + break; + } + isEnd = (ch == "*"); + } + return "comment"; + } + + function tokenString(quote) { + return function(stream, state) { + var escaped = false, next, end = false; + while((next = stream.next()) != null) { + if (next == quote && !escaped) { + end = true; break; + } + escaped = !escaped && next == "\\"; + } + if (end || !(escaped || multiLineStrings)) + state.tokenize = tokenBase; + return "error"; + }; + } + + + function tokenBase(stream, state) { + var ch = stream.next(); + + // is a start of string? + if (ch == '"' || ch == "'") + return chain(stream, state, tokenString(ch)); + // is it one of the special chars + else if(/[\[\]{}\(\),;\.]/.test(ch)) + return null; + // is it a number? + else if(/\d/.test(ch)) { + stream.eatWhile(/[\w\.]/); + return "number"; + } + // multi line comment or operator + else if (ch == "/") { + if (stream.eat("*")) { + return chain(stream, state, tokenComment); + } + else { + stream.eatWhile(isOperatorChar); + return "operator"; + } + } + // single line comment or operator + else if (ch=="-") { + if(stream.eat("-")){ + stream.skipToEnd(); + return "comment"; + } + else { + stream.eatWhile(isOperatorChar); + return "operator"; + } + } + // is it an operator + else if (isOperatorChar.test(ch)) { + stream.eatWhile(isOperatorChar); + return "operator"; + } + else { + // get the while word + stream.eatWhile(/[\w\$_]/); + // is it one of the listed keywords? + if (keywords && keywords.propertyIsEnumerable(stream.current().toUpperCase())) { + //keywords can be used as variables like flatten(group), group.$0 etc.. + if (!stream.eat(")") && !stream.eat(".")) + return "keyword"; + } + // is it one of the builtin functions? + if (builtins && builtins.propertyIsEnumerable(stream.current().toUpperCase())) + return "variable-2"; + // is it one of the listed types? + if (types && types.propertyIsEnumerable(stream.current().toUpperCase())) + return "variable-3"; + // default is a 'variable' + return "variable"; + } + } + + // Interface + return { + startState: function() { + return { + tokenize: tokenBase, + startOfLine: true + }; + }, + + token: function(stream, state) { + if(stream.eatSpace()) return null; + var style = state.tokenize(stream, state); + return style; + } + }; +}); + +(function() { + function keywords(str) { + var obj = {}, words = str.split(" "); + for (var i = 0; i < words.length; ++i) obj[words[i]] = true; + return obj; + } + + // builtin funcs taken from trunk revision 1303237 + var pBuiltins = "ABS ACOS ARITY ASIN ATAN AVG BAGSIZE BINSTORAGE BLOOM BUILDBLOOM CBRT CEIL " + + "CONCAT COR COS COSH COUNT COUNT_STAR COV CONSTANTSIZE CUBEDIMENSIONS DIFF DISTINCT DOUBLEABS " + + "DOUBLEAVG DOUBLEBASE DOUBLEMAX DOUBLEMIN DOUBLEROUND DOUBLESUM EXP FLOOR FLOATABS FLOATAVG " + + "FLOATMAX FLOATMIN FLOATROUND FLOATSUM GENERICINVOKER INDEXOF INTABS INTAVG INTMAX INTMIN " + + "INTSUM INVOKEFORDOUBLE INVOKEFORFLOAT INVOKEFORINT INVOKEFORLONG INVOKEFORSTRING INVOKER " + + "ISEMPTY JSONLOADER JSONMETADATA JSONSTORAGE LAST_INDEX_OF LCFIRST LOG LOG10 LOWER LONGABS " + + "LONGAVG LONGMAX LONGMIN LONGSUM MAX MIN MAPSIZE MONITOREDUDF NONDETERMINISTIC OUTPUTSCHEMA " + + "PIGSTORAGE PIGSTREAMING RANDOM REGEX_EXTRACT REGEX_EXTRACT_ALL REPLACE ROUND SIN SINH SIZE " + + "SQRT STRSPLIT SUBSTRING SUM STRINGCONCAT STRINGMAX STRINGMIN STRINGSIZE TAN TANH TOBAG " + + "TOKENIZE TOMAP TOP TOTUPLE TRIM TEXTLOADER TUPLESIZE UCFIRST UPPER UTF8STORAGECONVERTER "; + + // taken from QueryLexer.g + var pKeywords = "VOID IMPORT RETURNS DEFINE LOAD FILTER FOREACH ORDER CUBE DISTINCT COGROUP " + + "JOIN CROSS UNION SPLIT INTO IF OTHERWISE ALL AS BY USING INNER OUTER ONSCHEMA PARALLEL " + + "PARTITION GROUP AND OR NOT GENERATE FLATTEN ASC DESC IS STREAM THROUGH STORE MAPREDUCE " + + "SHIP CACHE INPUT OUTPUT STDERROR STDIN STDOUT LIMIT SAMPLE LEFT RIGHT FULL EQ GT LT GTE LTE " + + "NEQ MATCHES TRUE FALSE DUMP"; + + // data types + var pTypes = "BOOLEAN INT LONG FLOAT DOUBLE CHARARRAY BYTEARRAY BAG TUPLE MAP "; + + CodeMirror.defineMIME("text/x-pig", { + name: "pig", + builtins: keywords(pBuiltins), + keywords: keywords(pKeywords), + types: keywords(pTypes) + }); + + CodeMirror.registerHelper("hintWords", "pig", (pBuiltins + pTypes + pKeywords).split(" ")); +}()); + +}); diff --git a/modules/editor/codemirror/mode/properties/properties.min.js b/modules/editor/codemirror/mode/properties/properties.min.js @@ -0,0 +1,78 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode("properties", function() { + return { + token: function(stream, state) { + var sol = stream.sol() || state.afterSection; + var eol = stream.eol(); + + state.afterSection = false; + + if (sol) { + if (state.nextMultiline) { + state.inMultiline = true; + state.nextMultiline = false; + } else { + state.position = "def"; + } + } + + if (eol && ! state.nextMultiline) { + state.inMultiline = false; + state.position = "def"; + } + + if (sol) { + while(stream.eatSpace()) {} + } + + var ch = stream.next(); + + if (sol && (ch === "#" || ch === "!" || ch === ";")) { + state.position = "comment"; + stream.skipToEnd(); + return "comment"; + } else if (sol && ch === "[") { + state.afterSection = true; + stream.skipTo("]"); stream.eat("]"); + return "header"; + } else if (ch === "=" || ch === ":") { + state.position = "quote"; + return null; + } else if (ch === "\\" && state.position === "quote") { + if (stream.eol()) { // end of line? + // Multiline value + state.nextMultiline = true; + } + } + + return state.position; + }, + + startState: function() { + return { + position : "def", // Current position, "def", "quote" or "comment" + nextMultiline : false, // Is the next line multiline value + inMultiline : false, // Is the current line a multiline value + afterSection : false // Did we just open a section + }; + } + + }; +}); + +CodeMirror.defineMIME("text/x-properties", "properties"); +CodeMirror.defineMIME("text/x-ini", "properties"); + +}); diff --git a/modules/editor/codemirror/mode/pug/pug.min.js b/modules/editor/codemirror/mode/pug/pug.min.js @@ -0,0 +1,591 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror"), require("../javascript/javascript"), require("../css/css"), require("../htmlmixed/htmlmixed")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror", "../javascript/javascript", "../css/css", "../htmlmixed/htmlmixed"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode("pug", function (config) { + // token types + var KEYWORD = 'keyword'; + var DOCTYPE = 'meta'; + var ID = 'builtin'; + var CLASS = 'qualifier'; + + var ATTRS_NEST = { + '{': '}', + '(': ')', + '[': ']' + }; + + var jsMode = CodeMirror.getMode(config, 'javascript'); + + function State() { + this.javaScriptLine = false; + this.javaScriptLineExcludesColon = false; + + this.javaScriptArguments = false; + this.javaScriptArgumentsDepth = 0; + + this.isInterpolating = false; + this.interpolationNesting = 0; + + this.jsState = CodeMirror.startState(jsMode); + + this.restOfLine = ''; + + this.isIncludeFiltered = false; + this.isEach = false; + + this.lastTag = ''; + this.scriptType = ''; + + // Attributes Mode + this.isAttrs = false; + this.attrsNest = []; + this.inAttributeName = true; + this.attributeIsType = false; + this.attrValue = ''; + + // Indented Mode + this.indentOf = Infinity; + this.indentToken = ''; + + this.innerMode = null; + this.innerState = null; + + this.innerModeForLine = false; + } + /** + * Safely copy a state + * + * @return {State} + */ + State.prototype.copy = function () { + var res = new State(); + res.javaScriptLine = this.javaScriptLine; + res.javaScriptLineExcludesColon = this.javaScriptLineExcludesColon; + res.javaScriptArguments = this.javaScriptArguments; + res.javaScriptArgumentsDepth = this.javaScriptArgumentsDepth; + res.isInterpolating = this.isInterpolating; + res.interpolationNesting = this.interpolationNesting; + + res.jsState = CodeMirror.copyState(jsMode, this.jsState); + + res.innerMode = this.innerMode; + if (this.innerMode && this.innerState) { + res.innerState = CodeMirror.copyState(this.innerMode, this.innerState); + } + + res.restOfLine = this.restOfLine; + + res.isIncludeFiltered = this.isIncludeFiltered; + res.isEach = this.isEach; + res.lastTag = this.lastTag; + res.scriptType = this.scriptType; + res.isAttrs = this.isAttrs; + res.attrsNest = this.attrsNest.slice(); + res.inAttributeName = this.inAttributeName; + res.attributeIsType = this.attributeIsType; + res.attrValue = this.attrValue; + res.indentOf = this.indentOf; + res.indentToken = this.indentToken; + + res.innerModeForLine = this.innerModeForLine; + + return res; + }; + + function javaScript(stream, state) { + if (stream.sol()) { + // if javaScriptLine was set at end of line, ignore it + state.javaScriptLine = false; + state.javaScriptLineExcludesColon = false; + } + if (state.javaScriptLine) { + if (state.javaScriptLineExcludesColon && stream.peek() === ':') { + state.javaScriptLine = false; + state.javaScriptLineExcludesColon = false; + return; + } + var tok = jsMode.token(stream, state.jsState); + if (stream.eol()) state.javaScriptLine = false; + return tok || true; + } + } + function javaScriptArguments(stream, state) { + if (state.javaScriptArguments) { + if (state.javaScriptArgumentsDepth === 0 && stream.peek() !== '(') { + state.javaScriptArguments = false; + return; + } + if (stream.peek() === '(') { + state.javaScriptArgumentsDepth++; + } else if (stream.peek() === ')') { + state.javaScriptArgumentsDepth--; + } + if (state.javaScriptArgumentsDepth === 0) { + state.javaScriptArguments = false; + return; + } + + var tok = jsMode.token(stream, state.jsState); + return tok || true; + } + } + + function yieldStatement(stream) { + if (stream.match(/^yield\b/)) { + return 'keyword'; + } + } + + function doctype(stream) { + if (stream.match(/^(?:doctype) *([^\n]+)?/)) { + return DOCTYPE; + } + } + + function interpolation(stream, state) { + if (stream.match('#{')) { + state.isInterpolating = true; + state.interpolationNesting = 0; + return 'punctuation'; + } + } + + function interpolationContinued(stream, state) { + if (state.isInterpolating) { + if (stream.peek() === '}') { + state.interpolationNesting--; + if (state.interpolationNesting < 0) { + stream.next(); + state.isInterpolating = false; + return 'punctuation'; + } + } else if (stream.peek() === '{') { + state.interpolationNesting++; + } + return jsMode.token(stream, state.jsState) || true; + } + } + + function caseStatement(stream, state) { + if (stream.match(/^case\b/)) { + state.javaScriptLine = true; + return KEYWORD; + } + } + + function when(stream, state) { + if (stream.match(/^when\b/)) { + state.javaScriptLine = true; + state.javaScriptLineExcludesColon = true; + return KEYWORD; + } + } + + function defaultStatement(stream) { + if (stream.match(/^default\b/)) { + return KEYWORD; + } + } + + function extendsStatement(stream, state) { + if (stream.match(/^extends?\b/)) { + state.restOfLine = 'string'; + return KEYWORD; + } + } + + function append(stream, state) { + if (stream.match(/^append\b/)) { + state.restOfLine = 'variable'; + return KEYWORD; + } + } + function prepend(stream, state) { + if (stream.match(/^prepend\b/)) { + state.restOfLine = 'variable'; + return KEYWORD; + } + } + function block(stream, state) { + if (stream.match(/^block\b *(?:(prepend|append)\b)?/)) { + state.restOfLine = 'variable'; + return KEYWORD; + } + } + + function include(stream, state) { + if (stream.match(/^include\b/)) { + state.restOfLine = 'string'; + return KEYWORD; + } + } + + function includeFiltered(stream, state) { + if (stream.match(/^include:([a-zA-Z0-9\-]+)/, false) && stream.match('include')) { + state.isIncludeFiltered = true; + return KEYWORD; + } + } + + function includeFilteredContinued(stream, state) { + if (state.isIncludeFiltered) { + var tok = filter(stream, state); + state.isIncludeFiltered = false; + state.restOfLine = 'string'; + return tok; + } + } + + function mixin(stream, state) { + if (stream.match(/^mixin\b/)) { + state.javaScriptLine = true; + return KEYWORD; + } + } + + function call(stream, state) { + if (stream.match(/^\+([-\w]+)/)) { + if (!stream.match(/^\( *[-\w]+ *=/, false)) { + state.javaScriptArguments = true; + state.javaScriptArgumentsDepth = 0; + } + return 'variable'; + } + if (stream.match(/^\+#{/, false)) { + stream.next(); + state.mixinCallAfter = true; + return interpolation(stream, state); + } + } + function callArguments(stream, state) { + if (state.mixinCallAfter) { + state.mixinCallAfter = false; + if (!stream.match(/^\( *[-\w]+ *=/, false)) { + state.javaScriptArguments = true; + state.javaScriptArgumentsDepth = 0; + } + return true; + } + } + + function conditional(stream, state) { + if (stream.match(/^(if|unless|else if|else)\b/)) { + state.javaScriptLine = true; + return KEYWORD; + } + } + + function each(stream, state) { + if (stream.match(/^(- *)?(each|for)\b/)) { + state.isEach = true; + return KEYWORD; + } + } + function eachContinued(stream, state) { + if (state.isEach) { + if (stream.match(/^ in\b/)) { + state.javaScriptLine = true; + state.isEach = false; + return KEYWORD; + } else if (stream.sol() || stream.eol()) { + state.isEach = false; + } else if (stream.next()) { + while (!stream.match(/^ in\b/, false) && stream.next()); + return 'variable'; + } + } + } + + function whileStatement(stream, state) { + if (stream.match(/^while\b/)) { + state.javaScriptLine = true; + return KEYWORD; + } + } + + function tag(stream, state) { + var captures; + if (captures = stream.match(/^(\w(?:[-:\w]*\w)?)\/?/)) { + state.lastTag = captures[1].toLowerCase(); + if (state.lastTag === 'script') { + state.scriptType = 'application/javascript'; + } + return 'tag'; + } + } + + function filter(stream, state) { + if (stream.match(/^:([\w\-]+)/)) { + var innerMode; + if (config && config.innerModes) { + innerMode = config.innerModes(stream.current().substring(1)); + } + if (!innerMode) { + innerMode = stream.current().substring(1); + } + if (typeof innerMode === 'string') { + innerMode = CodeMirror.getMode(config, innerMode); + } + setInnerMode(stream, state, innerMode); + return 'atom'; + } + } + + function code(stream, state) { + if (stream.match(/^(!?=|-)/)) { + state.javaScriptLine = true; + return 'punctuation'; + } + } + + function id(stream) { + if (stream.match(/^#([\w-]+)/)) { + return ID; + } + } + + function className(stream) { + if (stream.match(/^\.([\w-]+)/)) { + return CLASS; + } + } + + function attrs(stream, state) { + if (stream.peek() == '(') { + stream.next(); + state.isAttrs = true; + state.attrsNest = []; + state.inAttributeName = true; + state.attrValue = ''; + state.attributeIsType = false; + return 'punctuation'; + } + } + + function attrsContinued(stream, state) { + if (state.isAttrs) { + if (ATTRS_NEST[stream.peek()]) { + state.attrsNest.push(ATTRS_NEST[stream.peek()]); + } + if (state.attrsNest[state.attrsNest.length - 1] === stream.peek()) { + state.attrsNest.pop(); + } else if (stream.eat(')')) { + state.isAttrs = false; + return 'punctuation'; + } + if (state.inAttributeName && stream.match(/^[^=,\)!]+/)) { + if (stream.peek() === '=' || stream.peek() === '!') { + state.inAttributeName = false; + state.jsState = CodeMirror.startState(jsMode); + if (state.lastTag === 'script' && stream.current().trim().toLowerCase() === 'type') { + state.attributeIsType = true; + } else { + state.attributeIsType = false; + } + } + return 'attribute'; + } + + var tok = jsMode.token(stream, state.jsState); + if (state.attributeIsType && tok === 'string') { + state.scriptType = stream.current().toString(); + } + if (state.attrsNest.length === 0 && (tok === 'string' || tok === 'variable' || tok === 'keyword')) { + try { + Function('', 'var x ' + state.attrValue.replace(/,\s*$/, '').replace(/^!/, '')); + state.inAttributeName = true; + state.attrValue = ''; + stream.backUp(stream.current().length); + return attrsContinued(stream, state); + } catch (ex) { + //not the end of an attribute + } + } + state.attrValue += stream.current(); + return tok || true; + } + } + + function attributesBlock(stream, state) { + if (stream.match(/^&attributes\b/)) { + state.javaScriptArguments = true; + state.javaScriptArgumentsDepth = 0; + return 'keyword'; + } + } + + function indent(stream) { + if (stream.sol() && stream.eatSpace()) { + return 'indent'; + } + } + + function comment(stream, state) { + if (stream.match(/^ *\/\/(-)?([^\n]*)/)) { + state.indentOf = stream.indentation(); + state.indentToken = 'comment'; + return 'comment'; + } + } + + function colon(stream) { + if (stream.match(/^: */)) { + return 'colon'; + } + } + + function text(stream, state) { + if (stream.match(/^(?:\| ?| )([^\n]+)/)) { + return 'string'; + } + if (stream.match(/^(<[^\n]*)/, false)) { + // html string + setInnerMode(stream, state, 'htmlmixed'); + state.innerModeForLine = true; + return innerMode(stream, state, true); + } + } + + function dot(stream, state) { + if (stream.eat('.')) { + var innerMode = null; + if (state.lastTag === 'script' && state.scriptType.toLowerCase().indexOf('javascript') != -1) { + innerMode = state.scriptType.toLowerCase().replace(/"|'/g, ''); + } else if (state.lastTag === 'style') { + innerMode = 'css'; + } + setInnerMode(stream, state, innerMode); + return 'dot'; + } + } + + function fail(stream) { + stream.next(); + return null; + } + + + function setInnerMode(stream, state, mode) { + mode = CodeMirror.mimeModes[mode] || mode; + mode = config.innerModes ? config.innerModes(mode) || mode : mode; + mode = CodeMirror.mimeModes[mode] || mode; + mode = CodeMirror.getMode(config, mode); + state.indentOf = stream.indentation(); + + if (mode && mode.name !== 'null') { + state.innerMode = mode; + } else { + state.indentToken = 'string'; + } + } + function innerMode(stream, state, force) { + if (stream.indentation() > state.indentOf || (state.innerModeForLine && !stream.sol()) || force) { + if (state.innerMode) { + if (!state.innerState) { + state.innerState = state.innerMode.startState ? CodeMirror.startState(state.innerMode, stream.indentation()) : {}; + } + return stream.hideFirstChars(state.indentOf + 2, function () { + return state.innerMode.token(stream, state.innerState) || true; + }); + } else { + stream.skipToEnd(); + return state.indentToken; + } + } else if (stream.sol()) { + state.indentOf = Infinity; + state.indentToken = null; + state.innerMode = null; + state.innerState = null; + } + } + function restOfLine(stream, state) { + if (stream.sol()) { + // if restOfLine was set at end of line, ignore it + state.restOfLine = ''; + } + if (state.restOfLine) { + stream.skipToEnd(); + var tok = state.restOfLine; + state.restOfLine = ''; + return tok; + } + } + + + function startState() { + return new State(); + } + function copyState(state) { + return state.copy(); + } + /** + * Get the next token in the stream + * + * @param {Stream} stream + * @param {State} state + */ + function nextToken(stream, state) { + var tok = innerMode(stream, state) + || restOfLine(stream, state) + || interpolationContinued(stream, state) + || includeFilteredContinued(stream, state) + || eachContinued(stream, state) + || attrsContinued(stream, state) + || javaScript(stream, state) + || javaScriptArguments(stream, state) + || callArguments(stream, state) + + || yieldStatement(stream, state) + || doctype(stream, state) + || interpolation(stream, state) + || caseStatement(stream, state) + || when(stream, state) + || defaultStatement(stream, state) + || extendsStatement(stream, state) + || append(stream, state) + || prepend(stream, state) + || block(stream, state) + || include(stream, state) + || includeFiltered(stream, state) + || mixin(stream, state) + || call(stream, state) + || conditional(stream, state) + || each(stream, state) + || whileStatement(stream, state) + || tag(stream, state) + || filter(stream, state) + || code(stream, state) + || id(stream, state) + || className(stream, state) + || attrs(stream, state) + || attributesBlock(stream, state) + || indent(stream, state) + || text(stream, state) + || comment(stream, state) + || colon(stream, state) + || dot(stream, state) + || fail(stream, state); + + return tok === true ? null : tok; + } + return { + startState: startState, + copyState: copyState, + token: nextToken + }; +}, 'javascript', 'css', 'htmlmixed'); + +CodeMirror.defineMIME('text/x-pug', 'pug'); +CodeMirror.defineMIME('text/x-jade', 'pug'); + +}); diff --git a/modules/editor/codemirror/mode/r/r.min.js b/modules/editor/codemirror/mode/r/r.min.js @@ -0,0 +1,183 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.registerHelper("wordChars", "r", /[\w.]/); + +CodeMirror.defineMode("r", function(config) { + function wordObj(str) { + var words = str.split(" "), res = {}; + for (var i = 0; i < words.length; ++i) res[words[i]] = true; + return res; + } + var atoms = wordObj("NULL NA Inf NaN NA_integer_ NA_real_ NA_complex_ NA_character_"); + var builtins = wordObj("list quote bquote eval return call parse deparse"); + var keywords = wordObj("if else repeat while function for in next break"); + var blockkeywords = wordObj("if else repeat while function for"); + var opChars = /[+\-*\/^<>=!&|~$:]/; + var curPunc; + + function tokenBase(stream, state) { + curPunc = null; + var ch = stream.next(); + if (ch == "#") { + stream.skipToEnd(); + return "comment"; + } else if (ch == "0" && stream.eat("x")) { + stream.eatWhile(/[\da-f]/i); + return "number"; + } else if (ch == "." && stream.eat(/\d/)) { + stream.match(/\d*(?:e[+\-]?\d+)?/); + return "number"; + } else if (/\d/.test(ch)) { + stream.match(/\d*(?:\.\d+)?(?:e[+\-]\d+)?L?/); + return "number"; + } else if (ch == "'" || ch == '"') { + state.tokenize = tokenString(ch); + return "string"; + } else if (ch == "`") { + stream.match(/[^`]+`/); + return "variable-3"; + } else if (ch == "." && stream.match(/.[.\d]+/)) { + return "keyword"; + } else if (/[\w\.]/.test(ch) && ch != "_") { + stream.eatWhile(/[\w\.]/); + var word = stream.current(); + if (atoms.propertyIsEnumerable(word)) return "atom"; + if (keywords.propertyIsEnumerable(word)) { + // Block keywords start new blocks, except 'else if', which only starts + // one new block for the 'if', no block for the 'else'. + if (blockkeywords.propertyIsEnumerable(word) && + !stream.match(/\s*if(\s+|$)/, false)) + curPunc = "block"; + return "keyword"; + } + if (builtins.propertyIsEnumerable(word)) return "builtin"; + return "variable"; + } else if (ch == "%") { + if (stream.skipTo("%")) stream.next(); + return "operator variable-2"; + } else if ( + (ch == "<" && stream.eat("-")) || + (ch == "<" && stream.match("<-")) || + (ch == "-" && stream.match(/>>?/)) + ) { + return "operator arrow"; + } else if (ch == "=" && state.ctx.argList) { + return "arg-is"; + } else if (opChars.test(ch)) { + if (ch == "$") return "operator dollar"; + stream.eatWhile(opChars); + return "operator"; + } else if (/[\(\){}\[\];]/.test(ch)) { + curPunc = ch; + if (ch == ";") return "semi"; + return null; + } else { + return null; + } + } + + function tokenString(quote) { + return function(stream, state) { + if (stream.eat("\\")) { + var ch = stream.next(); + if (ch == "x") stream.match(/^[a-f0-9]{2}/i); + else if ((ch == "u" || ch == "U") && stream.eat("{") && stream.skipTo("}")) stream.next(); + else if (ch == "u") stream.match(/^[a-f0-9]{4}/i); + else if (ch == "U") stream.match(/^[a-f0-9]{8}/i); + else if (/[0-7]/.test(ch)) stream.match(/^[0-7]{1,2}/); + return "string-2"; + } else { + var next; + while ((next = stream.next()) != null) { + if (next == quote) { state.tokenize = tokenBase; break; } + if (next == "\\") { stream.backUp(1); break; } + } + return "string"; + } + }; + } + + var ALIGN_YES = 1, ALIGN_NO = 2, BRACELESS = 4 + + function push(state, type, stream) { + state.ctx = {type: type, + indent: state.indent, + flags: 0, + column: stream.column(), + prev: state.ctx}; + } + function setFlag(state, flag) { + var ctx = state.ctx + state.ctx = {type: ctx.type, + indent: ctx.indent, + flags: ctx.flags | flag, + column: ctx.column, + prev: ctx.prev} + } + function pop(state) { + state.indent = state.ctx.indent; + state.ctx = state.ctx.prev; + } + + return { + startState: function() { + return {tokenize: tokenBase, + ctx: {type: "top", + indent: -config.indentUnit, + flags: ALIGN_NO}, + indent: 0, + afterIdent: false}; + }, + + token: function(stream, state) { + if (stream.sol()) { + if ((state.ctx.flags & 3) == 0) state.ctx.flags |= ALIGN_NO + if (state.ctx.flags & BRACELESS) pop(state) + state.indent = stream.indentation(); + } + if (stream.eatSpace()) return null; + var style = state.tokenize(stream, state); + if (style != "comment" && (state.ctx.flags & ALIGN_NO) == 0) setFlag(state, ALIGN_YES) + + if ((curPunc == ";" || curPunc == "{" || curPunc == "}") && state.ctx.type == "block") pop(state); + if (curPunc == "{") push(state, "}", stream); + else if (curPunc == "(") { + push(state, ")", stream); + if (state.afterIdent) state.ctx.argList = true; + } + else if (curPunc == "[") push(state, "]", stream); + else if (curPunc == "block") push(state, "block", stream); + else if (curPunc == state.ctx.type) pop(state); + else if (state.ctx.type == "block" && style != "comment") setFlag(state, BRACELESS) + state.afterIdent = style == "variable" || style == "keyword"; + return style; + }, + + indent: function(state, textAfter) { + if (state.tokenize != tokenBase) return 0; + var firstChar = textAfter && textAfter.charAt(0), ctx = state.ctx, + closing = firstChar == ctx.type; + if (ctx.flags & BRACELESS) ctx = ctx.prev + if (ctx.type == "block") return ctx.indent + (firstChar == "{" ? 0 : config.indentUnit); + else if (ctx.flags & ALIGN_YES) return ctx.column + (closing ? 0 : 1); + else return ctx.indent + (closing ? 0 : config.indentUnit); + }, + + lineComment: "#" + }; +}); + +CodeMirror.defineMIME("text/x-rsrc", "r"); + +}); diff --git a/modules/editor/codemirror/mode/ruby/test.min.js b/modules/editor/codemirror/mode/ruby/test.min.js @@ -0,0 +1,16 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function() { + var mode = CodeMirror.getMode({indentUnit: 2}, "ruby"); + function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } + + MT("divide_equal_operator", + "[variable bar] [operator /=] [variable foo]"); + + MT("divide_equal_operator_no_spacing", + "[variable foo][operator /=][number 42]"); + + MT("complex_regexp", + "[keyword if] [variable cr] [operator =~] [string-2 /(?: \\( #{][tag RE_NOT][string-2 }\\( | #{][tag RE_NOT_PAR_OR][string-2 }* #{][tag RE_OPA_OR][string-2 } )/][variable x]") +})(); diff --git a/modules/editor/codemirror/mode/sas/sas.min.js b/modules/editor/codemirror/mode/sas/sas.min.js @@ -0,0 +1,303 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + + +// SAS mode copyright (c) 2016 Jared Dean, SAS Institute +// Created by Jared Dean + +// TODO +// indent and de-indent +// identify macro variables + + +//Definitions +// comment -- text within * ; or /* */ +// keyword -- SAS language variable +// variable -- macro variables starts with '&' or variable formats +// variable-2 -- DATA Step, proc, or macro names +// string -- text within ' ' or " " +// operator -- numeric operator + / - * ** le eq ge ... and so on +// builtin -- proc %macro data run mend +// atom +// def + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + CodeMirror.defineMode("sas", function () { + var words = {}; + var isDoubleOperatorSym = { + eq: 'operator', + lt: 'operator', + le: 'operator', + gt: 'operator', + ge: 'operator', + "in": 'operator', + ne: 'operator', + or: 'operator' + }; + var isDoubleOperatorChar = /(<=|>=|!=|<>)/; + var isSingleOperatorChar = /[=\(:\),{}.*<>+\-\/^\[\]]/; + + // Takes a string of words separated by spaces and adds them as + // keys with the value of the first argument 'style' + function define(style, string, context) { + if (context) { + var split = string.split(' '); + for (var i = 0; i < split.length; i++) { + words[split[i]] = {style: style, state: context}; + } + } + } + //datastep + define('def', 'stack pgm view source debug nesting nolist', ['inDataStep']); + define('def', 'if while until for do do; end end; then else cancel', ['inDataStep']); + define('def', 'label format _n_ _error_', ['inDataStep']); + define('def', 'ALTER BUFNO BUFSIZE CNTLLEV COMPRESS DLDMGACTION ENCRYPT ENCRYPTKEY EXTENDOBSCOUNTER GENMAX GENNUM INDEX LABEL OBSBUF OUTREP PW PWREQ READ REPEMPTY REPLACE REUSE ROLE SORTEDBY SPILL TOBSNO TYPE WRITE FILECLOSE FIRSTOBS IN OBS POINTOBS WHERE WHEREUP IDXNAME IDXWHERE DROP KEEP RENAME', ['inDataStep']); + define('def', 'filevar finfo finv fipname fipnamel fipstate first firstobs floor', ['inDataStep']); + define('def', 'varfmt varinfmt varlabel varlen varname varnum varray varrayx vartype verify vformat vformatd vformatdx vformatn vformatnx vformatw vformatwx vformatx vinarray vinarrayx vinformat vinformatd vinformatdx vinformatn vinformatnx vinformatw vinformatwx vinformatx vlabel vlabelx vlength vlengthx vname vnamex vnferr vtype vtypex weekday', ['inDataStep']); + define('def', 'zipfips zipname zipnamel zipstate', ['inDataStep']); + define('def', 'put putc putn', ['inDataStep']); + define('builtin', 'data run', ['inDataStep']); + + + //proc + define('def', 'data', ['inProc']); + + // flow control for macros + define('def', '%if %end %end; %else %else; %do %do; %then', ['inMacro']); + + //everywhere + define('builtin', 'proc run; quit; libname filename %macro %mend option options', ['ALL']); + + define('def', 'footnote title libname ods', ['ALL']); + define('def', '%let %put %global %sysfunc %eval ', ['ALL']); + // automatic macro variables http://support.sas.com/documentation/cdl/en/mcrolref/61885/HTML/default/viewer.htm#a003167023.htm + define('variable', '&sysbuffr &syscc &syscharwidth &syscmd &sysdate &sysdate9 &sysday &sysdevic &sysdmg &sysdsn &sysencoding &sysenv &syserr &syserrortext &sysfilrc &syshostname &sysindex &sysinfo &sysjobid &syslast &syslckrc &syslibrc &syslogapplname &sysmacroname &sysmenv &sysmsg &sysncpu &sysodspath &sysparm &syspbuff &sysprocessid &sysprocessname &sysprocname &sysrc &sysscp &sysscpl &sysscpl &syssite &sysstartid &sysstartname &systcpiphostname &systime &sysuserid &sysver &sysvlong &sysvlong4 &syswarningtext', ['ALL']); + + //footnote[1-9]? title[1-9]? + + //options statement + define('def', 'source2 nosource2 page pageno pagesize', ['ALL']); + + //proc and datastep + define('def', '_all_ _character_ _cmd_ _freq_ _i_ _infile_ _last_ _msg_ _null_ _numeric_ _temporary_ _type_ abort abs addr adjrsq airy alpha alter altlog altprint and arcos array arsin as atan attrc attrib attrn authserver autoexec awscontrol awsdef awsmenu awsmenumerge awstitle backward band base betainv between blocksize blshift bnot bor brshift bufno bufsize bxor by byerr byline byte calculated call cards cards4 catcache cbufno cdf ceil center cexist change chisq cinv class cleanup close cnonct cntllev coalesce codegen col collate collin column comamid comaux1 comaux2 comdef compbl compound compress config continue convert cos cosh cpuid create cross crosstab css curobs cv daccdb daccdbsl daccsl daccsyd dacctab dairy datalines datalines4 datejul datepart datetime day dbcslang dbcstype dclose ddm delete delimiter depdb depdbsl depsl depsyd deptab dequote descending descript design= device dflang dhms dif digamma dim dinfo display distinct dkricond dkrocond dlm dnum do dopen doptname doptnum dread drop dropnote dsname dsnferr echo else emaildlg emailid emailpw emailserver emailsys encrypt end endsas engine eof eov erf erfc error errorcheck errors exist exp fappend fclose fcol fdelete feedback fetch fetchobs fexist fget file fileclose fileexist filefmt filename fileref fmterr fmtsearch fnonct fnote font fontalias fopen foptname foptnum force formatted formchar formdelim formdlim forward fpoint fpos fput fread frewind frlen from fsep fuzz fwrite gaminv gamma getoption getvarc getvarn go goto group gwindow hbar hbound helpenv helploc hms honorappearance hosthelp hostprint hour hpct html hvar ibessel ibr id if index indexc indexw initcmd initstmt inner input inputc inputn inr insert int intck intnx into intrr invaliddata irr is jbessel join juldate keep kentb kurtosis label lag last lbound leave left length levels lgamma lib library libref line linesize link list log log10 log2 logpdf logpmf logsdf lostcard lowcase lrecl ls macro macrogen maps mautosource max maxdec maxr mdy mean measures median memtype merge merror min minute missing missover mlogic mod mode model modify month mopen mort mprint mrecall msglevel msymtabmax mvarsize myy n nest netpv new news nmiss no nobatch nobs nocaps nocardimage nocenter nocharcode nocmdmac nocol nocum nodate nodbcs nodetails nodmr nodms nodmsbatch nodup nodupkey noduplicates noechoauto noequals noerrorabend noexitwindows nofullstimer noicon noimplmac noint nolist noloadlist nomiss nomlogic nomprint nomrecall nomsgcase nomstored nomultenvappl nonotes nonumber noobs noovp nopad nopercent noprint noprintinit normal norow norsasuser nosetinit nosplash nosymbolgen note notes notitle notitles notsorted noverbose noxsync noxwait npv null number numkeys nummousekeys nway obs on open order ordinal otherwise out outer outp= output over ovp p(1 5 10 25 50 75 90 95 99) pad pad2 paired parm parmcards path pathdll pathname pdf peek peekc pfkey pmf point poisson poke position printer probbeta probbnml probchi probf probgam probhypr probit probnegb probnorm probsig probt procleave prt ps pw pwreq qtr quote r ranbin rancau ranexp rangam range ranks rannor ranpoi rantbl rantri ranuni read recfm register regr remote remove rename repeat replace resolve retain return reuse reverse rewind right round rsquare rtf rtrace rtraceloc s s2 samploc sasautos sascontrol sasfrscr sasmsg sasmstore sasscript sasuser saving scan sdf second select selection separated seq serror set setcomm setot sign simple sin sinh siteinfo skewness skip sle sls sortedby sortpgm sortseq sortsize soundex spedis splashlocation split spool sqrt start std stderr stdin stfips stimer stname stnamel stop stopover subgroup subpopn substr sum sumwgt symbol symbolgen symget symput sysget sysin sysleave sysmsg sysparm sysprint sysprintfont sysprod sysrc system t table tables tan tanh tapeclose tbufsize terminal test then timepart tinv tnonct to today tol tooldef totper transformout translate trantab tranwrd trigamma trim trimn trunc truncover type unformatted uniform union until upcase update user usericon uss validate value var weight when where while wincharset window work workinit workterm write wsum xsync xwait yearcutoff yes yyq min max', ['inDataStep', 'inProc']); + define('operator', 'and not ', ['inDataStep', 'inProc']); + + // Main function + function tokenize(stream, state) { + // Finally advance the stream + var ch = stream.next(); + + // BLOCKCOMMENT + if (ch === '/' && stream.eat('*')) { + state.continueComment = true; + return "comment"; + } else if (state.continueComment === true) { // in comment block + //comment ends at the beginning of the line + if (ch === '*' && stream.peek() === '/') { + stream.next(); + state.continueComment = false; + } else if (stream.skipTo('*')) { //comment is potentially later in line + stream.skipTo('*'); + stream.next(); + if (stream.eat('/')) + state.continueComment = false; + } else { + stream.skipToEnd(); + } + return "comment"; + } + + if (ch == "*" && stream.column() == stream.indentation()) { + stream.skipToEnd() + return "comment" + } + + // DoubleOperator match + var doubleOperator = ch + stream.peek(); + + if ((ch === '"' || ch === "'") && !state.continueString) { + state.continueString = ch + return "string" + } else if (state.continueString) { + if (state.continueString == ch) { + state.continueString = null; + } else if (stream.skipTo(state.continueString)) { + // quote found on this line + stream.next(); + state.continueString = null; + } else { + stream.skipToEnd(); + } + return "string"; + } else if (state.continueString !== null && stream.eol()) { + stream.skipTo(state.continueString) || stream.skipToEnd(); + return "string"; + } else if (/[\d\.]/.test(ch)) { //find numbers + if (ch === ".") + stream.match(/^[0-9]+([eE][\-+]?[0-9]+)?/); + else if (ch === "0") + stream.match(/^[xX][0-9a-fA-F]+/) || stream.match(/^0[0-7]+/); + else + stream.match(/^[0-9]*\.?[0-9]*([eE][\-+]?[0-9]+)?/); + return "number"; + } else if (isDoubleOperatorChar.test(ch + stream.peek())) { // TWO SYMBOL TOKENS + stream.next(); + return "operator"; + } else if (isDoubleOperatorSym.hasOwnProperty(doubleOperator)) { + stream.next(); + if (stream.peek() === ' ') + return isDoubleOperatorSym[doubleOperator.toLowerCase()]; + } else if (isSingleOperatorChar.test(ch)) { // SINGLE SYMBOL TOKENS + return "operator"; + } + + // Matches one whole word -- even if the word is a character + var word; + if (stream.match(/[%&;\w]+/, false) != null) { + word = ch + stream.match(/[%&;\w]+/, true); + if (/&/.test(word)) return 'variable' + } else { + word = ch; + } + // the word after DATA PROC or MACRO + if (state.nextword) { + stream.match(/[\w]+/); + // match memname.libname + if (stream.peek() === '.') stream.skipTo(' '); + state.nextword = false; + return 'variable-2'; + } + + word = word.toLowerCase() + // Are we in a DATA Step? + if (state.inDataStep) { + if (word === 'run;' || stream.match(/run\s;/)) { + state.inDataStep = false; + return 'builtin'; + } + // variable formats + if ((word) && stream.next() === '.') { + //either a format or libname.memname + if (/\w/.test(stream.peek())) return 'variable-2'; + else return 'variable'; + } + // do we have a DATA Step keyword + if (word && words.hasOwnProperty(word) && + (words[word].state.indexOf("inDataStep") !== -1 || + words[word].state.indexOf("ALL") !== -1)) { + //backup to the start of the word + if (stream.start < stream.pos) + stream.backUp(stream.pos - stream.start); + //advance the length of the word and return + for (var i = 0; i < word.length; ++i) stream.next(); + return words[word].style; + } + } + // Are we in an Proc statement? + if (state.inProc) { + if (word === 'run;' || word === 'quit;') { + state.inProc = false; + return 'builtin'; + } + // do we have a proc keyword + if (word && words.hasOwnProperty(word) && + (words[word].state.indexOf("inProc") !== -1 || + words[word].state.indexOf("ALL") !== -1)) { + stream.match(/[\w]+/); + return words[word].style; + } + } + // Are we in a Macro statement? + if (state.inMacro) { + if (word === '%mend') { + if (stream.peek() === ';') stream.next(); + state.inMacro = false; + return 'builtin'; + } + if (word && words.hasOwnProperty(word) && + (words[word].state.indexOf("inMacro") !== -1 || + words[word].state.indexOf("ALL") !== -1)) { + stream.match(/[\w]+/); + return words[word].style; + } + + return 'atom'; + } + // Do we have Keywords specific words? + if (word && words.hasOwnProperty(word)) { + // Negates the initial next() + stream.backUp(1); + // Actually move the stream + stream.match(/[\w]+/); + if (word === 'data' && /=/.test(stream.peek()) === false) { + state.inDataStep = true; + state.nextword = true; + return 'builtin'; + } + if (word === 'proc') { + state.inProc = true; + state.nextword = true; + return 'builtin'; + } + if (word === '%macro') { + state.inMacro = true; + state.nextword = true; + return 'builtin'; + } + if (/title[1-9]/.test(word)) return 'def'; + + if (word === 'footnote') { + stream.eat(/[1-9]/); + return 'def'; + } + + // Returns their value as state in the prior define methods + if (state.inDataStep === true && words[word].state.indexOf("inDataStep") !== -1) + return words[word].style; + if (state.inProc === true && words[word].state.indexOf("inProc") !== -1) + return words[word].style; + if (state.inMacro === true && words[word].state.indexOf("inMacro") !== -1) + return words[word].style; + if (words[word].state.indexOf("ALL") !== -1) + return words[word].style; + return null; + } + // Unrecognized syntax + return null; + } + + return { + startState: function () { + return { + inDataStep: false, + inProc: false, + inMacro: false, + nextword: false, + continueString: null, + continueComment: false + }; + }, + token: function (stream, state) { + // Strip the spaces, but regex will account for them either way + if (stream.eatSpace()) return null; + // Go through the main process + return tokenize(stream, state); + }, + + blockCommentStart: "/*", + blockCommentEnd: "*/" + }; + + }); + + CodeMirror.defineMIME("text/x-sas", "sas"); +}); diff --git a/modules/editor/codemirror/mode/sass/sass.min.js b/modules/editor/codemirror/mode/sass/sass.min.js @@ -0,0 +1,454 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror"), require("../css/css")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror", "../css/css"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode("sass", function(config) { + var cssMode = CodeMirror.mimeModes["text/css"]; + var propertyKeywords = cssMode.propertyKeywords || {}, + colorKeywords = cssMode.colorKeywords || {}, + valueKeywords = cssMode.valueKeywords || {}, + fontProperties = cssMode.fontProperties || {}; + + function tokenRegexp(words) { + return new RegExp("^" + words.join("|")); + } + + var keywords = ["true", "false", "null", "auto"]; + var keywordsRegexp = new RegExp("^" + keywords.join("|")); + + var operators = ["\\(", "\\)", "=", ">", "<", "==", ">=", "<=", "\\+", "-", + "\\!=", "/", "\\*", "%", "and", "or", "not", ";","\\{","\\}",":"]; + var opRegexp = tokenRegexp(operators); + + var pseudoElementsRegexp = /^::?[a-zA-Z_][\w\-]*/; + + var word; + + function isEndLine(stream) { + return !stream.peek() || stream.match(/\s+$/, false); + } + + function urlTokens(stream, state) { + var ch = stream.peek(); + + if (ch === ")") { + stream.next(); + state.tokenizer = tokenBase; + return "operator"; + } else if (ch === "(") { + stream.next(); + stream.eatSpace(); + + return "operator"; + } else if (ch === "'" || ch === '"') { + state.tokenizer = buildStringTokenizer(stream.next()); + return "string"; + } else { + state.tokenizer = buildStringTokenizer(")", false); + return "string"; + } + } + function comment(indentation, multiLine) { + return function(stream, state) { + if (stream.sol() && stream.indentation() <= indentation) { + state.tokenizer = tokenBase; + return tokenBase(stream, state); + } + + if (multiLine && stream.skipTo("*/")) { + stream.next(); + stream.next(); + state.tokenizer = tokenBase; + } else { + stream.skipToEnd(); + } + + return "comment"; + }; + } + + function buildStringTokenizer(quote, greedy) { + if (greedy == null) { greedy = true; } + + function stringTokenizer(stream, state) { + var nextChar = stream.next(); + var peekChar = stream.peek(); + var previousChar = stream.string.charAt(stream.pos-2); + + var endingString = ((nextChar !== "\\" && peekChar === quote) || (nextChar === quote && previousChar !== "\\")); + + if (endingString) { + if (nextChar !== quote && greedy) { stream.next(); } + if (isEndLine(stream)) { + state.cursorHalf = 0; + } + state.tokenizer = tokenBase; + return "string"; + } else if (nextChar === "#" && peekChar === "{") { + state.tokenizer = buildInterpolationTokenizer(stringTokenizer); + stream.next(); + return "operator"; + } else { + return "string"; + } + } + + return stringTokenizer; + } + + function buildInterpolationTokenizer(currentTokenizer) { + return function(stream, state) { + if (stream.peek() === "}") { + stream.next(); + state.tokenizer = currentTokenizer; + return "operator"; + } else { + return tokenBase(stream, state); + } + }; + } + + function indent(state) { + if (state.indentCount == 0) { + state.indentCount++; + var lastScopeOffset = state.scopes[0].offset; + var currentOffset = lastScopeOffset + config.indentUnit; + state.scopes.unshift({ offset:currentOffset }); + } + } + + function dedent(state) { + if (state.scopes.length == 1) return; + + state.scopes.shift(); + } + + function tokenBase(stream, state) { + var ch = stream.peek(); + + // Comment + if (stream.match("/*")) { + state.tokenizer = comment(stream.indentation(), true); + return state.tokenizer(stream, state); + } + if (stream.match("//")) { + state.tokenizer = comment(stream.indentation(), false); + return state.tokenizer(stream, state); + } + + // Interpolation + if (stream.match("#{")) { + state.tokenizer = buildInterpolationTokenizer(tokenBase); + return "operator"; + } + + // Strings + if (ch === '"' || ch === "'") { + stream.next(); + state.tokenizer = buildStringTokenizer(ch); + return "string"; + } + + if(!state.cursorHalf){// state.cursorHalf === 0 + // first half i.e. before : for key-value pairs + // including selectors + + if (ch === "-") { + if (stream.match(/^-\w+-/)) { + return "meta"; + } + } + + if (ch === ".") { + stream.next(); + if (stream.match(/^[\w-]+/)) { + indent(state); + return "qualifier"; + } else if (stream.peek() === "#") { + indent(state); + return "tag"; + } + } + + if (ch === "#") { + stream.next(); + // ID selectors + if (stream.match(/^[\w-]+/)) { + indent(state); + return "builtin"; + } + if (stream.peek() === "#") { + indent(state); + return "tag"; + } + } + + // Variables + if (ch === "$") { + stream.next(); + stream.eatWhile(/[\w-]/); + return "variable-2"; + } + + // Numbers + if (stream.match(/^-?[0-9\.]+/)) + return "number"; + + // Units + if (stream.match(/^(px|em|in)\b/)) + return "unit"; + + if (stream.match(keywordsRegexp)) + return "keyword"; + + if (stream.match(/^url/) && stream.peek() === "(") { + state.tokenizer = urlTokens; + return "atom"; + } + + if (ch === "=") { + // Match shortcut mixin definition + if (stream.match(/^=[\w-]+/)) { + indent(state); + return "meta"; + } + } + + if (ch === "+") { + // Match shortcut mixin definition + if (stream.match(/^\+[\w-]+/)){ + return "variable-3"; + } + } + + if(ch === "@"){ + if(stream.match(/@extend/)){ + if(!stream.match(/\s*[\w]/)) + dedent(state); + } + } + + + // Indent Directives + if (stream.match(/^@(else if|if|media|else|for|each|while|mixin|function)/)) { + indent(state); + return "def"; + } + + // Other Directives + if (ch === "@") { + stream.next(); + stream.eatWhile(/[\w-]/); + return "def"; + } + + if (stream.eatWhile(/[\w-]/)){ + if(stream.match(/ *: *[\w-\+\$#!\("']/,false)){ + word = stream.current().toLowerCase(); + var prop = state.prevProp + "-" + word; + if (propertyKeywords.hasOwnProperty(prop)) { + return "property"; + } else if (propertyKeywords.hasOwnProperty(word)) { + state.prevProp = word; + return "property"; + } else if (fontProperties.hasOwnProperty(word)) { + return "property"; + } + return "tag"; + } + else if(stream.match(/ *:/,false)){ + indent(state); + state.cursorHalf = 1; + state.prevProp = stream.current().toLowerCase(); + return "property"; + } + else if(stream.match(/ *,/,false)){ + return "tag"; + } + else{ + indent(state); + return "tag"; + } + } + + if(ch === ":"){ + if (stream.match(pseudoElementsRegexp)){ // could be a pseudo-element + return "variable-3"; + } + stream.next(); + state.cursorHalf=1; + return "operator"; + } + + } // cursorHalf===0 ends here + else{ + + if (ch === "#") { + stream.next(); + // Hex numbers + if (stream.match(/[0-9a-fA-F]{6}|[0-9a-fA-F]{3}/)){ + if (isEndLine(stream)) { + state.cursorHalf = 0; + } + return "number"; + } + } + + // Numbers + if (stream.match(/^-?[0-9\.]+/)){ + if (isEndLine(stream)) { + state.cursorHalf = 0; + } + return "number"; + } + + // Units + if (stream.match(/^(px|em|in)\b/)){ + if (isEndLine(stream)) { + state.cursorHalf = 0; + } + return "unit"; + } + + if (stream.match(keywordsRegexp)){ + if (isEndLine(stream)) { + state.cursorHalf = 0; + } + return "keyword"; + } + + if (stream.match(/^url/) && stream.peek() === "(") { + state.tokenizer = urlTokens; + if (isEndLine(stream)) { + state.cursorHalf = 0; + } + return "atom"; + } + + // Variables + if (ch === "$") { + stream.next(); + stream.eatWhile(/[\w-]/); + if (isEndLine(stream)) { + state.cursorHalf = 0; + } + return "variable-2"; + } + + // bang character for !important, !default, etc. + if (ch === "!") { + stream.next(); + state.cursorHalf = 0; + return stream.match(/^[\w]+/) ? "keyword": "operator"; + } + + if (stream.match(opRegexp)){ + if (isEndLine(stream)) { + state.cursorHalf = 0; + } + return "operator"; + } + + // attributes + if (stream.eatWhile(/[\w-]/)) { + if (isEndLine(stream)) { + state.cursorHalf = 0; + } + word = stream.current().toLowerCase(); + if (valueKeywords.hasOwnProperty(word)) { + return "atom"; + } else if (colorKeywords.hasOwnProperty(word)) { + return "keyword"; + } else if (propertyKeywords.hasOwnProperty(word)) { + state.prevProp = stream.current().toLowerCase(); + return "property"; + } else { + return "tag"; + } + } + + //stream.eatSpace(); + if (isEndLine(stream)) { + state.cursorHalf = 0; + return null; + } + + } // else ends here + + if (stream.match(opRegexp)) + return "operator"; + + // If we haven't returned by now, we move 1 character + // and return an error + stream.next(); + return null; + } + + function tokenLexer(stream, state) { + if (stream.sol()) state.indentCount = 0; + var style = state.tokenizer(stream, state); + var current = stream.current(); + + if (current === "@return" || current === "}"){ + dedent(state); + } + + if (style !== null) { + var startOfToken = stream.pos - current.length; + + var withCurrentIndent = startOfToken + (config.indentUnit * state.indentCount); + + var newScopes = []; + + for (var i = 0; i < state.scopes.length; i++) { + var scope = state.scopes[i]; + + if (scope.offset <= withCurrentIndent) + newScopes.push(scope); + } + + state.scopes = newScopes; + } + + + return style; + } + + return { + startState: function() { + return { + tokenizer: tokenBase, + scopes: [{offset: 0, type: "sass"}], + indentCount: 0, + cursorHalf: 0, // cursor half tells us if cursor lies after (1) + // or before (0) colon (well... more or less) + definedVars: [], + definedMixins: [] + }; + }, + token: function(stream, state) { + var style = tokenLexer(stream, state); + + state.lastToken = { style: style, content: stream.current() }; + + return style; + }, + + indent: function(state) { + return state.scopes[0].offset; + } + }; +}, "css"); + +CodeMirror.defineMIME("text/x-sass", "sass"); + +}); diff --git a/modules/editor/codemirror/mode/slim/slim.min.js b/modules/editor/codemirror/mode/slim/slim.min.js @@ -0,0 +1,575 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// Slim Highlighting for CodeMirror copyright (c) HicknHack Software Gmbh + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror"), require("../htmlmixed/htmlmixed"), require("../ruby/ruby")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror", "../htmlmixed/htmlmixed", "../ruby/ruby"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + + CodeMirror.defineMode("slim", function(config) { + var htmlMode = CodeMirror.getMode(config, {name: "htmlmixed"}); + var rubyMode = CodeMirror.getMode(config, "ruby"); + var modes = { html: htmlMode, ruby: rubyMode }; + var embedded = { + ruby: "ruby", + javascript: "javascript", + css: "text/css", + sass: "text/x-sass", + scss: "text/x-scss", + less: "text/x-less", + styl: "text/x-styl", // no highlighting so far + coffee: "coffeescript", + asciidoc: "text/x-asciidoc", + markdown: "text/x-markdown", + textile: "text/x-textile", // no highlighting so far + creole: "text/x-creole", // no highlighting so far + wiki: "text/x-wiki", // no highlighting so far + mediawiki: "text/x-mediawiki", // no highlighting so far + rdoc: "text/x-rdoc", // no highlighting so far + builder: "text/x-builder", // no highlighting so far + nokogiri: "text/x-nokogiri", // no highlighting so far + erb: "application/x-erb" + }; + var embeddedRegexp = function(map){ + var arr = []; + for(var key in map) arr.push(key); + return new RegExp("^("+arr.join('|')+"):"); + }(embedded); + + var styleMap = { + "commentLine": "comment", + "slimSwitch": "operator special", + "slimTag": "tag", + "slimId": "attribute def", + "slimClass": "attribute qualifier", + "slimAttribute": "attribute", + "slimSubmode": "keyword special", + "closeAttributeTag": null, + "slimDoctype": null, + "lineContinuation": null + }; + var closing = { + "{": "}", + "[": "]", + "(": ")" + }; + + var nameStartChar = "_a-zA-Z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD"; + var nameChar = nameStartChar + "\\-0-9\xB7\u0300-\u036F\u203F-\u2040"; + var nameRegexp = new RegExp("^[:"+nameStartChar+"](?::["+nameChar+"]|["+nameChar+"]*)"); + var attributeNameRegexp = new RegExp("^[:"+nameStartChar+"][:\\."+nameChar+"]*(?=\\s*=)"); + var wrappedAttributeNameRegexp = new RegExp("^[:"+nameStartChar+"][:\\."+nameChar+"]*"); + var classNameRegexp = /^\.-?[_a-zA-Z]+[\w\-]*/; + var classIdRegexp = /^#[_a-zA-Z]+[\w\-]*/; + + function backup(pos, tokenize, style) { + var restore = function(stream, state) { + state.tokenize = tokenize; + if (stream.pos < pos) { + stream.pos = pos; + return style; + } + return state.tokenize(stream, state); + }; + return function(stream, state) { + state.tokenize = restore; + return tokenize(stream, state); + }; + } + + function maybeBackup(stream, state, pat, offset, style) { + var cur = stream.current(); + var idx = cur.search(pat); + if (idx > -1) { + state.tokenize = backup(stream.pos, state.tokenize, style); + stream.backUp(cur.length - idx - offset); + } + return style; + } + + function continueLine(state, column) { + state.stack = { + parent: state.stack, + style: "continuation", + indented: column, + tokenize: state.line + }; + state.line = state.tokenize; + } + function finishContinue(state) { + if (state.line == state.tokenize) { + state.line = state.stack.tokenize; + state.stack = state.stack.parent; + } + } + + function lineContinuable(column, tokenize) { + return function(stream, state) { + finishContinue(state); + if (stream.match(/^\\$/)) { + continueLine(state, column); + return "lineContinuation"; + } + var style = tokenize(stream, state); + if (stream.eol() && stream.current().match(/(?:^|[^\\])(?:\\\\)*\\$/)) { + stream.backUp(1); + } + return style; + }; + } + function commaContinuable(column, tokenize) { + return function(stream, state) { + finishContinue(state); + var style = tokenize(stream, state); + if (stream.eol() && stream.current().match(/,$/)) { + continueLine(state, column); + } + return style; + }; + } + + function rubyInQuote(endQuote, tokenize) { + // TODO: add multi line support + return function(stream, state) { + var ch = stream.peek(); + if (ch == endQuote && state.rubyState.tokenize.length == 1) { + // step out of ruby context as it seems to complete processing all the braces + stream.next(); + state.tokenize = tokenize; + return "closeAttributeTag"; + } else { + return ruby(stream, state); + } + }; + } + function startRubySplat(tokenize) { + var rubyState; + var runSplat = function(stream, state) { + if (state.rubyState.tokenize.length == 1 && !state.rubyState.context.prev) { + stream.backUp(1); + if (stream.eatSpace()) { + state.rubyState = rubyState; + state.tokenize = tokenize; + return tokenize(stream, state); + } + stream.next(); + } + return ruby(stream, state); + }; + return function(stream, state) { + rubyState = state.rubyState; + state.rubyState = CodeMirror.startState(rubyMode); + state.tokenize = runSplat; + return ruby(stream, state); + }; + } + + function ruby(stream, state) { + return rubyMode.token(stream, state.rubyState); + } + + function htmlLine(stream, state) { + if (stream.match(/^\\$/)) { + return "lineContinuation"; + } + return html(stream, state); + } + function html(stream, state) { + if (stream.match(/^#\{/)) { + state.tokenize = rubyInQuote("}", state.tokenize); + return null; + } + return maybeBackup(stream, state, /[^\\]#\{/, 1, htmlMode.token(stream, state.htmlState)); + } + + function startHtmlLine(lastTokenize) { + return function(stream, state) { + var style = htmlLine(stream, state); + if (stream.eol()) state.tokenize = lastTokenize; + return style; + }; + } + + function startHtmlMode(stream, state, offset) { + state.stack = { + parent: state.stack, + style: "html", + indented: stream.column() + offset, // pipe + space + tokenize: state.line + }; + state.line = state.tokenize = html; + return null; + } + + function comment(stream, state) { + stream.skipToEnd(); + return state.stack.style; + } + + function commentMode(stream, state) { + state.stack = { + parent: state.stack, + style: "comment", + indented: state.indented + 1, + tokenize: state.line + }; + state.line = comment; + return comment(stream, state); + } + + function attributeWrapper(stream, state) { + if (stream.eat(state.stack.endQuote)) { + state.line = state.stack.line; + state.tokenize = state.stack.tokenize; + state.stack = state.stack.parent; + return null; + } + if (stream.match(wrappedAttributeNameRegexp)) { + state.tokenize = attributeWrapperAssign; + return "slimAttribute"; + } + stream.next(); + return null; + } + function attributeWrapperAssign(stream, state) { + if (stream.match(/^==?/)) { + state.tokenize = attributeWrapperValue; + return null; + } + return attributeWrapper(stream, state); + } + function attributeWrapperValue(stream, state) { + var ch = stream.peek(); + if (ch == '"' || ch == "\'") { + state.tokenize = readQuoted(ch, "string", true, false, attributeWrapper); + stream.next(); + return state.tokenize(stream, state); + } + if (ch == '[') { + return startRubySplat(attributeWrapper)(stream, state); + } + if (stream.match(/^(true|false|nil)\b/)) { + state.tokenize = attributeWrapper; + return "keyword"; + } + return startRubySplat(attributeWrapper)(stream, state); + } + + function startAttributeWrapperMode(state, endQuote, tokenize) { + state.stack = { + parent: state.stack, + style: "wrapper", + indented: state.indented + 1, + tokenize: tokenize, + line: state.line, + endQuote: endQuote + }; + state.line = state.tokenize = attributeWrapper; + return null; + } + + function sub(stream, state) { + if (stream.match(/^#\{/)) { + state.tokenize = rubyInQuote("}", state.tokenize); + return null; + } + var subStream = new CodeMirror.StringStream(stream.string.slice(state.stack.indented), stream.tabSize); + subStream.pos = stream.pos - state.stack.indented; + subStream.start = stream.start - state.stack.indented; + subStream.lastColumnPos = stream.lastColumnPos - state.stack.indented; + subStream.lastColumnValue = stream.lastColumnValue - state.stack.indented; + var style = state.subMode.token(subStream, state.subState); + stream.pos = subStream.pos + state.stack.indented; + return style; + } + function firstSub(stream, state) { + state.stack.indented = stream.column(); + state.line = state.tokenize = sub; + return state.tokenize(stream, state); + } + + function createMode(mode) { + var query = embedded[mode]; + var spec = CodeMirror.mimeModes[query]; + if (spec) { + return CodeMirror.getMode(config, spec); + } + var factory = CodeMirror.modes[query]; + if (factory) { + return factory(config, {name: query}); + } + return CodeMirror.getMode(config, "null"); + } + + function getMode(mode) { + if (!modes.hasOwnProperty(mode)) { + return modes[mode] = createMode(mode); + } + return modes[mode]; + } + + function startSubMode(mode, state) { + var subMode = getMode(mode); + var subState = CodeMirror.startState(subMode); + + state.subMode = subMode; + state.subState = subState; + + state.stack = { + parent: state.stack, + style: "sub", + indented: state.indented + 1, + tokenize: state.line + }; + state.line = state.tokenize = firstSub; + return "slimSubmode"; + } + + function doctypeLine(stream, _state) { + stream.skipToEnd(); + return "slimDoctype"; + } + + function startLine(stream, state) { + var ch = stream.peek(); + if (ch == '<') { + return (state.tokenize = startHtmlLine(state.tokenize))(stream, state); + } + if (stream.match(/^[|']/)) { + return startHtmlMode(stream, state, 1); + } + if (stream.match(/^\/(!|\[\w+])?/)) { + return commentMode(stream, state); + } + if (stream.match(/^(-|==?[<>]?)/)) { + state.tokenize = lineContinuable(stream.column(), commaContinuable(stream.column(), ruby)); + return "slimSwitch"; + } + if (stream.match(/^doctype\b/)) { + state.tokenize = doctypeLine; + return "keyword"; + } + + var m = stream.match(embeddedRegexp); + if (m) { + return startSubMode(m[1], state); + } + + return slimTag(stream, state); + } + + function slim(stream, state) { + if (state.startOfLine) { + return startLine(stream, state); + } + return slimTag(stream, state); + } + + function slimTag(stream, state) { + if (stream.eat('*')) { + state.tokenize = startRubySplat(slimTagExtras); + return null; + } + if (stream.match(nameRegexp)) { + state.tokenize = slimTagExtras; + return "slimTag"; + } + return slimClass(stream, state); + } + function slimTagExtras(stream, state) { + if (stream.match(/^(<>?|><?)/)) { + state.tokenize = slimClass; + return null; + } + return slimClass(stream, state); + } + function slimClass(stream, state) { + if (stream.match(classIdRegexp)) { + state.tokenize = slimClass; + return "slimId"; + } + if (stream.match(classNameRegexp)) { + state.tokenize = slimClass; + return "slimClass"; + } + return slimAttribute(stream, state); + } + function slimAttribute(stream, state) { + if (stream.match(/^([\[\{\(])/)) { + return startAttributeWrapperMode(state, closing[RegExp.$1], slimAttribute); + } + if (stream.match(attributeNameRegexp)) { + state.tokenize = slimAttributeAssign; + return "slimAttribute"; + } + if (stream.peek() == '*') { + stream.next(); + state.tokenize = startRubySplat(slimContent); + return null; + } + return slimContent(stream, state); + } + function slimAttributeAssign(stream, state) { + if (stream.match(/^==?/)) { + state.tokenize = slimAttributeValue; + return null; + } + // should never happen, because of forward lookup + return slimAttribute(stream, state); + } + + function slimAttributeValue(stream, state) { + var ch = stream.peek(); + if (ch == '"' || ch == "\'") { + state.tokenize = readQuoted(ch, "string", true, false, slimAttribute); + stream.next(); + return state.tokenize(stream, state); + } + if (ch == '[') { + return startRubySplat(slimAttribute)(stream, state); + } + if (ch == ':') { + return startRubySplat(slimAttributeSymbols)(stream, state); + } + if (stream.match(/^(true|false|nil)\b/)) { + state.tokenize = slimAttribute; + return "keyword"; + } + return startRubySplat(slimAttribute)(stream, state); + } + function slimAttributeSymbols(stream, state) { + stream.backUp(1); + if (stream.match(/^[^\s],(?=:)/)) { + state.tokenize = startRubySplat(slimAttributeSymbols); + return null; + } + stream.next(); + return slimAttribute(stream, state); + } + function readQuoted(quote, style, embed, unescaped, nextTokenize) { + return function(stream, state) { + finishContinue(state); + var fresh = stream.current().length == 0; + if (stream.match(/^\\$/, fresh)) { + if (!fresh) return style; + continueLine(state, state.indented); + return "lineContinuation"; + } + if (stream.match(/^#\{/, fresh)) { + if (!fresh) return style; + state.tokenize = rubyInQuote("}", state.tokenize); + return null; + } + var escaped = false, ch; + while ((ch = stream.next()) != null) { + if (ch == quote && (unescaped || !escaped)) { + state.tokenize = nextTokenize; + break; + } + if (embed && ch == "#" && !escaped) { + if (stream.eat("{")) { + stream.backUp(2); + break; + } + } + escaped = !escaped && ch == "\\"; + } + if (stream.eol() && escaped) { + stream.backUp(1); + } + return style; + }; + } + function slimContent(stream, state) { + if (stream.match(/^==?/)) { + state.tokenize = ruby; + return "slimSwitch"; + } + if (stream.match(/^\/$/)) { // tag close hint + state.tokenize = slim; + return null; + } + if (stream.match(/^:/)) { // inline tag + state.tokenize = slimTag; + return "slimSwitch"; + } + startHtmlMode(stream, state, 0); + return state.tokenize(stream, state); + } + + var mode = { + // default to html mode + startState: function() { + var htmlState = CodeMirror.startState(htmlMode); + var rubyState = CodeMirror.startState(rubyMode); + return { + htmlState: htmlState, + rubyState: rubyState, + stack: null, + last: null, + tokenize: slim, + line: slim, + indented: 0 + }; + }, + + copyState: function(state) { + return { + htmlState : CodeMirror.copyState(htmlMode, state.htmlState), + rubyState: CodeMirror.copyState(rubyMode, state.rubyState), + subMode: state.subMode, + subState: state.subMode && CodeMirror.copyState(state.subMode, state.subState), + stack: state.stack, + last: state.last, + tokenize: state.tokenize, + line: state.line + }; + }, + + token: function(stream, state) { + if (stream.sol()) { + state.indented = stream.indentation(); + state.startOfLine = true; + state.tokenize = state.line; + while (state.stack && state.stack.indented > state.indented && state.last != "slimSubmode") { + state.line = state.tokenize = state.stack.tokenize; + state.stack = state.stack.parent; + state.subMode = null; + state.subState = null; + } + } + if (stream.eatSpace()) return null; + var style = state.tokenize(stream, state); + state.startOfLine = false; + if (style) state.last = style; + return styleMap.hasOwnProperty(style) ? styleMap[style] : style; + }, + + blankLine: function(state) { + if (state.subMode && state.subMode.blankLine) { + return state.subMode.blankLine(state.subState); + } + }, + + innerMode: function(state) { + if (state.subMode) return {state: state.subState, mode: state.subMode}; + return {state: state, mode: mode}; + } + + //indent: function(state) { + // return state.indented; + //} + }; + return mode; + }, "htmlmixed", "ruby"); + + CodeMirror.defineMIME("text/x-slim", "slim"); + CodeMirror.defineMIME("application/x-slim", "slim"); +}); diff --git a/modules/editor/codemirror/mode/solr/solr.min.js b/modules/editor/codemirror/mode/solr/solr.min.js @@ -0,0 +1,104 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode("solr", function() { + "use strict"; + + var isStringChar = /[^\s\|\!\+\-\*\?\~\^\&\:\(\)\[\]\{\}\"\\]/; + var isOperatorChar = /[\|\!\+\-\*\?\~\^\&]/; + var isOperatorString = /^(OR|AND|NOT|TO)$/i; + + function isNumber(word) { + return parseFloat(word).toString() === word; + } + + function tokenString(quote) { + return function(stream, state) { + var escaped = false, next; + while ((next = stream.next()) != null) { + if (next == quote && !escaped) break; + escaped = !escaped && next == "\\"; + } + + if (!escaped) state.tokenize = tokenBase; + return "string"; + }; + } + + function tokenOperator(operator) { + return function(stream, state) { + var style = "operator"; + if (operator == "+") + style += " positive"; + else if (operator == "-") + style += " negative"; + else if (operator == "|") + stream.eat(/\|/); + else if (operator == "&") + stream.eat(/\&/); + else if (operator == "^") + style += " boost"; + + state.tokenize = tokenBase; + return style; + }; + } + + function tokenWord(ch) { + return function(stream, state) { + var word = ch; + while ((ch = stream.peek()) && ch.match(isStringChar) != null) { + word += stream.next(); + } + + state.tokenize = tokenBase; + if (isOperatorString.test(word)) + return "operator"; + else if (isNumber(word)) + return "number"; + else if (stream.peek() == ":") + return "field"; + else + return "string"; + }; + } + + function tokenBase(stream, state) { + var ch = stream.next(); + if (ch == '"') + state.tokenize = tokenString(ch); + else if (isOperatorChar.test(ch)) + state.tokenize = tokenOperator(ch); + else if (isStringChar.test(ch)) + state.tokenize = tokenWord(ch); + + return (state.tokenize != tokenBase) ? state.tokenize(stream, state) : null; + } + + return { + startState: function() { + return { + tokenize: tokenBase + }; + }, + + token: function(stream, state) { + if (stream.eatSpace()) return null; + return state.tokenize(stream, state); + } + }; +}); + +CodeMirror.defineMIME("text/x-solr", "solr"); + +}); diff --git a/modules/editor/codemirror/mode/stylus/stylus.min.js b/modules/editor/codemirror/mode/stylus/stylus.min.js @@ -0,0 +1,771 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// Stylus mode created by Dmitry Kiselyov http://git.io/AaRB + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + CodeMirror.defineMode("stylus", function(config) { + var indentUnit = config.indentUnit, + indentUnitString = '', + tagKeywords = keySet(tagKeywords_), + tagVariablesRegexp = /^(a|b|i|s|col|em)$/i, + propertyKeywords = keySet(propertyKeywords_), + nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_), + valueKeywords = keySet(valueKeywords_), + colorKeywords = keySet(colorKeywords_), + documentTypes = keySet(documentTypes_), + documentTypesRegexp = wordRegexp(documentTypes_), + mediaFeatures = keySet(mediaFeatures_), + mediaTypes = keySet(mediaTypes_), + fontProperties = keySet(fontProperties_), + operatorsRegexp = /^\s*([.]{2,3}|&&|\|\||\*\*|[?!=:]?=|[-+*\/%<>]=?|\?:|\~)/, + wordOperatorKeywordsRegexp = wordRegexp(wordOperatorKeywords_), + blockKeywords = keySet(blockKeywords_), + vendorPrefixesRegexp = new RegExp(/^\-(moz|ms|o|webkit)-/i), + commonAtoms = keySet(commonAtoms_), + firstWordMatch = "", + states = {}, + ch, + style, + type, + override; + + while (indentUnitString.length < indentUnit) indentUnitString += ' '; + + /** + * Tokenizers + */ + function tokenBase(stream, state) { + firstWordMatch = stream.string.match(/(^[\w-]+\s*=\s*$)|(^\s*[\w-]+\s*=\s*[\w-])|(^\s*(\.|#|@|\$|\&|\[|\d|\+|::?|\{|\>|~|\/)?\s*[\w-]*([a-z0-9-]|\*|\/\*)(\(|,)?)/); + state.context.line.firstWord = firstWordMatch ? firstWordMatch[0].replace(/^\s*/, "") : ""; + state.context.line.indent = stream.indentation(); + ch = stream.peek(); + + // Line comment + if (stream.match("//")) { + stream.skipToEnd(); + return ["comment", "comment"]; + } + // Block comment + if (stream.match("/*")) { + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } + // String + if (ch == "\"" || ch == "'") { + stream.next(); + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } + // Def + if (ch == "@") { + stream.next(); + stream.eatWhile(/[\w\\-]/); + return ["def", stream.current()]; + } + // ID selector or Hex color + if (ch == "#") { + stream.next(); + // Hex color + if (stream.match(/^[0-9a-f]{6}|[0-9a-f]{3}/i)) { + return ["atom", "atom"]; + } + // ID selector + if (stream.match(/^[a-z][\w-]*/i)) { + return ["builtin", "hash"]; + } + } + // Vendor prefixes + if (stream.match(vendorPrefixesRegexp)) { + return ["meta", "vendor-prefixes"]; + } + // Numbers + if (stream.match(/^-?[0-9]?\.?[0-9]/)) { + stream.eatWhile(/[a-z%]/i); + return ["number", "unit"]; + } + // !important|optional + if (ch == "!") { + stream.next(); + return [stream.match(/^(important|optional)/i) ? "keyword": "operator", "important"]; + } + // Class + if (ch == "." && stream.match(/^\.[a-z][\w-]*/i)) { + return ["qualifier", "qualifier"]; + } + // url url-prefix domain regexp + if (stream.match(documentTypesRegexp)) { + if (stream.peek() == "(") state.tokenize = tokenParenthesized; + return ["property", "word"]; + } + // Mixins / Functions + if (stream.match(/^[a-z][\w-]*\(/i)) { + stream.backUp(1); + return ["keyword", "mixin"]; + } + // Block mixins + if (stream.match(/^(\+|-)[a-z][\w-]*\(/i)) { + stream.backUp(1); + return ["keyword", "block-mixin"]; + } + // Parent Reference BEM naming + if (stream.string.match(/^\s*&/) && stream.match(/^[-_]+[a-z][\w-]*/)) { + return ["qualifier", "qualifier"]; + } + // / Root Reference & Parent Reference + if (stream.match(/^(\/|&)(-|_|:|\.|#|[a-z])/)) { + stream.backUp(1); + return ["variable-3", "reference"]; + } + if (stream.match(/^&{1}\s*$/)) { + return ["variable-3", "reference"]; + } + // Word operator + if (stream.match(wordOperatorKeywordsRegexp)) { + return ["operator", "operator"]; + } + // Word + if (stream.match(/^\$?[-_]*[a-z0-9]+[\w-]*/i)) { + // Variable + if (stream.match(/^(\.|\[)[\w-\'\"\]]+/i, false)) { + if (!wordIsTag(stream.current())) { + stream.match(/\./); + return ["variable-2", "variable-name"]; + } + } + return ["variable-2", "word"]; + } + // Operators + if (stream.match(operatorsRegexp)) { + return ["operator", stream.current()]; + } + // Delimiters + if (/[:;,{}\[\]\(\)]/.test(ch)) { + stream.next(); + return [null, ch]; + } + // Non-detected items + stream.next(); + return [null, null]; + } + + /** + * Token comment + */ + function tokenCComment(stream, state) { + var maybeEnd = false, ch; + while ((ch = stream.next()) != null) { + if (maybeEnd && ch == "/") { + state.tokenize = null; + break; + } + maybeEnd = (ch == "*"); + } + return ["comment", "comment"]; + } + + /** + * Token string + */ + function tokenString(quote) { + return function(stream, state) { + var escaped = false, ch; + while ((ch = stream.next()) != null) { + if (ch == quote && !escaped) { + if (quote == ")") stream.backUp(1); + break; + } + escaped = !escaped && ch == "\\"; + } + if (ch == quote || !escaped && quote != ")") state.tokenize = null; + return ["string", "string"]; + }; + } + + /** + * Token parenthesized + */ + function tokenParenthesized(stream, state) { + stream.next(); // Must be "(" + if (!stream.match(/\s*[\"\')]/, false)) + state.tokenize = tokenString(")"); + else + state.tokenize = null; + return [null, "("]; + } + + /** + * Context management + */ + function Context(type, indent, prev, line) { + this.type = type; + this.indent = indent; + this.prev = prev; + this.line = line || {firstWord: "", indent: 0}; + } + + function pushContext(state, stream, type, indent) { + indent = indent >= 0 ? indent : indentUnit; + state.context = new Context(type, stream.indentation() + indent, state.context); + return type; + } + + function popContext(state, currentIndent) { + var contextIndent = state.context.indent - indentUnit; + currentIndent = currentIndent || false; + state.context = state.context.prev; + if (currentIndent) state.context.indent = contextIndent; + 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); + } + + + /** + * Parser + */ + function wordIsTag(word) { + return word.toLowerCase() in tagKeywords; + } + + function wordIsProperty(word) { + word = word.toLowerCase(); + return word in propertyKeywords || word in fontProperties; + } + + function wordIsBlock(word) { + return word.toLowerCase() in blockKeywords; + } + + function wordIsVendorPrefix(word) { + return word.toLowerCase().match(vendorPrefixesRegexp); + } + + function wordAsValue(word) { + var wordLC = word.toLowerCase(); + var override = "variable-2"; + if (wordIsTag(word)) override = "tag"; + else if (wordIsBlock(word)) override = "block-keyword"; + else if (wordIsProperty(word)) override = "property"; + else if (wordLC in valueKeywords || wordLC in commonAtoms) override = "atom"; + else if (wordLC == "return" || wordLC in colorKeywords) override = "keyword"; + + // Font family + else if (word.match(/^[A-Z]/)) override = "string"; + return override; + } + + function typeIsBlock(type, stream) { + return ((endOfLine(stream) && (type == "{" || type == "]" || type == "hash" || type == "qualifier")) || type == "block-mixin"); + } + + function typeIsInterpolation(type, stream) { + return type == "{" && stream.match(/^\s*\$?[\w-]+/i, false); + } + + function typeIsPseudo(type, stream) { + return type == ":" && stream.match(/^[a-z-]+/, false); + } + + function startOfLine(stream) { + return stream.sol() || stream.string.match(new RegExp("^\\s*" + escapeRegExp(stream.current()))); + } + + function endOfLine(stream) { + return stream.eol() || stream.match(/^\s*$/, false); + } + + function firstWordOfLine(line) { + var re = /^\s*[-_]*[a-z0-9]+[\w-]*/i; + var result = typeof line == "string" ? line.match(re) : line.string.match(re); + return result ? result[0].replace(/^\s*/, "") : ""; + } + + + /** + * Block + */ + states.block = function(type, stream, state) { + if ((type == "comment" && startOfLine(stream)) || + (type == "," && endOfLine(stream)) || + type == "mixin") { + return pushContext(state, stream, "block", 0); + } + if (typeIsInterpolation(type, stream)) { + return pushContext(state, stream, "interpolation"); + } + if (endOfLine(stream) && type == "]") { + if (!/^\s*(\.|#|:|\[|\*|&)/.test(stream.string) && !wordIsTag(firstWordOfLine(stream))) { + return pushContext(state, stream, "block", 0); + } + } + if (typeIsBlock(type, stream)) { + return pushContext(state, stream, "block"); + } + if (type == "}" && endOfLine(stream)) { + return pushContext(state, stream, "block", 0); + } + if (type == "variable-name") { + if (stream.string.match(/^\s?\$[\w-\.\[\]\'\"]+$/) || wordIsBlock(firstWordOfLine(stream))) { + return pushContext(state, stream, "variableName"); + } + else { + return pushContext(state, stream, "variableName", 0); + } + } + if (type == "=") { + if (!endOfLine(stream) && !wordIsBlock(firstWordOfLine(stream))) { + return pushContext(state, stream, "block", 0); + } + return pushContext(state, stream, "block"); + } + if (type == "*") { + if (endOfLine(stream) || stream.match(/\s*(,|\.|#|\[|:|{)/,false)) { + override = "tag"; + return pushContext(state, stream, "block"); + } + } + if (typeIsPseudo(type, stream)) { + return pushContext(state, stream, "pseudo"); + } + if (/@(font-face|media|supports|(-moz-)?document)/.test(type)) { + return pushContext(state, stream, endOfLine(stream) ? "block" : "atBlock"); + } + if (/@(-(moz|ms|o|webkit)-)?keyframes$/.test(type)) { + return pushContext(state, stream, "keyframes"); + } + if (/@extends?/.test(type)) { + return pushContext(state, stream, "extend", 0); + } + if (type && type.charAt(0) == "@") { + + // Property Lookup + if (stream.indentation() > 0 && wordIsProperty(stream.current().slice(1))) { + override = "variable-2"; + return "block"; + } + if (/(@import|@require|@charset)/.test(type)) { + return pushContext(state, stream, "block", 0); + } + return pushContext(state, stream, "block"); + } + if (type == "reference" && endOfLine(stream)) { + return pushContext(state, stream, "block"); + } + if (type == "(") { + return pushContext(state, stream, "parens"); + } + + if (type == "vendor-prefixes") { + return pushContext(state, stream, "vendorPrefixes"); + } + if (type == "word") { + var word = stream.current(); + override = wordAsValue(word); + + if (override == "property") { + if (startOfLine(stream)) { + return pushContext(state, stream, "block", 0); + } else { + override = "atom"; + return "block"; + } + } + + if (override == "tag") { + + // tag is a css value + if (/embed|menu|pre|progress|sub|table/.test(word)) { + if (wordIsProperty(firstWordOfLine(stream))) { + override = "atom"; + return "block"; + } + } + + // tag is an attribute + if (stream.string.match(new RegExp("\\[\\s*" + word + "|" + word +"\\s*\\]"))) { + override = "atom"; + return "block"; + } + + // tag is a variable + if (tagVariablesRegexp.test(word)) { + if ((startOfLine(stream) && stream.string.match(/=/)) || + (!startOfLine(stream) && + !stream.string.match(/^(\s*\.|#|\&|\[|\/|>|\*)/) && + !wordIsTag(firstWordOfLine(stream)))) { + override = "variable-2"; + if (wordIsBlock(firstWordOfLine(stream))) return "block"; + return pushContext(state, stream, "block", 0); + } + } + + if (endOfLine(stream)) return pushContext(state, stream, "block"); + } + if (override == "block-keyword") { + override = "keyword"; + + // Postfix conditionals + if (stream.current(/(if|unless)/) && !startOfLine(stream)) { + return "block"; + } + return pushContext(state, stream, "block"); + } + if (word == "return") return pushContext(state, stream, "block", 0); + + // Placeholder selector + if (override == "variable-2" && stream.string.match(/^\s?\$[\w-\.\[\]\'\"]+$/)) { + return pushContext(state, stream, "block"); + } + } + return state.context.type; + }; + + + /** + * Parens + */ + states.parens = function(type, stream, state) { + if (type == "(") return pushContext(state, stream, "parens"); + if (type == ")") { + if (state.context.prev.type == "parens") { + return popContext(state); + } + if ((stream.string.match(/^[a-z][\w-]*\(/i) && endOfLine(stream)) || + wordIsBlock(firstWordOfLine(stream)) || + /(\.|#|:|\[|\*|&|>|~|\+|\/)/.test(firstWordOfLine(stream)) || + (!stream.string.match(/^-?[a-z][\w-\.\[\]\'\"]*\s*=/) && + wordIsTag(firstWordOfLine(stream)))) { + return pushContext(state, stream, "block"); + } + if (stream.string.match(/^[\$-]?[a-z][\w-\.\[\]\'\"]*\s*=/) || + stream.string.match(/^\s*(\(|\)|[0-9])/) || + stream.string.match(/^\s+[a-z][\w-]*\(/i) || + stream.string.match(/^\s+[\$-]?[a-z]/i)) { + return pushContext(state, stream, "block", 0); + } + if (endOfLine(stream)) return pushContext(state, stream, "block"); + else return pushContext(state, stream, "block", 0); + } + if (type && type.charAt(0) == "@" && wordIsProperty(stream.current().slice(1))) { + override = "variable-2"; + } + if (type == "word") { + var word = stream.current(); + override = wordAsValue(word); + if (override == "tag" && tagVariablesRegexp.test(word)) { + override = "variable-2"; + } + if (override == "property" || word == "to") override = "atom"; + } + if (type == "variable-name") { + return pushContext(state, stream, "variableName"); + } + if (typeIsPseudo(type, stream)) { + return pushContext(state, stream, "pseudo"); + } + return state.context.type; + }; + + + /** + * Vendor prefixes + */ + states.vendorPrefixes = function(type, stream, state) { + if (type == "word") { + override = "property"; + return pushContext(state, stream, "block", 0); + } + return popContext(state); + }; + + + /** + * Pseudo + */ + states.pseudo = function(type, stream, state) { + if (!wordIsProperty(firstWordOfLine(stream.string))) { + stream.match(/^[a-z-]+/); + override = "variable-3"; + if (endOfLine(stream)) return pushContext(state, stream, "block"); + return popContext(state); + } + return popAndPass(type, stream, state); + }; + + + /** + * atBlock + */ + states.atBlock = function(type, stream, state) { + if (type == "(") return pushContext(state, stream, "atBlock_parens"); + if (typeIsBlock(type, stream)) { + return pushContext(state, stream, "block"); + } + if (typeIsInterpolation(type, stream)) { + return pushContext(state, stream, "interpolation"); + } + if (type == "word") { + var word = stream.current().toLowerCase(); + if (/^(only|not|and|or)$/.test(word)) + override = "keyword"; + else if (documentTypes.hasOwnProperty(word)) + override = "tag"; + else if (mediaTypes.hasOwnProperty(word)) + override = "attribute"; + else if (mediaFeatures.hasOwnProperty(word)) + override = "property"; + else if (nonStandardPropertyKeywords.hasOwnProperty(word)) + override = "string-2"; + else override = wordAsValue(stream.current()); + if (override == "tag" && endOfLine(stream)) { + return pushContext(state, stream, "block"); + } + } + if (type == "operator" && /^(not|and|or)$/.test(stream.current())) { + override = "keyword"; + } + return state.context.type; + }; + + states.atBlock_parens = function(type, stream, state) { + if (type == "{" || type == "}") return state.context.type; + if (type == ")") { + if (endOfLine(stream)) return pushContext(state, stream, "block"); + else return pushContext(state, stream, "atBlock"); + } + if (type == "word") { + var word = stream.current().toLowerCase(); + override = wordAsValue(word); + if (/^(max|min)/.test(word)) override = "property"; + if (override == "tag") { + tagVariablesRegexp.test(word) ? override = "variable-2" : override = "atom"; + } + return state.context.type; + } + return states.atBlock(type, stream, state); + }; + + + /** + * Keyframes + */ + states.keyframes = function(type, stream, state) { + if (stream.indentation() == "0" && ((type == "}" && startOfLine(stream)) || type == "]" || type == "hash" + || type == "qualifier" || wordIsTag(stream.current()))) { + return popAndPass(type, stream, state); + } + if (type == "{") return pushContext(state, stream, "keyframes"); + if (type == "}") { + if (startOfLine(stream)) return popContext(state, true); + else return pushContext(state, stream, "keyframes"); + } + if (type == "unit" && /^[0-9]+\%$/.test(stream.current())) { + return pushContext(state, stream, "keyframes"); + } + if (type == "word") { + override = wordAsValue(stream.current()); + if (override == "block-keyword") { + override = "keyword"; + return pushContext(state, stream, "keyframes"); + } + } + if (/@(font-face|media|supports|(-moz-)?document)/.test(type)) { + return pushContext(state, stream, endOfLine(stream) ? "block" : "atBlock"); + } + if (type == "mixin") { + return pushContext(state, stream, "block", 0); + } + return state.context.type; + }; + + + /** + * Interpolation + */ + states.interpolation = function(type, stream, state) { + if (type == "{") popContext(state) && pushContext(state, stream, "block"); + if (type == "}") { + if (stream.string.match(/^\s*(\.|#|:|\[|\*|&|>|~|\+|\/)/i) || + (stream.string.match(/^\s*[a-z]/i) && wordIsTag(firstWordOfLine(stream)))) { + return pushContext(state, stream, "block"); + } + if (!stream.string.match(/^(\{|\s*\&)/) || + stream.match(/\s*[\w-]/,false)) { + return pushContext(state, stream, "block", 0); + } + return pushContext(state, stream, "block"); + } + if (type == "variable-name") { + return pushContext(state, stream, "variableName", 0); + } + if (type == "word") { + override = wordAsValue(stream.current()); + if (override == "tag") override = "atom"; + } + return state.context.type; + }; + + + /** + * Extend/s + */ + states.extend = function(type, stream, state) { + if (type == "[" || type == "=") return "extend"; + if (type == "]") return popContext(state); + if (type == "word") { + override = wordAsValue(stream.current()); + return "extend"; + } + return popContext(state); + }; + + + /** + * Variable name + */ + states.variableName = function(type, stream, state) { + if (type == "string" || type == "[" || type == "]" || stream.current().match(/^(\.|\$)/)) { + if (stream.current().match(/^\.[\w-]+/i)) override = "variable-2"; + return "variableName"; + } + return popAndPass(type, stream, state); + }; + + + return { + startState: function(base) { + return { + tokenize: null, + state: "block", + context: new Context("block", base || 0, null) + }; + }, + token: function(stream, state) { + if (!state.tokenize && stream.eatSpace()) return null; + style = (state.tokenize || tokenBase)(stream, state); + if (style && typeof style == "object") { + type = style[1]; + style = style[0]; + } + override = style; + state.state = states[state.state](type, stream, state); + return override; + }, + indent: function(state, textAfter, line) { + + var cx = state.context, + ch = textAfter && textAfter.charAt(0), + indent = cx.indent, + lineFirstWord = firstWordOfLine(textAfter), + lineIndent = line.match(/^\s*/)[0].replace(/\t/g, indentUnitString).length, + prevLineFirstWord = state.context.prev ? state.context.prev.line.firstWord : "", + prevLineIndent = state.context.prev ? state.context.prev.line.indent : lineIndent; + + if (cx.prev && + (ch == "}" && (cx.type == "block" || cx.type == "atBlock" || cx.type == "keyframes") || + ch == ")" && (cx.type == "parens" || cx.type == "atBlock_parens") || + ch == "{" && (cx.type == "at"))) { + indent = cx.indent - indentUnit; + } else if (!(/(\})/.test(ch))) { + if (/@|\$|\d/.test(ch) || + /^\{/.test(textAfter) || +/^\s*\/(\/|\*)/.test(textAfter) || + /^\s*\/\*/.test(prevLineFirstWord) || + /^\s*[\w-\.\[\]\'\"]+\s*(\?|:|\+)?=/i.test(textAfter) || +/^(\+|-)?[a-z][\w-]*\(/i.test(textAfter) || +/^return/.test(textAfter) || + wordIsBlock(lineFirstWord)) { + indent = lineIndent; + } else if (/(\.|#|:|\[|\*|&|>|~|\+|\/)/.test(ch) || wordIsTag(lineFirstWord)) { + if (/\,\s*$/.test(prevLineFirstWord)) { + indent = prevLineIndent; + } else if (/^\s+/.test(line) && (/(\.|#|:|\[|\*|&|>|~|\+|\/)/.test(prevLineFirstWord) || wordIsTag(prevLineFirstWord))) { + indent = lineIndent <= prevLineIndent ? prevLineIndent : prevLineIndent + indentUnit; + } else { + indent = lineIndent; + } + } else if (!/,\s*$/.test(line) && (wordIsVendorPrefix(lineFirstWord) || wordIsProperty(lineFirstWord))) { + if (wordIsBlock(prevLineFirstWord)) { + indent = lineIndent <= prevLineIndent ? prevLineIndent : prevLineIndent + indentUnit; + } else if (/^\{/.test(prevLineFirstWord)) { + indent = lineIndent <= prevLineIndent ? lineIndent : prevLineIndent + indentUnit; + } else if (wordIsVendorPrefix(prevLineFirstWord) || wordIsProperty(prevLineFirstWord)) { + indent = lineIndent >= prevLineIndent ? prevLineIndent : lineIndent; + } else if (/^(\.|#|:|\[|\*|&|@|\+|\-|>|~|\/)/.test(prevLineFirstWord) || + /=\s*$/.test(prevLineFirstWord) || + wordIsTag(prevLineFirstWord) || + /^\$[\w-\.\[\]\'\"]/.test(prevLineFirstWord)) { + indent = prevLineIndent + indentUnit; + } else { + indent = lineIndent; + } + } + } + return indent; + }, + electricChars: "}", + lineComment: "//", + fold: "indent" + }; + }); + + // developer.mozilla.org/en-US/docs/Web/HTML/Element + var tagKeywords_ = ["a","abbr","address","area","article","aside","audio", "b", "base","bdi", "bdo","bgsound","blockquote","body","br","button","canvas","caption","cite", "code","col","colgroup","data","datalist","dd","del","details","dfn","div", "dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1", "h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe", "img","input","ins","kbd","keygen","label","legend","li","link","main","map", "mark","marquee","menu","menuitem","meta","meter","nav","nobr","noframes", "noscript","object","ol","optgroup","option","output","p","param","pre", "progress","q","rp","rt","ruby","s","samp","script","section","select", "small","source","span","strong","style","sub","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","track", "u","ul","var","video"]; + + // github.com/codemirror/CodeMirror/blob/master/mode/css/css.js + var documentTypes_ = ["domain", "regexp", "url", "url-prefix"]; + var mediaTypes_ = ["all","aural","braille","handheld","print","projection","screen","tty","tv","embossed"]; + var 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"]; + var 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-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","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","font-smoothing","osx-font-smoothing"]; + var 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"]; + var fontProperties_ = ["font-family","src","unicode-range","font-variant","font-feature-settings","font-stretch","font-weight","font-style"]; + var 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"]; + var 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","column","compact","condensed","contain","content","contents","content-box","context-menu","continuous","copy","counter","counters","cover","crop","cross","crosshair","currentcolor","cursive","cyclic","dashed","decimal","decimal-leading-zero","default","default-button","destination-atop","destination-in","destination-out","destination-over","devanagari","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","expanded","extends","extra-condensed","extra-expanded","fantasy","fast","fill","fixed","flat","flex","footnotes","forwards","from","geometricPrecision","georgian","graytext","groove","gujarati","gurmukhi","hand","hangul","hangul-consonant","hebrew","help","hidden","hide","higher","highlight","highlighttext","hiragana","hiragana-iroha","horizontal","hsl","hsla","icon","ignore","inactiveborder","inactivecaption","inactivecaptiontext","infinite","infobackground","infotext","inherit","initial","inline","inline-axis","inline-block","inline-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","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","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","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-resize","rtl","run-in","running","s-resize","sans-serif","scale","scale3d","scaleX","scaleY","scaleZ","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","solid","somali","source-atop","source-in","source-out","source-over","space","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","x-large","x-small","xor","xx-large","xx-small","bicubic","optimizespeed","grayscale","row","row-reverse","wrap","wrap-reverse","column-reverse","flex-start","flex-end","space-between","space-around", "unset"]; + + var wordOperatorKeywords_ = ["in","and","or","not","is not","is a","is","isnt","defined","if unless"], + blockKeywords_ = ["for","if","else","unless", "from", "to"], + commonAtoms_ = ["null","true","false","href","title","type","not-allowed","readonly","disabled"], + commonDef_ = ["@font-face", "@keyframes", "@media", "@viewport", "@page", "@host", "@supports", "@block", "@css"]; + + var hintWords = tagKeywords_.concat(documentTypes_,mediaTypes_,mediaFeatures_, + propertyKeywords_,nonStandardPropertyKeywords_, + colorKeywords_,valueKeywords_,fontProperties_, + wordOperatorKeywords_,blockKeywords_, + commonAtoms_,commonDef_); + + function wordRegexp(words) { + words = words.sort(function(a,b){return b > a;}); + return new RegExp("^((" + words.join(")|(") + "))\\b"); + } + + function keySet(array) { + var keys = {}; + for (var i = 0; i < array.length; ++i) keys[array[i]] = true; + return keys; + } + + function escapeRegExp(text) { + return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); + } + + CodeMirror.registerHelper("hintWords", "stylus", hintWords); + CodeMirror.defineMIME("text/x-styl", "stylus"); +}); diff --git a/modules/editor/codemirror/mode/tiki/tiki.min.js b/modules/editor/codemirror/mode/tiki/tiki.min.js @@ -0,0 +1,312 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode('tiki', function(config) { + function inBlock(style, terminator, returnTokenizer) { + return function(stream, state) { + while (!stream.eol()) { + if (stream.match(terminator)) { + state.tokenize = inText; + break; + } + stream.next(); + } + + if (returnTokenizer) state.tokenize = returnTokenizer; + + return style; + }; + } + + function inLine(style) { + return function(stream, state) { + while(!stream.eol()) { + stream.next(); + } + state.tokenize = inText; + return style; + }; + } + + function inText(stream, state) { + function chain(parser) { + state.tokenize = parser; + return parser(stream, state); + } + + var sol = stream.sol(); + var ch = stream.next(); + + //non start of line + switch (ch) { //switch is generally much faster than if, so it is used here + case "{": //plugin + stream.eat("/"); + stream.eatSpace(); + stream.eatWhile(/[^\s\u00a0=\"\'\/?(}]/); + state.tokenize = inPlugin; + return "tag"; + case "_": //bold + if (stream.eat("_")) + return chain(inBlock("strong", "__", inText)); + break; + case "'": //italics + if (stream.eat("'")) + return chain(inBlock("em", "''", inText)); + break; + case "(":// Wiki Link + if (stream.eat("(")) + return chain(inBlock("variable-2", "))", inText)); + break; + case "[":// Weblink + return chain(inBlock("variable-3", "]", inText)); + break; + case "|": //table + if (stream.eat("|")) + return chain(inBlock("comment", "||")); + break; + case "-": + if (stream.eat("=")) {//titleBar + return chain(inBlock("header string", "=-", inText)); + } else if (stream.eat("-")) {//deleted + return chain(inBlock("error tw-deleted", "--", inText)); + } + break; + case "=": //underline + if (stream.match("==")) + return chain(inBlock("tw-underline", "===", inText)); + break; + case ":": + if (stream.eat(":")) + return chain(inBlock("comment", "::")); + break; + case "^": //box + return chain(inBlock("tw-box", "^")); + break; + case "~": //np + if (stream.match("np~")) + return chain(inBlock("meta", "~/np~")); + break; + } + + //start of line types + if (sol) { + switch (ch) { + case "!": //header at start of line + if (stream.match('!!!!!')) { + return chain(inLine("header string")); + } else if (stream.match('!!!!')) { + return chain(inLine("header string")); + } else if (stream.match('!!!')) { + return chain(inLine("header string")); + } else if (stream.match('!!')) { + return chain(inLine("header string")); + } else { + return chain(inLine("header string")); + } + break; + case "*": //unordered list line item, or <li /> at start of line + case "#": //ordered list line item, or <li /> at start of line + case "+": //ordered list line item, or <li /> at start of line + return chain(inLine("tw-listitem bracket")); + break; + } + } + + //stream.eatWhile(/[&{]/); was eating up plugins, turned off to act less like html and more like tiki + return null; + } + + var indentUnit = config.indentUnit; + + // Return variables for tokenizers + var pluginName, type; + function inPlugin(stream, state) { + var ch = stream.next(); + var peek = stream.peek(); + + if (ch == "}") { + state.tokenize = inText; + //type = ch == ")" ? "endPlugin" : "selfclosePlugin"; inPlugin + return "tag"; + } else if (ch == "(" || ch == ")") { + return "bracket"; + } else if (ch == "=") { + type = "equals"; + + if (peek == ">") { + stream.next(); + peek = stream.peek(); + } + + //here we detect values directly after equal character with no quotes + if (!/[\'\"]/.test(peek)) { + state.tokenize = inAttributeNoQuote(); + } + //end detect values + + return "operator"; + } else if (/[\'\"]/.test(ch)) { + state.tokenize = inAttribute(ch); + return state.tokenize(stream, state); + } else { + stream.eatWhile(/[^\s\u00a0=\"\'\/?]/); + return "keyword"; + } + } + + function inAttribute(quote) { + return function(stream, state) { + while (!stream.eol()) { + if (stream.next() == quote) { + state.tokenize = inPlugin; + break; + } + } + return "string"; + }; + } + + function inAttributeNoQuote() { + return function(stream, state) { + while (!stream.eol()) { + var ch = stream.next(); + var peek = stream.peek(); + if (ch == " " || ch == "," || /[ )}]/.test(peek)) { + state.tokenize = inPlugin; + break; + } + } + return "string"; +}; + } + +var curState, setStyle; +function pass() { + for (var i = arguments.length - 1; i >= 0; i--) curState.cc.push(arguments[i]); +} + +function cont() { + pass.apply(null, arguments); + return true; +} + +function pushContext(pluginName, startOfLine) { + var noIndent = curState.context && curState.context.noIndent; + curState.context = { + prev: curState.context, + pluginName: pluginName, + indent: curState.indented, + startOfLine: startOfLine, + noIndent: noIndent + }; +} + +function popContext() { + if (curState.context) curState.context = curState.context.prev; +} + +function element(type) { + if (type == "openPlugin") {curState.pluginName = pluginName; return cont(attributes, endplugin(curState.startOfLine));} + else if (type == "closePlugin") { + var err = false; + if (curState.context) { + err = curState.context.pluginName != pluginName; + popContext(); + } else { + err = true; + } + if (err) setStyle = "error"; + return cont(endcloseplugin(err)); + } + else if (type == "string") { + if (!curState.context || curState.context.name != "!cdata") pushContext("!cdata"); + if (curState.tokenize == inText) popContext(); + return cont(); + } + else return cont(); +} + +function endplugin(startOfLine) { + return function(type) { + if ( + type == "selfclosePlugin" || + type == "endPlugin" + ) + return cont(); + if (type == "endPlugin") {pushContext(curState.pluginName, startOfLine); return cont();} + return cont(); + }; +} + +function endcloseplugin(err) { + return function(type) { + if (err) setStyle = "error"; + if (type == "endPlugin") return cont(); + return pass(); + }; +} + +function attributes(type) { + if (type == "keyword") {setStyle = "attribute"; return cont(attributes);} + if (type == "equals") return cont(attvalue, attributes); + return pass(); +} +function attvalue(type) { + if (type == "keyword") {setStyle = "string"; return cont();} + if (type == "string") return cont(attvaluemaybe); + return pass(); +} +function attvaluemaybe(type) { + if (type == "string") return cont(attvaluemaybe); + else return pass(); +} +return { + startState: function() { + return {tokenize: inText, cc: [], indented: 0, startOfLine: true, pluginName: null, context: null}; + }, + token: function(stream, state) { + if (stream.sol()) { + state.startOfLine = true; + state.indented = stream.indentation(); + } + if (stream.eatSpace()) return null; + + setStyle = type = pluginName = null; + var style = state.tokenize(stream, state); + if ((style || type) && style != "comment") { + curState = state; + while (true) { + var comb = state.cc.pop() || element; + if (comb(type || style)) break; + } + } + state.startOfLine = false; + return setStyle || style; + }, + indent: function(state, textAfter) { + var context = state.context; + if (context && context.noIndent) return 0; + if (context && /^{\//.test(textAfter)) + context = context.prev; + while (context && !context.startOfLine) + context = context.prev; + if (context) return context.indent + indentUnit; + else return 0; + }, + electricChars: "/" +}; +}); + +CodeMirror.defineMIME("text/tiki", "tiki"); + +}); diff --git a/modules/editor/codemirror/mode/verilog/test.min.js b/modules/editor/codemirror/mode/verilog/test.min.js @@ -0,0 +1,273 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function() { + var mode = CodeMirror.getMode({indentUnit: 4}, "verilog"); + function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } + + MT("binary_literals", + "[number 1'b0]", + "[number 1'b1]", + "[number 1'bx]", + "[number 1'bz]", + "[number 1'bX]", + "[number 1'bZ]", + "[number 1'B0]", + "[number 1'B1]", + "[number 1'Bx]", + "[number 1'Bz]", + "[number 1'BX]", + "[number 1'BZ]", + "[number 1'b0]", + "[number 1'b1]", + "[number 2'b01]", + "[number 2'bxz]", + "[number 2'b11]", + "[number 2'b10]", + "[number 2'b1Z]", + "[number 12'b0101_0101_0101]", + "[number 1'b 0]", + "[number 'b0101]" + ); + + MT("octal_literals", + "[number 3'o7]", + "[number 3'O7]", + "[number 3'so7]", + "[number 3'SO7]" + ); + + MT("decimal_literals", + "[number 0]", + "[number 1]", + "[number 7]", + "[number 123_456]", + "[number 'd33]", + "[number 8'd255]", + "[number 8'D255]", + "[number 8'sd255]", + "[number 8'SD255]", + "[number 32'd123]", + "[number 32 'd123]", + "[number 32 'd 123]" + ); + + MT("hex_literals", + "[number 4'h0]", + "[number 4'ha]", + "[number 4'hF]", + "[number 4'hx]", + "[number 4'hz]", + "[number 4'hX]", + "[number 4'hZ]", + "[number 32'hdc78]", + "[number 32'hDC78]", + "[number 32 'hDC78]", + "[number 32'h DC78]", + "[number 32 'h DC78]", + "[number 32'h44x7]", + "[number 32'hFFF?]" + ); + + MT("real_number_literals", + "[number 1.2]", + "[number 0.1]", + "[number 2394.26331]", + "[number 1.2E12]", + "[number 1.2e12]", + "[number 1.30e-2]", + "[number 0.1e-0]", + "[number 23E10]", + "[number 29E-2]", + "[number 236.123_763_e-12]" + ); + + MT("operators", + "[meta ^]" + ); + + MT("keywords", + "[keyword logic]", + "[keyword logic] [variable foo]", + "[keyword reg] [variable abc]" + ); + + MT("variables", + "[variable _leading_underscore]", + "[variable _if]", + "[number 12] [variable foo]", + "[variable foo] [number 14]" + ); + + MT("tick_defines", + "[def `FOO]", + "[def `foo]", + "[def `FOO_bar]" + ); + + MT("system_calls", + "[meta $display]", + "[meta $vpi_printf]" + ); + + MT("line_comment", "[comment // Hello world]"); + + // Alignment tests + MT("align_port_map_style1", + /** + * mod mod(.a(a), + * .b(b) + * ); + */ + "[variable mod] [variable mod][bracket (].[variable a][bracket (][variable a][bracket )],", + " .[variable b][bracket (][variable b][bracket )]", + " [bracket )];", + "" + ); + + MT("align_port_map_style2", + /** + * mod mod( + * .a(a), + * .b(b) + * ); + */ + "[variable mod] [variable mod][bracket (]", + " .[variable a][bracket (][variable a][bracket )],", + " .[variable b][bracket (][variable b][bracket )]", + "[bracket )];", + "" + ); + + // Indentation tests + MT("indent_single_statement_if", + "[keyword if] [bracket (][variable foo][bracket )]", + " [keyword break];", + "" + ); + + MT("no_indent_after_single_line_if", + "[keyword if] [bracket (][variable foo][bracket )] [keyword break];", + "" + ); + + MT("indent_after_if_begin_same_line", + "[keyword if] [bracket (][variable foo][bracket )] [keyword begin]", + " [keyword break];", + " [keyword break];", + "[keyword end]", + "" + ); + + MT("indent_after_if_begin_next_line", + "[keyword if] [bracket (][variable foo][bracket )]", + " [keyword begin]", + " [keyword break];", + " [keyword break];", + " [keyword end]", + "" + ); + + MT("indent_single_statement_if_else", + "[keyword if] [bracket (][variable foo][bracket )]", + " [keyword break];", + "[keyword else]", + " [keyword break];", + "" + ); + + MT("indent_if_else_begin_same_line", + "[keyword if] [bracket (][variable foo][bracket )] [keyword begin]", + " [keyword break];", + " [keyword break];", + "[keyword end] [keyword else] [keyword begin]", + " [keyword break];", + " [keyword break];", + "[keyword end]", + "" + ); + + MT("indent_if_else_begin_next_line", + "[keyword if] [bracket (][variable foo][bracket )]", + " [keyword begin]", + " [keyword break];", + " [keyword break];", + " [keyword end]", + "[keyword else]", + " [keyword begin]", + " [keyword break];", + " [keyword break];", + " [keyword end]", + "" + ); + + MT("indent_if_nested_without_begin", + "[keyword if] [bracket (][variable foo][bracket )]", + " [keyword if] [bracket (][variable foo][bracket )]", + " [keyword if] [bracket (][variable foo][bracket )]", + " [keyword break];", + "" + ); + + MT("indent_case", + "[keyword case] [bracket (][variable state][bracket )]", + " [variable FOO]:", + " [keyword break];", + " [variable BAR]:", + " [keyword break];", + "[keyword endcase]", + "" + ); + + MT("unindent_after_end_with_preceding_text", + "[keyword begin]", + " [keyword break]; [keyword end]", + "" + ); + + MT("export_function_one_line_does_not_indent", + "[keyword export] [string \"DPI-C\"] [keyword function] [variable helloFromSV];", + "" + ); + + MT("export_task_one_line_does_not_indent", + "[keyword export] [string \"DPI-C\"] [keyword task] [variable helloFromSV];", + "" + ); + + MT("export_function_two_lines_indents_properly", + "[keyword export]", + " [string \"DPI-C\"] [keyword function] [variable helloFromSV];", + "" + ); + + MT("export_task_two_lines_indents_properly", + "[keyword export]", + " [string \"DPI-C\"] [keyword task] [variable helloFromSV];", + "" + ); + + MT("import_function_one_line_does_not_indent", + "[keyword import] [string \"DPI-C\"] [keyword function] [variable helloFromC];", + "" + ); + + MT("import_task_one_line_does_not_indent", + "[keyword import] [string \"DPI-C\"] [keyword task] [variable helloFromC];", + "" + ); + + MT("import_package_single_line_does_not_indent", + "[keyword import] [variable p]::[variable x];", + "[keyword import] [variable p]::[variable y];", + "" + ); + + MT("covergroup_with_function_indents_properly", + "[keyword covergroup] [variable cg] [keyword with] [keyword function] [variable sample][bracket (][keyword bit] [variable b][bracket )];", + " [variable c] : [keyword coverpoint] [variable c];", + "[keyword endgroup]: [variable cg]", + "" + ); + +})(); diff --git a/modules/editor/codemirror/mode/vhdl/vhdl.min.js b/modules/editor/codemirror/mode/vhdl/vhdl.min.js @@ -0,0 +1,189 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// Originally written by Alf Nielsen, re-written by Michael Zhou +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +function words(str) { + var obj = {}, words = str.split(","); + for (var i = 0; i < words.length; ++i) { + var allCaps = words[i].toUpperCase(); + var firstCap = words[i].charAt(0).toUpperCase() + words[i].slice(1); + obj[words[i]] = true; + obj[allCaps] = true; + obj[firstCap] = true; + } + return obj; +} + +function metaHook(stream) { + stream.eatWhile(/[\w\$_]/); + return "meta"; +} + +CodeMirror.defineMode("vhdl", function(config, parserConfig) { + var indentUnit = config.indentUnit, + atoms = parserConfig.atoms || words("null"), + hooks = parserConfig.hooks || {"`": metaHook, "$": metaHook}, + multiLineStrings = parserConfig.multiLineStrings; + + var keywords = words("abs,access,after,alias,all,and,architecture,array,assert,attribute,begin,block," + + "body,buffer,bus,case,component,configuration,constant,disconnect,downto,else,elsif,end,end block,end case," + + "end component,end for,end generate,end if,end loop,end process,end record,end units,entity,exit,file,for," + + "function,generate,generic,generic map,group,guarded,if,impure,in,inertial,inout,is,label,library,linkage," + + "literal,loop,map,mod,nand,new,next,nor,null,of,on,open,or,others,out,package,package body,port,port map," + + "postponed,procedure,process,pure,range,record,register,reject,rem,report,return,rol,ror,select,severity,signal," + + "sla,sll,sra,srl,subtype,then,to,transport,type,unaffected,units,until,use,variable,wait,when,while,with,xnor,xor"); + + var blockKeywords = words("architecture,entity,begin,case,port,else,elsif,end,for,function,if"); + + var isOperatorChar = /[&|~><!\)\(*#%@+\/=?\:;}{,\.\^\-\[\]]/; + var curPunc; + + function tokenBase(stream, state) { + var ch = stream.next(); + if (hooks[ch]) { + var result = hooks[ch](stream, state); + if (result !== false) return result; + } + if (ch == '"') { + state.tokenize = tokenString2(ch); + return state.tokenize(stream, state); + } + if (ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } + if (/[\[\]{}\(\),;\:\.]/.test(ch)) { + curPunc = ch; + return null; + } + if (/[\d']/.test(ch)) { + stream.eatWhile(/[\w\.']/); + return "number"; + } + if (ch == "-") { + if (stream.eat("-")) { + stream.skipToEnd(); + return "comment"; + } + } + if (isOperatorChar.test(ch)) { + stream.eatWhile(isOperatorChar); + return "operator"; + } + stream.eatWhile(/[\w\$_]/); + var cur = stream.current(); + if (keywords.propertyIsEnumerable(cur.toLowerCase())) { + if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement"; + return "keyword"; + } + if (atoms.propertyIsEnumerable(cur)) return "atom"; + return "variable"; + } + + function tokenString(quote) { + return function(stream, state) { + var escaped = false, next, end = false; + while ((next = stream.next()) != null) { + if (next == quote && !escaped) {end = true; break;} + escaped = !escaped && next == "--"; + } + if (end || !(escaped || multiLineStrings)) + state.tokenize = tokenBase; + return "string"; + }; + } + function tokenString2(quote) { + return function(stream, state) { + var escaped = false, next, end = false; + while ((next = stream.next()) != null) { + if (next == quote && !escaped) {end = true; break;} + escaped = !escaped && next == "--"; + } + if (end || !(escaped || multiLineStrings)) + state.tokenize = tokenBase; + return "string-2"; + }; + } + + function Context(indented, column, type, align, prev) { + this.indented = indented; + this.column = column; + this.type = type; + this.align = align; + this.prev = prev; + } + function pushContext(state, col, type) { + return state.context = new Context(state.indented, col, type, null, state.context); + } + function popContext(state) { + var t = state.context.type; + if (t == ")" || t == "]" || t == "}") + state.indented = state.context.indented; + return state.context = state.context.prev; + } + + // Interface + return { + startState: function(basecolumn) { + return { + tokenize: null, + context: new Context((basecolumn || 0) - indentUnit, 0, "top", false), + indented: 0, + startOfLine: true + }; + }, + + token: function(stream, state) { + var ctx = state.context; + if (stream.sol()) { + if (ctx.align == null) ctx.align = false; + state.indented = stream.indentation(); + state.startOfLine = true; + } + if (stream.eatSpace()) return null; + curPunc = null; + var style = (state.tokenize || tokenBase)(stream, state); + if (style == "comment" || style == "meta") return style; + if (ctx.align == null) ctx.align = true; + + if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state); + else if (curPunc == "{") pushContext(state, stream.column(), "}"); + else if (curPunc == "[") pushContext(state, stream.column(), "]"); + else if (curPunc == "(") pushContext(state, stream.column(), ")"); + else if (curPunc == "}") { + while (ctx.type == "statement") ctx = popContext(state); + if (ctx.type == "}") ctx = popContext(state); + while (ctx.type == "statement") ctx = popContext(state); + } + else if (curPunc == ctx.type) popContext(state); + else if (ctx.type == "}" || ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement")) + pushContext(state, stream.column(), "statement"); + state.startOfLine = false; + return style; + }, + + indent: function(state, textAfter) { + if (state.tokenize != tokenBase && state.tokenize != null) return 0; + var firstChar = textAfter && textAfter.charAt(0), ctx = state.context, closing = firstChar == ctx.type; + if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : indentUnit); + else if (ctx.align) return ctx.column + (closing ? 0 : 1); + else return ctx.indented + (closing ? 0 : indentUnit); + }, + + electricChars: "{}" + }; +}); + +CodeMirror.defineMIME("text/x-vhdl", "vhdl"); + +}); diff --git a/modules/editor/codemirror/mode/yacas/yacas.min.js b/modules/editor/codemirror/mode/yacas/yacas.min.js @@ -0,0 +1,204 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// Yacas mode copyright (c) 2015 by Grzegorz Mazur +// Loosely based on mathematica mode by Calin Barbat + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode('yacas', function(_config, _parserConfig) { + + function words(str) { + var obj = {}, words = str.split(" "); + for (var i = 0; i < words.length; ++i) obj[words[i]] = true; + return obj; + } + + var bodiedOps = words("Assert BackQuote D Defun Deriv For ForEach FromFile " + + "FromString Function Integrate InverseTaylor Limit " + + "LocalSymbols Macro MacroRule MacroRulePattern " + + "NIntegrate Rule RulePattern Subst TD TExplicitSum " + + "TSum Taylor Taylor1 Taylor2 Taylor3 ToFile " + + "ToStdout ToString TraceRule Until While"); + + // patterns + var pFloatForm = "(?:(?:\\.\\d+|\\d+\\.\\d*|\\d+)(?:[eE][+-]?\\d+)?)"; + var pIdentifier = "(?:[a-zA-Z\\$'][a-zA-Z0-9\\$']*)"; + + // regular expressions + var reFloatForm = new RegExp(pFloatForm); + var reIdentifier = new RegExp(pIdentifier); + var rePattern = new RegExp(pIdentifier + "?_" + pIdentifier); + var reFunctionLike = new RegExp(pIdentifier + "\\s*\\("); + + function tokenBase(stream, state) { + var ch; + + // get next character + ch = stream.next(); + + // string + if (ch === '"') { + state.tokenize = tokenString; + return state.tokenize(stream, state); + } + + // comment + if (ch === '/') { + if (stream.eat('*')) { + state.tokenize = tokenComment; + return state.tokenize(stream, state); + } + if (stream.eat("/")) { + stream.skipToEnd(); + return "comment"; + } + } + + // go back one character + stream.backUp(1); + + // update scope info + var m = stream.match(/^(\w+)\s*\(/, false); + if (m !== null && bodiedOps.hasOwnProperty(m[1])) + state.scopes.push('bodied'); + + var scope = currentScope(state); + + if (scope === 'bodied' && ch === '[') + state.scopes.pop(); + + if (ch === '[' || ch === '{' || ch === '(') + state.scopes.push(ch); + + scope = currentScope(state); + + if (scope === '[' && ch === ']' || + scope === '{' && ch === '}' || + scope === '(' && ch === ')') + state.scopes.pop(); + + if (ch === ';') { + while (scope === 'bodied') { + state.scopes.pop(); + scope = currentScope(state); + } + } + + // look for ordered rules + if (stream.match(/\d+ *#/, true, false)) { + return 'qualifier'; + } + + // look for numbers + if (stream.match(reFloatForm, true, false)) { + return 'number'; + } + + // look for placeholders + if (stream.match(rePattern, true, false)) { + return 'variable-3'; + } + + // match all braces separately + if (stream.match(/(?:\[|\]|{|}|\(|\))/, true, false)) { + return 'bracket'; + } + + // literals looking like function calls + if (stream.match(reFunctionLike, true, false)) { + stream.backUp(1); + return 'variable'; + } + + // all other identifiers + if (stream.match(reIdentifier, true, false)) { + return 'variable-2'; + } + + // operators; note that operators like @@ or /; are matched separately for each symbol. + if (stream.match(/(?:\\|\+|\-|\*|\/|,|;|\.|:|@|~|=|>|<|&|\||_|`|'|\^|\?|!|%|#)/, true, false)) { + return 'operator'; + } + + // everything else is an error + return 'error'; + } + + function tokenString(stream, state) { + var next, end = false, escaped = false; + while ((next = stream.next()) != null) { + if (next === '"' && !escaped) { + end = true; + break; + } + escaped = !escaped && next === '\\'; + } + if (end && !escaped) { + state.tokenize = tokenBase; + } + return 'string'; + }; + + function tokenComment(stream, state) { + var prev, next; + while((next = stream.next()) != null) { + if (prev === '*' && next === '/') { + state.tokenize = tokenBase; + break; + } + prev = next; + } + return 'comment'; + } + + function currentScope(state) { + var scope = null; + if (state.scopes.length > 0) + scope = state.scopes[state.scopes.length - 1]; + return scope; + } + + return { + startState: function() { + return { + tokenize: tokenBase, + scopes: [] + }; + }, + token: function(stream, state) { + if (stream.eatSpace()) return null; + return state.tokenize(stream, state); + }, + indent: function(state, textAfter) { + if (state.tokenize !== tokenBase && state.tokenize !== null) + return CodeMirror.Pass; + + var delta = 0; + if (textAfter === ']' || textAfter === '];' || + textAfter === '}' || textAfter === '};' || + textAfter === ');') + delta = -1; + + return (state.scopes.length + delta) * _config.indentUnit; + }, + electricChars: "{}[]();", + blockCommentStart: "/*", + blockCommentEnd: "*/", + lineComment: "//" + }; +}); + +CodeMirror.defineMIME('text/x-yacas', { + name: 'yacas' +}); + +}); diff --git a/modules/editor/codemirror/modes.txt b/modules/editor/codemirror/modes.txt @@ -0,0 +1,152 @@ +mode/handlebars/handlebars.js +mode/smalltalk/smalltalk.js +mode/php/test.js +mode/php/php.js +mode/cobol/cobol.js +mode/haskell/haskell.js +mode/mathematica/mathematica.js +mode/pug/pug.js +mode/livescript/livescript.js +mode/yaml-frontmatter/yaml-frontmatter.js +mode/stylus/stylus.js +mode/markdown/test.js +mode/markdown/markdown.js +mode/jsx/test.js +mode/jsx/jsx.js +mode/velocity/velocity.js +mode/fortran/fortran.js +mode/mirc/mirc.js +mode/xquery/xquery.js +mode/xquery/test.js +mode/elm/elm.js +mode/vhdl/vhdl.js +mode/verilog/test.js +mode/verilog/verilog.js +mode/spreadsheet/spreadsheet.js +mode/coffeescript/coffeescript.js +mode/tiddlywiki/tiddlywiki.js +mode/mumps/mumps.js +mode/eiffel/eiffel.js +mode/webidl/webidl.js +mode/ebnf/ebnf.js +mode/http/http.js +mode/textile/textile.js +mode/textile/test.js +mode/r/r.js +mode/haml/haml.js +mode/haml/test.js +mode/ecl/ecl.js +mode/cypher/test.js +mode/cypher/cypher.js +mode/sieve/sieve.js +mode/soy/test.js +mode/soy/soy.js +mode/pig/pig.js +mode/apl/apl.js +mode/crystal/crystal.js +mode/clike/test.js +mode/clike/clike.js +mode/oz/oz.js +mode/modelica/modelica.js +mode/gherkin/gherkin.js +mode/swift/test.js +mode/swift/swift.js +mode/scheme/scheme.js +mode/idl/idl.js +mode/yaml/yaml.js +mode/vue/vue.js +mode/twig/twig.js +mode/cmake/cmake.js +mode/asciiarmor/asciiarmor.js +mode/pegjs/pegjs.js +mode/solr/solr.js +mode/tiki/tiki.js +mode/slim/test.js +mode/slim/slim.js +mode/puppet/puppet.js +mode/meta.js +mode/go/go.js +mode/commonlisp/commonlisp.js +mode/rust/test.js +mode/rust/rust.js +mode/powershell/test.js +mode/powershell/powershell.js +mode/stex/stex.js +mode/stex/test.js +mode/q/q.js +mode/htmlembedded/htmlembedded.js +mode/d/test.js +mode/d/d.js +mode/protobuf/protobuf.js +mode/mscgen/msgenny_test.js +mode/mscgen/mscgen_test.js +mode/mscgen/mscgen.js +mode/mscgen/xu_test.js +mode/django/django.js +mode/toml/toml.js +mode/yacas/yacas.js +mode/dockerfile/dockerfile.js +mode/python/python.js +mode/python/test.js +mode/vb/vb.js +mode/octave/octave.js +mode/tcl/tcl.js +mode/clojure/clojure.js +mode/sass/test.js +mode/sass/sass.js +mode/gas/gas.js +mode/sas/sas.js +mode/julia/julia.js +mode/fcl/fcl.js +mode/tornado/tornado.js +mode/asterisk/asterisk.js +mode/sql/sql.js +mode/gfm/test.js +mode/gfm/gfm.js +mode/mllike/mllike.js +mode/rst/rst.js +mode/ntriples/ntriples.js +mode/sparql/sparql.js +mode/properties/properties.js +mode/rpm/rpm.js +mode/htmlmixed/htmlmixed.js +mode/xml/test.js +mode/xml/xml.js +mode/ttcn-cfg/ttcn-cfg.js +mode/ttcn/ttcn.js +mode/z80/z80.js +mode/brainfuck/brainfuck.js +mode/forth/forth.js +mode/nginx/nginx.js +mode/javascript/javascript.js +mode/javascript/test.js +mode/pascal/pascal.js +mode/haxe/haxe.js +mode/perl/perl.js +mode/factor/factor.js +mode/smarty/smarty.js +mode/vbscript/vbscript.js +mode/dylan/test.js +mode/dylan/dylan.js +mode/asn.1/asn.1.js +mode/ruby/test.js +mode/ruby/ruby.js +mode/nsis/nsis.js +mode/css/css.js +mode/css/test.js +mode/css/less_test.js +mode/css/gss_test.js +mode/css/scss_test.js +mode/haskell-literate/haskell-literate.js +mode/mbox/mbox.js +mode/dtd/dtd.js +mode/erlang/erlang.js +mode/turtle/turtle.js +mode/troff/troff.js +mode/jinja2/jinja2.js +mode/diff/diff.js +mode/dart/dart.js +mode/shell/test.js +mode/shell/shell.js +mode/lua/lua.js +mode/groovy/groovy.js diff --git a/modules/editor/codemirror/package.json b/modules/editor/codemirror/package.json @@ -0,0 +1,49 @@ +{ + "name": "codemirror", + "version": "5.32.0", + "main": "lib/codemirror.js", + "style": "lib/codemirror.css", + "description": "Full-featured in-browser code editor", + "license": "MIT", + "directories": { + "lib": "./lib" + }, + "scripts": { + "build": "rollup -c", + "watch": "rollup -w -c", + "prepare": "npm run-script build", + "test": "node ./test/run.js", + "lint": "bin/lint" + }, + "devDependencies": { + "blint": "^1", + "node-static": "0.6.0", + "phantomjs-prebuilt": "^2.1.12", + "rollup": "^0.41.0", + "rollup-plugin-buble": "^0.15.0", + "rollup-watch": "^3.2.0" + }, + "bugs": "http://github.com/codemirror/CodeMirror/issues", + "keywords": [ + "JavaScript", + "CodeMirror", + "Editor" + ], + "homepage": "http://codemirror.net", + "maintainers": [ + { + "name": "Marijn Haverbeke", + "email": "marijnh@gmail.com", + "web": "http://marijnhaverbeke.nl" + } + ], + "repository": { + "type": "git", + "url": "https://github.com/codemirror/CodeMirror.git" + }, + "jspm": { + "directories": {}, + "dependencies": {}, + "devDependencies": {} + } +} diff --git a/modules/editor/codemirror/src/display/gutters.js b/modules/editor/codemirror/src/display/gutters.js @@ -0,0 +1,34 @@ +import { elt, removeChildren } from "../util/dom.js" +import { indexOf } from "../util/misc.js" + +import { updateGutterSpace } from "./update_display.js" + +// Rebuild the gutter elements, ensure the margin to the left of the +// code matches their width. +export function updateGutters(cm) { + let gutters = cm.display.gutters, specs = cm.options.gutters + removeChildren(gutters) + let i = 0 + for (; i < specs.length; ++i) { + let gutterClass = specs[i] + let gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass)) + if (gutterClass == "CodeMirror-linenumbers") { + cm.display.lineGutter = gElt + gElt.style.width = (cm.display.lineNumWidth || 1) + "px" + } + } + gutters.style.display = i ? "" : "none" + updateGutterSpace(cm) +} + +// Make sure the gutters options contains the element +// "CodeMirror-linenumbers" when the lineNumbers option is true. +export function setGuttersForLineNumbers(options) { + let 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) + } +} diff --git a/modules/editor/codemirror/src/display/mode_state.js b/modules/editor/codemirror/src/display/mode_state.js @@ -0,0 +1,22 @@ +import { getMode } from "../modes.js" + +import { startWorker } from "./highlight_worker.js" +import { regChange } from "./view_tracking.js" + +// Used to get the editor into a consistent state again when options change. + +export function loadMode(cm) { + cm.doc.mode = getMode(cm.options, cm.doc.modeOption) + resetModeState(cm) +} + +export function resetModeState(cm) { + cm.doc.iter(line => { + if (line.stateAfter) line.stateAfter = null + if (line.styles) line.styles = null + }) + cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first + startWorker(cm, 100) + cm.state.modeGen++ + if (cm.curOp) regChange(cm) +} diff --git a/modules/editor/codemirror/src/display/operations.min.js b/modules/editor/codemirror/src/display/operations.min.js @@ -0,0 +1,205 @@ +import { clipPos } from "../line/pos.js" +import { findMaxLine } from "../line/spans.js" +import { displayWidth, measureChar, scrollGap } from "../measurement/position_measurement.js" +import { signal } from "../util/event.js" +import { activeElt } from "../util/dom.js" +import { finishOperation, pushOperation } from "../util/operation_group.js" + +import { ensureFocus } from "./focus.js" +import { measureForScrollbars, updateScrollbars } from "./scrollbars.js" +import { restartBlink } from "./selection.js" +import { maybeScrollWindow, scrollPosIntoView, setScrollLeft, setScrollTop } from "./scrolling.js" +import { DisplayUpdate, maybeClipScrollbars, postUpdateDisplay, setDocumentHeight, updateDisplayIfNeeded } from "./update_display.js" +import { updateHeightsInViewport } from "./update_lines.js" + +// Operations are used to wrap a series of changes to the editor +// state in such a way that each change won't have to update the +// cursor and display (which would be awkward, slow, and +// error-prone). Instead, display updates are batched and then all +// combined and executed at once. + +let nextOpId = 0 +// Start a new operation. +export function startOperation(cm) { + cm.curOp = { + cm: cm, + viewChanged: false, // Flag that indicates that lines might need to be redrawn + startHeight: cm.doc.height, // Used to detect need to update scrollbar + forceUpdate: false, // Used to force a redraw + updateInput: null, // Whether to reset the input textarea + typing: false, // Whether this reset should be careful to leave existing text (for compositing) + changeObjs: null, // Accumulated changes, for firing change events + cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on + cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already + selectionChanged: false, // Whether the selection needs to be redrawn + updateMaxLine: false, // Set when the widest line needs to be determined anew + scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet + scrollToPos: null, // Used to scroll to a specific position + focus: false, + id: ++nextOpId // Unique ID + } + pushOperation(cm.curOp) +} + +// Finish an operation, updating the display and signalling delayed events +export function endOperation(cm) { + let op = cm.curOp + finishOperation(op, group => { + for (let i = 0; i < group.ops.length; i++) + group.ops[i].cm.curOp = null + endOperations(group) + }) +} + +// The DOM updates done when an operation finishes are batched so +// that the minimum number of relayouts are required. +function endOperations(group) { + let ops = group.ops + for (let i = 0; i < ops.length; i++) // Read DOM + endOperation_R1(ops[i]) + for (let i = 0; i < ops.length; i++) // Write DOM (maybe) + endOperation_W1(ops[i]) + for (let i = 0; i < ops.length; i++) // Read DOM + endOperation_R2(ops[i]) + for (let i = 0; i < ops.length; i++) // Write DOM (maybe) + endOperation_W2(ops[i]) + for (let i = 0; i < ops.length; i++) // Read DOM + endOperation_finish(ops[i]) +} + +function endOperation_R1(op) { + let cm = op.cm, display = cm.display + maybeClipScrollbars(cm) + if (op.updateMaxLine) findMaxLine(cm) + + op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || + op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || + op.scrollToPos.to.line >= display.viewTo) || + display.maxLineChanged && cm.options.lineWrapping + op.update = op.mustUpdate && + new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate) +} + +function endOperation_W1(op) { + op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update) +} + +function endOperation_R2(op) { + let cm = op.cm, display = cm.display + if (op.updatedDisplay) updateHeightsInViewport(cm) + + op.barMeasure = measureForScrollbars(cm) + + // If the max line changed since it was last measured, measure it, + // and ensure the document's width matches it. + // updateDisplay_W2 will use these properties to do the actual resizing + if (display.maxLineChanged && !cm.options.lineWrapping) { + op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3 + cm.display.sizerWidth = op.adjustWidthTo + op.barMeasure.scrollWidth = + Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth) + op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)) + } + + if (op.updatedDisplay || op.selectionChanged) + op.preparedSelection = display.input.prepareSelection() +} + +function endOperation_W2(op) { + let cm = op.cm + + if (op.adjustWidthTo != null) { + cm.display.sizer.style.minWidth = op.adjustWidthTo + "px" + if (op.maxScrollLeft < cm.doc.scrollLeft) + setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true) + cm.display.maxLineChanged = false + } + + let takeFocus = op.focus && op.focus == activeElt() + if (op.preparedSelection) + cm.display.input.showSelection(op.preparedSelection, takeFocus) + if (op.updatedDisplay || op.startHeight != cm.doc.height) + updateScrollbars(cm, op.barMeasure) + if (op.updatedDisplay) + setDocumentHeight(cm, op.barMeasure) + + if (op.selectionChanged) restartBlink(cm) + + if (cm.state.focused && op.updateInput) + cm.display.input.reset(op.typing) + if (takeFocus) ensureFocus(op.cm) +} + +function endOperation_finish(op) { + let cm = op.cm, display = cm.display, doc = cm.doc + + if (op.updatedDisplay) postUpdateDisplay(cm, op.update) + + // Abort mouse wheel delta measurement, when scrolling explicitly + if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) + display.wheelStartX = display.wheelStartY = null + + // Propagate the scroll position to the actual DOM scroller + if (op.scrollTop != null) setScrollTop(cm, op.scrollTop, op.forceScroll) + + if (op.scrollLeft != null) setScrollLeft(cm, op.scrollLeft, true, true) + // If we need to scroll a specific position into view, do so. + if (op.scrollToPos) { + let rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), + clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin) + maybeScrollWindow(cm, rect) + } + + // Fire events for markers that are hidden/unidden by editing or + // undoing + let hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers + if (hidden) for (let i = 0; i < hidden.length; ++i) + if (!hidden[i].lines.length) signal(hidden[i], "hide") + if (unhidden) for (let i = 0; i < unhidden.length; ++i) + if (unhidden[i].lines.length) signal(unhidden[i], "unhide") + + if (display.wrapper.offsetHeight) + doc.scrollTop = cm.display.scroller.scrollTop + + // Fire change events, and delayed event handlers + if (op.changeObjs) + signal(cm, "changes", cm, op.changeObjs) + if (op.update) + op.update.finish() +} + +// Run the given function in an operation +export function runInOp(cm, f) { + if (cm.curOp) return f() + startOperation(cm) + try { return f() } + finally { endOperation(cm) } +} +// Wraps a function in an operation. Returns the wrapped function. +export function operation(cm, f) { + return function() { + if (cm.curOp) return f.apply(cm, arguments) + startOperation(cm) + try { return f.apply(cm, arguments) } + finally { endOperation(cm) } + } +} +// Used to add methods to editor and doc instances, wrapping them in +// operations. +export function methodOp(f) { + return function() { + if (this.curOp) return f.apply(this, arguments) + startOperation(this) + try { return f.apply(this, arguments) } + finally { endOperation(this) } + } +} +export function docMethodOp(f) { + return function() { + let cm = this.cm + if (!cm || cm.curOp) return f.apply(this, arguments) + startOperation(cm) + try { return f.apply(this, arguments) } + finally { endOperation(cm) } + } +} diff --git a/modules/editor/codemirror/src/display/scrollbars.min.js b/modules/editor/codemirror/src/display/scrollbars.min.js @@ -0,0 +1,192 @@ +import { addClass, elt, rmClass } from "../util/dom.js" +import { on } from "../util/event.js" +import { scrollGap, paddingVert } from "../measurement/position_measurement.js" +import { ie, ie_version, mac, mac_geMountainLion } from "../util/browser.js" +import { updateHeightsInViewport } from "./update_lines.js" +import { Delayed } from "../util/misc.js" + +import { setScrollLeft, updateScrollTop } from "./scrolling.js" + +// SCROLLBARS + +// Prepare DOM reads needed to update the scrollbars. Done in one +// shot to minimize update/measure roundtrips. +export function measureForScrollbars(cm) { + let d = cm.display, gutterW = d.gutters.offsetWidth + let 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 + } +} + +class NativeScrollbars { + constructor(place, scroll, cm) { + this.cm = cm + let vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar") + let horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar") + place(vert); place(horiz) + + on(vert, "scroll", () => { + if (vert.clientHeight) scroll(vert.scrollTop, "vertical") + }) + on(horiz, "scroll", () => { + if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal") + }) + + this.checkedZeroWidth = false + // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). + if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px" + } + + update(measure) { + let needsH = measure.scrollWidth > measure.clientWidth + 1 + let needsV = measure.scrollHeight > measure.clientHeight + 1 + let sWidth = measure.nativeBarWidth + + if (needsV) { + this.vert.style.display = "block" + this.vert.style.bottom = needsH ? sWidth + "px" : "0" + let totalHeight = measure.viewHeight - (needsH ? sWidth : 0) + // A bug in IE8 can cause this value to be negative, so guard it. + this.vert.firstChild.style.height = + Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px" + } else { + this.vert.style.display = "" + this.vert.firstChild.style.height = "0" + } + + if (needsH) { + this.horiz.style.display = "block" + this.horiz.style.right = needsV ? sWidth + "px" : "0" + this.horiz.style.left = measure.barLeft + "px" + let totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0) + this.horiz.firstChild.style.width = + Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px" + } else { + this.horiz.style.display = "" + this.horiz.firstChild.style.width = "0" + } + + if (!this.checkedZeroWidth && measure.clientHeight > 0) { + if (sWidth == 0) this.zeroWidthHack() + this.checkedZeroWidth = true + } + + return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0} + } + + setScrollLeft(pos) { + if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos + if (this.disableHoriz) this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz") + } + + setScrollTop(pos) { + if (this.vert.scrollTop != pos) this.vert.scrollTop = pos + if (this.disableVert) this.enableZeroWidthBar(this.vert, this.disableVert, "vert") + } + + zeroWidthHack() { + let 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(bar, delay, type) { + bar.style.pointerEvents = "auto" + function maybeDisable() { + // To find out whether the scrollbar is still visible, we + // check whether the element under the pixel in the bottom + // right corner of the scrollbar box is the scrollbar box + // itself (when the bar is still visible) or its filler child + // (when the bar is hidden). If it is still visible, we keep + // it enabled, if it's hidden, we disable pointer events. + let box = bar.getBoundingClientRect() + let elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2) + : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1) + if (elt != bar) bar.style.pointerEvents = "none" + else delay.set(1000, maybeDisable) + } + delay.set(1000, maybeDisable) + } + + clear() { + let parent = this.horiz.parentNode + parent.removeChild(this.horiz) + parent.removeChild(this.vert) + } +} + +class NullScrollbars { + update() { return {bottom: 0, right: 0} } + setScrollLeft() {} + setScrollTop() {} + clear() {} +} + +export function updateScrollbars(cm, measure) { + if (!measure) measure = measureForScrollbars(cm) + let startWidth = cm.display.barWidth, startHeight = cm.display.barHeight + updateScrollbarsInner(cm, measure) + for (let i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) { + if (startWidth != cm.display.barWidth && cm.options.lineWrapping) + updateHeightsInViewport(cm) + updateScrollbarsInner(cm, measureForScrollbars(cm)) + startWidth = cm.display.barWidth; startHeight = cm.display.barHeight + } +} + +// Re-synchronize the fake scrollbars with the actual size of the +// content. +function updateScrollbarsInner(cm, measure) { + let d = cm.display + let 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 = "" +} + +export let scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars} + +export function initScrollbars(cm) { + if (cm.display.scrollbars) { + cm.display.scrollbars.clear() + if (cm.display.scrollbars.addClass) + rmClass(cm.display.wrapper, cm.display.scrollbars.addClass) + } + + cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](node => { + cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller) + // Prevent clicks in the scrollbars from killing focus + on(node, "mousedown", () => { + if (cm.state.focused) setTimeout(() => cm.display.input.focus(), 0) + }) + node.setAttribute("cm-not-content", "true") + }, (pos, axis) => { + if (axis == "horizontal") setScrollLeft(cm, pos) + else updateScrollTop(cm, pos) + }, cm) + if (cm.display.scrollbars.addClass) + addClass(cm.display.wrapper, cm.display.scrollbars.addClass) +} diff --git a/modules/editor/codemirror/src/display/scrolling.js b/modules/editor/codemirror/src/display/scrolling.js @@ -0,0 +1,184 @@ +import { Pos } from "../line/pos.js" +import { cursorCoords, displayHeight, displayWidth, estimateCoords, paddingTop, paddingVert, scrollGap, textHeight } from "../measurement/position_measurement.js" +import { gecko, phantom } from "../util/browser.js" +import { elt } from "../util/dom.js" +import { signalDOMEvent } from "../util/event.js" + +import { startWorker } from "./highlight_worker.js" +import { alignHorizontally } from "./line_numbers.js" +import { updateDisplaySimple } from "./update_display.js" + +// SCROLLING THINGS INTO VIEW + +// If an editor sits on the top or bottom of the window, partially +// scrolled out of view, this ensures that the cursor is visible. +export function maybeScrollWindow(cm, rect) { + if (signalDOMEvent(cm, "scrollCursorIntoView")) return + + let display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null + if (rect.top + box.top < 0) doScroll = true + else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false + if (doScroll != null && !phantom) { + let scrollNode = elt("div", "\u200b", null, `position: absolute; + top: ${rect.top - display.viewOffset - paddingTop(cm.display)}px; + height: ${rect.bottom - rect.top + scrollGap(cm) + display.barHeight}px; + left: ${rect.left}px; width: ${Math.max(2, rect.right - rect.left)}px;`) + cm.display.lineSpace.appendChild(scrollNode) + scrollNode.scrollIntoView(doScroll) + cm.display.lineSpace.removeChild(scrollNode) + } +} + +// Scroll a given position into view (immediately), verifying that +// it actually became visible (as line heights are accurately +// measured, the position of something may 'drift' during drawing). +export function scrollPosIntoView(cm, pos, end, margin) { + if (margin == null) margin = 0 + let rect + if (!cm.options.lineWrapping && pos == end) { + // Set pos and end to the cursor positions around the character pos sticks to + // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch + // If pos == Pos(_, 0, "before"), pos and end are unchanged + pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos + end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos + } + for (let limit = 0; limit < 5; limit++) { + let changed = false + let coords = cursorCoords(cm, pos) + let endCoords = !end || end == pos ? coords : cursorCoords(cm, end) + rect = {left: Math.min(coords.left, endCoords.left), + top: Math.min(coords.top, endCoords.top) - margin, + right: Math.max(coords.left, endCoords.left), + bottom: Math.max(coords.bottom, endCoords.bottom) + margin} + let scrollPos = calculateScrollPos(cm, rect) + let startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft + if (scrollPos.scrollTop != null) { + updateScrollTop(cm, scrollPos.scrollTop) + if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true + } + if (scrollPos.scrollLeft != null) { + setScrollLeft(cm, scrollPos.scrollLeft) + if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true + } + if (!changed) break + } + return rect +} + +// Scroll a given set of coordinates into view (immediately). +export function scrollIntoView(cm, rect) { + let scrollPos = calculateScrollPos(cm, rect) + if (scrollPos.scrollTop != null) updateScrollTop(cm, scrollPos.scrollTop) + if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft) +} + +// Calculate a new scroll position needed to scroll the given +// rectangle into view. Returns an object with scrollTop and +// scrollLeft properties. When these are undefined, the +// vertical/horizontal position does not need to be adjusted. +function calculateScrollPos(cm, rect) { + let display = cm.display, snapMargin = textHeight(cm.display) + if (rect.top < 0) rect.top = 0 + let screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop + let screen = displayHeight(cm), result = {} + if (rect.bottom - rect.top > screen) rect.bottom = rect.top + screen + let docBottom = cm.doc.height + paddingVert(display) + let atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin + if (rect.top < screentop) { + result.scrollTop = atTop ? 0 : rect.top + } else if (rect.bottom > screentop + screen) { + let newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen) + if (newTop != screentop) result.scrollTop = newTop + } + + let screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft + let screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0) + let tooWide = rect.right - rect.left > screenw + if (tooWide) rect.right = rect.left + screenw + if (rect.left < 10) + result.scrollLeft = 0 + else if (rect.left < screenleft) + result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)) + else if (rect.right > screenw + screenleft - 3) + result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw + return result +} + +// Store a relative adjustment to the scroll position in the current +// operation (to be applied when the operation finishes). +export function addToScrollTop(cm, top) { + if (top == null) return + resolveScrollToPos(cm) + cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top +} + +// Make sure that at the end of the operation the current cursor is +// shown. +export function ensureCursorVisible(cm) { + resolveScrollToPos(cm) + let cur = cm.getCursor() + cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin} +} + +export function scrollToCoords(cm, x, y) { + if (x != null || y != null) resolveScrollToPos(cm) + if (x != null) cm.curOp.scrollLeft = x + if (y != null) cm.curOp.scrollTop = y +} + +export function scrollToRange(cm, range) { + resolveScrollToPos(cm) + cm.curOp.scrollToPos = range +} + +// When an operation has its scrollToPos property set, and another +// scroll action is applied before the end of the operation, this +// 'simulates' scrolling that position into view in a cheap way, so +// that the effect of intermediate scroll commands is not ignored. +function resolveScrollToPos(cm) { + let range = cm.curOp.scrollToPos + if (range) { + cm.curOp.scrollToPos = null + let from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to) + scrollToCoordsRange(cm, from, to, range.margin) + } +} + +export function scrollToCoordsRange(cm, from, to, margin) { + let sPos = calculateScrollPos(cm, { + left: Math.min(from.left, to.left), + top: Math.min(from.top, to.top) - margin, + right: Math.max(from.right, to.right), + bottom: Math.max(from.bottom, to.bottom) + margin + }) + scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop) +} + +// Sync the scrollable area and scrollbars, ensure the viewport +// covers the visible area. +export function updateScrollTop(cm, val) { + if (Math.abs(cm.doc.scrollTop - val) < 2) return + if (!gecko) updateDisplaySimple(cm, {top: val}) + setScrollTop(cm, val, true) + if (gecko) updateDisplaySimple(cm) + startWorker(cm, 100) +} + +export function setScrollTop(cm, val, forceScroll) { + val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val) + if (cm.display.scroller.scrollTop == val && !forceScroll) return + cm.doc.scrollTop = val + cm.display.scrollbars.setScrollTop(val) + if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val +} + +// Sync scroller and scrollbar, ensure the gutter elements are +// aligned. +export function setScrollLeft(cm, val, isScroller, forceScroll) { + val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth) + if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) return + cm.doc.scrollLeft = val + alignHorizontally(cm) + if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val + cm.display.scrollbars.setScrollLeft(val) +} diff --git a/modules/editor/codemirror/src/display/selection.js b/modules/editor/codemirror/src/display/selection.js @@ -0,0 +1,158 @@ +import { Pos } from "../line/pos.js" +import { visualLine } from "../line/spans.js" +import { getLine } from "../line/utils_line.js" +import { charCoords, cursorCoords, displayWidth, paddingH, wrappedLineExtentChar } from "../measurement/position_measurement.js" +import { getOrder, iterateBidiSections } from "../util/bidi.js" +import { elt } from "../util/dom.js" + +export function updateSelection(cm) { + cm.display.input.showSelection(cm.display.input.prepareSelection()) +} + +export function prepareSelection(cm, primary = true) { + let doc = cm.doc, result = {} + let curFragment = result.cursors = document.createDocumentFragment() + let selFragment = result.selection = document.createDocumentFragment() + + for (let i = 0; i < doc.sel.ranges.length; i++) { + if (!primary && i == doc.sel.primIndex) continue + let range = doc.sel.ranges[i] + if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) continue + let collapsed = range.empty() + if (collapsed || cm.options.showCursorWhenSelecting) + drawSelectionCursor(cm, range.head, curFragment) + if (!collapsed) + drawSelectionRange(cm, range, selFragment) + } + return result +} + +// Draws a cursor for the given range +export function drawSelectionCursor(cm, head, output) { + let pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine) + + let cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")) + cursor.style.left = pos.left + "px" + cursor.style.top = pos.top + "px" + cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px" + + if (pos.other) { + // Secondary cursor, shown when on a 'jump' in bi-directional text + let otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")) + otherCursor.style.display = "" + otherCursor.style.left = pos.other.left + "px" + otherCursor.style.top = pos.other.top + "px" + otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px" + } +} + +function cmpCoords(a, b) { return a.top - b.top || a.left - b.left } + +// Draws the given range as a highlighted selection +function drawSelectionRange(cm, range, output) { + let display = cm.display, doc = cm.doc + let fragment = document.createDocumentFragment() + let padding = paddingH(cm.display), leftSide = padding.left + let rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right + let docLTR = doc.direction == "ltr" + + function add(left, top, width, bottom) { + if (top < 0) top = 0 + top = Math.round(top) + bottom = Math.round(bottom) + fragment.appendChild(elt("div", null, "CodeMirror-selected", `position: absolute; left: ${left}px; + top: ${top}px; width: ${width == null ? rightSide - left : width}px; + height: ${bottom - top}px`)) + } + + function drawForLine(line, fromArg, toArg) { + let lineObj = getLine(doc, line) + let lineLen = lineObj.text.length + let start, end + function coords(ch, bias) { + return charCoords(cm, Pos(line, ch), "div", lineObj, bias) + } + + function wrapX(pos, dir, side) { + let extent = wrappedLineExtentChar(cm, lineObj, null, pos) + let prop = (dir == "ltr") == (side == "after") ? "left" : "right" + let ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1) + return coords(ch, prop)[prop] + } + + let order = getOrder(lineObj, doc.direction) + iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, (from, to, dir, i) => { + let ltr = dir == "ltr" + let fromPos = coords(from, ltr ? "left" : "right") + let toPos = coords(to - 1, ltr ? "right" : "left") + + let openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen + let first = i == 0, last = !order || i == order.length - 1 + if (toPos.top - fromPos.top <= 3) { // Single line + let openLeft = (docLTR ? openStart : openEnd) && first + let openRight = (docLTR ? openEnd : openStart) && last + let left = openLeft ? leftSide : (ltr ? fromPos : toPos).left + let right = openRight ? rightSide : (ltr ? toPos : fromPos).right + add(left, fromPos.top, right - left, fromPos.bottom) + } else { // Multiple lines + let topLeft, topRight, botLeft, botRight + if (ltr) { + topLeft = docLTR && openStart && first ? leftSide : fromPos.left + topRight = docLTR ? rightSide : wrapX(from, dir, "before") + botLeft = docLTR ? leftSide : wrapX(to, dir, "after") + botRight = docLTR && openEnd && last ? rightSide : toPos.right + } else { + topLeft = !docLTR ? leftSide : wrapX(from, dir, "before") + topRight = !docLTR && openStart && first ? rightSide : fromPos.right + botLeft = !docLTR && openEnd && last ? leftSide : toPos.left + botRight = !docLTR ? rightSide : wrapX(to, dir, "after") + } + add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom) + if (fromPos.bottom < toPos.top) add(leftSide, fromPos.bottom, null, toPos.top) + add(botLeft, toPos.top, botRight - botLeft, toPos.bottom) + } + + if (!start || cmpCoords(fromPos, start) < 0) start = fromPos + if (cmpCoords(toPos, start) < 0) start = toPos + if (!end || cmpCoords(fromPos, end) < 0) end = fromPos + if (cmpCoords(toPos, end) < 0) end = toPos + }) + return {start: start, end: end} + } + + let sFrom = range.from(), sTo = range.to() + if (sFrom.line == sTo.line) { + drawForLine(sFrom.line, sFrom.ch, sTo.ch) + } else { + let fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line) + let singleVLine = visualLine(fromLine) == visualLine(toLine) + let leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end + let rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start + if (singleVLine) { + if (leftEnd.top < rightStart.top - 2) { + add(leftEnd.right, leftEnd.top, null, leftEnd.bottom) + add(leftSide, rightStart.top, rightStart.left, rightStart.bottom) + } else { + add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom) + } + } + if (leftEnd.bottom < rightStart.top) + add(leftSide, leftEnd.bottom, null, rightStart.top) + } + + output.appendChild(fragment) +} + +// Cursor-blinking +export function restartBlink(cm) { + if (!cm.state.focused) return + let display = cm.display + clearInterval(display.blinker) + let on = true + display.cursorDiv.style.visibility = "" + if (cm.options.cursorBlinkRate > 0) + display.blinker = setInterval(() => display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden", + cm.options.cursorBlinkRate) + else if (cm.options.cursorBlinkRate < 0) + display.cursorDiv.style.visibility = "hidden" +} diff --git a/modules/editor/codemirror/src/display/update_display.min.js b/modules/editor/codemirror/src/display/update_display.min.js @@ -0,0 +1,260 @@ +import { sawCollapsedSpans } from "../line/saw_special_spans.js" +import { heightAtLine, visualLineEndNo, visualLineNo } from "../line/spans.js" +import { getLine, lineNumberFor } from "../line/utils_line.js" +import { displayHeight, displayWidth, getDimensions, paddingVert, scrollGap } from "../measurement/position_measurement.js" +import { mac, webkit } from "../util/browser.js" +import { activeElt, removeChildren, contains } from "../util/dom.js" +import { hasHandler, signal } from "../util/event.js" +import { indexOf } from "../util/misc.js" + +import { buildLineElement, updateLineForChanges } from "./update_line.js" +import { startWorker } from "./highlight_worker.js" +import { maybeUpdateLineNumberWidth } from "./line_numbers.js" +import { measureForScrollbars, updateScrollbars } from "./scrollbars.js" +import { updateSelection } from "./selection.js" +import { updateHeightsInViewport, visibleLines } from "./update_lines.js" +import { adjustView, countDirtyView, resetView } from "./view_tracking.js" + +// DISPLAY DRAWING + +export class DisplayUpdate { + constructor(cm, viewport, force) { + let display = cm.display + + this.viewport = viewport + // Store some values that we'll need later (but don't want to force a relayout for) + this.visible = visibleLines(display, cm.doc, viewport) + this.editorIsHidden = !display.wrapper.offsetWidth + this.wrapperHeight = display.wrapper.clientHeight + this.wrapperWidth = display.wrapper.clientWidth + this.oldDisplayWidth = displayWidth(cm) + this.force = force + this.dims = getDimensions(cm) + this.events = [] + } + + signal(emitter, type) { + if (hasHandler(emitter, type)) + this.events.push(arguments) + } + finish() { + for (let i = 0; i < this.events.length; i++) + signal.apply(null, this.events[i]) + } +} + +export function maybeClipScrollbars(cm) { + let display = cm.display + if (!display.scrollbarsClipped && display.scroller.offsetWidth) { + display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth + display.heightForcer.style.height = scrollGap(cm) + "px" + display.sizer.style.marginBottom = -display.nativeBarWidth + "px" + display.sizer.style.borderRightWidth = scrollGap(cm) + "px" + display.scrollbarsClipped = true + } +} + +function selectionSnapshot(cm) { + if (cm.hasFocus()) return null + let active = activeElt() + if (!active || !contains(cm.display.lineDiv, active)) return null + let result = {activeElt: active} + if (window.getSelection) { + let sel = window.getSelection() + if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) { + result.anchorNode = sel.anchorNode + result.anchorOffset = sel.anchorOffset + result.focusNode = sel.focusNode + result.focusOffset = sel.focusOffset + } + } + return result +} + +function restoreSelection(snapshot) { + if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) return + snapshot.activeElt.focus() + if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) { + let sel = window.getSelection(), range = document.createRange() + range.setEnd(snapshot.anchorNode, snapshot.anchorOffset) + range.collapse(false) + sel.removeAllRanges() + sel.addRange(range) + sel.extend(snapshot.focusNode, snapshot.focusOffset) + } +} + +// Does the actual updating of the line display. Bails out +// (returning false) when there is nothing to be done and forced is +// false. +export function updateDisplayIfNeeded(cm, update) { + let display = cm.display, doc = cm.doc + + if (update.editorIsHidden) { + resetView(cm) + return false + } + + // Bail out if the visible area is already rendered and nothing changed. + if (!update.force && + update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && + (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && + display.renderedView == display.view && countDirtyView(cm) == 0) + return false + + if (maybeUpdateLineNumberWidth(cm)) { + resetView(cm) + update.dims = getDimensions(cm) + } + + // Compute a suitable new viewport (from & to) + let end = doc.first + doc.size + let from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first) + let to = Math.min(end, update.visible.to + cm.options.viewportMargin) + if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom) + if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo) + if (sawCollapsedSpans) { + from = visualLineNo(cm.doc, from) + to = visualLineEndNo(cm.doc, to) + } + + let different = from != display.viewFrom || to != display.viewTo || + display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth + adjustView(cm, from, to) + + display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)) + // Position the mover div to align with the current scroll position + cm.display.mover.style.top = display.viewOffset + "px" + + let toUpdate = countDirtyView(cm) + if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && + (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) + return false + + // For big changes, we hide the enclosing element during the + // update, since that speeds up the operations on most browsers. + let selSnapshot = selectionSnapshot(cm) + if (toUpdate > 4) display.lineDiv.style.display = "none" + patchDisplay(cm, display.updateLineNumbers, update.dims) + if (toUpdate > 4) display.lineDiv.style.display = "" + display.renderedView = display.view + // There might have been a widget with a focused element that got + // hidden or updated, if so re-focus it. + restoreSelection(selSnapshot) + + // Prevent selection and cursors from interfering with the scroll + // width and height. + removeChildren(display.cursorDiv) + removeChildren(display.selectionDiv) + display.gutters.style.height = display.sizer.style.minHeight = 0 + + if (different) { + display.lastWrapHeight = update.wrapperHeight + display.lastWrapWidth = update.wrapperWidth + startWorker(cm, 400) + } + + display.updateLineNumbers = null + + return true +} + +export function postUpdateDisplay(cm, update) { + let viewport = update.viewport + + for (let first = true;; first = false) { + if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { + // Clip forced viewport to actual scrollable area. + if (viewport && viewport.top != null) + viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)} + // Updated line heights might result in the drawn area not + // actually covering the viewport. Keep looping until it does. + update.visible = visibleLines(cm.display, cm.doc, viewport) + if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) + break + } + if (!updateDisplayIfNeeded(cm, update)) break + updateHeightsInViewport(cm) + let barMeasure = measureForScrollbars(cm) + updateSelection(cm) + updateScrollbars(cm, barMeasure) + setDocumentHeight(cm, barMeasure) + update.force = false + } + + 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 + } +} + +export function updateDisplaySimple(cm, viewport) { + let update = new DisplayUpdate(cm, viewport) + if (updateDisplayIfNeeded(cm, update)) { + updateHeightsInViewport(cm) + postUpdateDisplay(cm, update) + let barMeasure = measureForScrollbars(cm) + updateSelection(cm) + updateScrollbars(cm, barMeasure) + setDocumentHeight(cm, barMeasure) + update.finish() + } +} + +// Sync the actual display DOM structure with display.view, removing +// nodes for lines that are no longer in view, and creating the ones +// that are not there yet, and updating the ones that are out of +// date. +function patchDisplay(cm, updateNumbersFrom, dims) { + let display = cm.display, lineNumbers = cm.options.lineNumbers + let container = display.lineDiv, cur = container.firstChild + + function rm(node) { + let next = node.nextSibling + // Works around a throw-scroll bug in OS X Webkit + if (webkit && mac && cm.display.currentWheelTarget == node) + node.style.display = "none" + else + node.parentNode.removeChild(node) + return next + } + + let view = display.view, lineN = display.viewFrom + // Loop over the elements in the view, syncing cur (the DOM nodes + // in display.lineDiv) with the view as we go. + for (let i = 0; i < view.length; i++) { + let lineView = view[i] + if (lineView.hidden) { + } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet + let node = buildLineElement(cm, lineView, lineN, dims) + container.insertBefore(node, cur) + } else { // Already drawn + while (cur != lineView.node) cur = rm(cur) + let updateNumber = lineNumbers && updateNumbersFrom != null && + updateNumbersFrom <= lineN && lineView.lineNumber + if (lineView.changes) { + if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false + updateLineForChanges(cm, lineView, lineN, dims) + } + if (updateNumber) { + removeChildren(lineView.lineNumber) + lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))) + } + cur = lineView.node.nextSibling + } + lineN += lineView.size + } + while (cur) cur = rm(cur) +} + +export function updateGutterSpace(cm) { + let width = cm.display.gutters.offsetWidth + cm.display.sizer.style.marginLeft = width + "px" +} + +export 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" +} diff --git a/modules/editor/codemirror/src/display/update_lines.js b/modules/editor/codemirror/src/display/update_lines.js @@ -0,0 +1,64 @@ +import { heightAtLine } from "../line/spans.js" +import { getLine, lineAtHeight, updateLineHeight } from "../line/utils_line.js" +import { paddingTop, textHeight } from "../measurement/position_measurement.js" +import { ie, ie_version } from "../util/browser.js" + +// Read the actual heights of the rendered lines, and update their +// stored heights to match. +export function updateHeightsInViewport(cm) { + let display = cm.display + let prevBottom = display.lineDiv.offsetTop + for (let i = 0; i < display.view.length; i++) { + let cur = display.view[i], height + if (cur.hidden) continue + if (ie && ie_version < 8) { + let bot = cur.node.offsetTop + cur.node.offsetHeight + height = bot - prevBottom + prevBottom = bot + } else { + let box = cur.node.getBoundingClientRect() + height = box.bottom - box.top + } + let diff = cur.line.height - height + if (height < 2) height = textHeight(display) + if (diff > .005 || diff < -.005) { + updateLineHeight(cur.line, height) + updateWidgetHeight(cur.line) + if (cur.rest) for (let j = 0; j < cur.rest.length; j++) + updateWidgetHeight(cur.rest[j]) + } + } +} + +// Read and store the height of line widgets associated with the +// given line. +function updateWidgetHeight(line) { + if (line.widgets) for (let i = 0; i < line.widgets.length; ++i) { + let w = line.widgets[i], parent = w.node.parentNode + if (parent) w.height = parent.offsetHeight + } +} + +// Compute the lines that are visible in a given viewport (defaults +// the the current scroll position). viewport may contain top, +// height, and ensure (see op.scrollToPos) properties. +export function visibleLines(display, doc, viewport) { + let top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop + top = Math.floor(top - paddingTop(display)) + let bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight + + let from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom) + // Ensure is a {from: {line, ch}, to: {line, ch}} object, and + // forces those lines into the viewport (if possible). + if (viewport && viewport.ensure) { + let 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)} +} diff --git a/modules/editor/codemirror/src/edit/key_events.min.js b/modules/editor/codemirror/src/edit/key_events.min.js @@ -0,0 +1,159 @@ +import { signalLater } from "../util/operation_group.js" +import { restartBlink } from "../display/selection.js" +import { isModifierKey, keyName, lookupKey } from "../input/keymap.js" +import { eventInWidget } from "../measurement/widgets.js" +import { ie, ie_version, mac, presto } from "../util/browser.js" +import { activeElt, addClass, rmClass } from "../util/dom.js" +import { e_preventDefault, off, on, signalDOMEvent } from "../util/event.js" +import { hasCopyEvent } from "../util/feature_detection.js" +import { Delayed, Pass } from "../util/misc.js" + +import { commands } from "./commands.js" + +// Run a handler that was bound to a key. +function doHandleBinding(cm, bound, dropShift) { + if (typeof bound == "string") { + bound = commands[bound] + if (!bound) return false + } + // Ensure previous input has been read, so that the handler sees a + // consistent view of the document + cm.display.input.ensurePolled() + let prevShift = cm.display.shift, done = false + try { + if (cm.isReadOnly()) cm.state.suppressEdits = true + if (dropShift) cm.display.shift = false + done = bound(cm) != Pass + } finally { + cm.display.shift = prevShift + cm.state.suppressEdits = false + } + return done +} + +function lookupKeyForEditor(cm, name, handle) { + for (let i = 0; i < cm.state.keyMaps.length; i++) { + let 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) +} + +// Note that, despite the name, this function is also used to check +// for bound mouse clicks. + +let stopSeq = new Delayed + +export function dispatchKey(cm, name, e, handle) { + let seq = cm.state.keySeq + if (seq) { + if (isModifierKey(name)) return "handled" + if (/\'$/.test(name)) + cm.state.keySeq = null + else + stopSeq.set(50, () => { + if (cm.state.keySeq == seq) { + cm.state.keySeq = null + cm.display.input.reset() + } + }) + if (dispatchKeyInner(cm, seq + " " + name, e, handle)) return true + } + return dispatchKeyInner(cm, name, e, handle) +} + +function dispatchKeyInner(cm, name, e, handle) { + let result = lookupKeyForEditor(cm, name, handle) + + if (result == "multi") + cm.state.keySeq = name + if (result == "handled") + signalLater(cm, "keyHandled", cm, name, e) + + if (result == "handled" || result == "multi") { + e_preventDefault(e) + restartBlink(cm) + } + + return !!result +} + +// Handle a key from the keydown event. +function handleKeyBinding(cm, e) { + let name = keyName(e, true) + if (!name) return false + + if (e.shiftKey && !cm.state.keySeq) { + // First try to resolve full name (including 'Shift-'). Failing + // that, see if there is a cursor-motion command (starting with + // 'go') bound to the keyname without 'Shift-'. + return dispatchKey(cm, "Shift-" + name, e, b => doHandleBinding(cm, b, true)) + || dispatchKey(cm, name, e, b => { + if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) + return doHandleBinding(cm, b) + }) + } else { + return dispatchKey(cm, name, e, b => doHandleBinding(cm, b)) + } +} + +// Handle a key from the keypress event +function handleCharBinding(cm, e, ch) { + return dispatchKey(cm, "'" + ch + "'", e, b => doHandleBinding(cm, b, true)) +} + +let lastStoppedKey = null +export function onKeyDown(e) { + let cm = this + cm.curOp.focus = activeElt() + if (signalDOMEvent(cm, e)) return + // IE does strange things with escape. + if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false + let code = e.keyCode + cm.display.shift = code == 16 || e.shiftKey + let handled = handleKeyBinding(cm, e) + if (presto) { + lastStoppedKey = handled ? code : null + // Opera has no cut event... we try to at least catch the key combo + if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) + cm.replaceSelection("", null, "cut") + } + + // Turn mouse into crosshair when Alt is held on Mac. + if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) + showCrossHair(cm) +} + +function showCrossHair(cm) { + let lineDiv = cm.display.lineDiv + addClass(lineDiv, "CodeMirror-crosshair") + + function up(e) { + if (e.keyCode == 18 || !e.altKey) { + rmClass(lineDiv, "CodeMirror-crosshair") + off(document, "keyup", up) + off(document, "mouseover", up) + } + } + on(document, "keyup", up) + on(document, "mouseover", up) +} + +export function onKeyUp(e) { + if (e.keyCode == 16) this.doc.sel.shift = false + signalDOMEvent(this, e) +} + +export function onKeyPress(e) { + let cm = this + if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return + let keyCode = e.keyCode, charCode = e.charCode + if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return} + if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return + let ch = String.fromCharCode(charCode == null ? keyCode : charCode) + // Some browsers fire keypress events for backspace + if (ch == "\x08") return + if (handleCharBinding(cm, e, ch)) return + cm.display.input.onKeyPress(e) +} diff --git a/modules/editor/codemirror/src/edit/utils.min.js b/modules/editor/codemirror/src/edit/utils.min.js @@ -0,0 +1,7 @@ +import { clearCaches } from "../measurement/position_measurement.js" + +export 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) +} diff --git a/modules/editor/codemirror/src/input/ContentEditableInput.js b/modules/editor/codemirror/src/input/ContentEditableInput.js @@ -0,0 +1,517 @@ +import { operation, runInOp } from "../display/operations.js" +import { prepareSelection } from "../display/selection.js" +import { regChange } from "../display/view_tracking.js" +import { applyTextInput, copyableRanges, disableBrowserMagic, handlePaste, hiddenTextarea, lastCopied, setLastCopied } from "./input.js" +import { cmp, maxPos, minPos, Pos } from "../line/pos.js" +import { getBetween, getLine, lineNo } from "../line/utils_line.js" +import { findViewForLine, findViewIndex, mapFromLineView, nodeAndOffsetInLineMap } from "../measurement/position_measurement.js" +import { replaceRange } from "../model/changes.js" +import { simpleSelection } from "../model/selection.js" +import { setSelection } from "../model/selection_updates.js" +import { getBidiPartAt, getOrder } from "../util/bidi.js" +import { android, chrome, gecko, ie_version } from "../util/browser.js" +import { contains, range, removeChildrenAndAdd, selectInput } from "../util/dom.js" +import { on, signalDOMEvent } from "../util/event.js" +import { Delayed, lst, sel_dontScroll } from "../util/misc.js" + +// CONTENTEDITABLE INPUT STYLE + +export default class ContentEditableInput { + constructor(cm) { + this.cm = cm + this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null + this.polling = new Delayed() + this.composing = null + this.gracePeriod = false + this.readDOMTimeout = null + } + + init(display) { + let input = this, cm = input.cm + let div = input.div = display.lineDiv + disableBrowserMagic(div, cm.options.spellcheck) + + on(div, "paste", e => { + if (signalDOMEvent(cm, e) || handlePaste(e, cm)) return + // IE doesn't fire input events, so we schedule a read for the pasted content in this way + if (ie_version <= 11) setTimeout(operation(cm, () => this.updateFromDOM()), 20) + }) + + on(div, "compositionstart", e => { + this.composing = {data: e.data, done: false} + }) + on(div, "compositionupdate", e => { + if (!this.composing) this.composing = {data: e.data, done: false} + }) + on(div, "compositionend", e => { + if (this.composing) { + if (e.data != this.composing.data) this.readFromDOMSoon() + this.composing.done = true + } + }) + + on(div, "touchstart", () => input.forceCompositionEnd()) + + on(div, "input", () => { + if (!this.composing) this.readFromDOMSoon() + }) + + function onCopyCut(e) { + if (signalDOMEvent(cm, e)) return + if (cm.somethingSelected()) { + setLastCopied({lineWise: false, text: cm.getSelections()}) + if (e.type == "cut") cm.replaceSelection("", null, "cut") + } else if (!cm.options.lineWiseCopyCut) { + return + } else { + let ranges = copyableRanges(cm) + setLastCopied({lineWise: true, text: ranges.text}) + if (e.type == "cut") { + cm.operation(() => { + cm.setSelections(ranges.ranges, 0, sel_dontScroll) + cm.replaceSelection("", null, "cut") + }) + } + } + if (e.clipboardData) { + e.clipboardData.clearData() + let content = lastCopied.text.join("\n") + // iOS exposes the clipboard API, but seems to discard content inserted into it + e.clipboardData.setData("Text", content) + if (e.clipboardData.getData("Text") == content) { + e.preventDefault() + return + } + } + // Old-fashioned briefly-focus-a-textarea hack + let kludge = hiddenTextarea(), te = kludge.firstChild + cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild) + te.value = lastCopied.text.join("\n") + let hadFocus = document.activeElement + selectInput(te) + setTimeout(() => { + cm.display.lineSpace.removeChild(kludge) + hadFocus.focus() + if (hadFocus == div) input.showPrimarySelection() + }, 50) + } + on(div, "copy", onCopyCut) + on(div, "cut", onCopyCut) + } + + prepareSelection() { + let result = prepareSelection(this.cm, false) + result.focus = this.cm.state.focused + return result + } + + showSelection(info, takeFocus) { + if (!info || !this.cm.display.view.length) return + if (info.focus || takeFocus) this.showPrimarySelection() + this.showMultipleSelections(info) + } + + showPrimarySelection() { + let sel = window.getSelection(), cm = this.cm, prim = cm.doc.sel.primary() + let from = prim.from(), to = prim.to() + + if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) { + sel.removeAllRanges() + return + } + + let curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset) + let curFocus = domToPos(cm, sel.focusNode, sel.focusOffset) + if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && + cmp(minPos(curAnchor, curFocus), from) == 0 && + cmp(maxPos(curAnchor, curFocus), to) == 0) + return + + let view = cm.display.view + let start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) || + {node: view[0].measure.map[2], offset: 0} + let end = to.line < cm.display.viewTo && posToDOM(cm, to) + if (!end) { + let measure = view[view.length - 1].measure + let 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]} + } + + if (!start || !end) { + sel.removeAllRanges() + return + } + + let old = sel.rangeCount && sel.getRangeAt(0), rng + try { rng = range(start.node, start.offset, end.offset, end.node) } + catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible + if (rng) { + if (!gecko && cm.state.focused) { + sel.collapse(start.node, start.offset) + if (!rng.collapsed) { + sel.removeAllRanges() + sel.addRange(rng) + } + } else { + sel.removeAllRanges() + sel.addRange(rng) + } + if (old && sel.anchorNode == null) sel.addRange(old) + else if (gecko) this.startGracePeriod() + } + this.rememberSelection() + } + + startGracePeriod() { + clearTimeout(this.gracePeriod) + this.gracePeriod = setTimeout(() => { + this.gracePeriod = false + if (this.selectionChanged()) + this.cm.operation(() => this.cm.curOp.selectionChanged = true) + }, 20) + } + + showMultipleSelections(info) { + removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors) + removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection) + } + + rememberSelection() { + let sel = window.getSelection() + this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset + this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset + } + + selectionInEditor() { + let sel = window.getSelection() + if (!sel.rangeCount) return false + let node = sel.getRangeAt(0).commonAncestorContainer + return contains(this.div, node) + } + + focus() { + if (this.cm.options.readOnly != "nocursor") { + if (!this.selectionInEditor()) + this.showSelection(this.prepareSelection(), true) + this.div.focus() + } + } + blur() { this.div.blur() } + getField() { return this.div } + + supportsTouch() { return true } + + receivedFocus() { + let input = this + if (this.selectionInEditor()) + this.pollSelection() + else + runInOp(this.cm, () => input.cm.curOp.selectionChanged = true) + + function poll() { + if (input.cm.state.focused) { + input.pollSelection() + input.polling.set(input.cm.options.pollInterval, poll) + } + } + this.polling.set(this.cm.options.pollInterval, poll) + } + + selectionChanged() { + let sel = window.getSelection() + return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || + sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset + } + + pollSelection() { + if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) return + let sel = window.getSelection(), cm = this.cm + // On Android Chrome (version 56, at least), backspacing into an + // uneditable block element will put the cursor in that element, + // and then, because it's not editable, hide the virtual keyboard. + // Because Android doesn't allow us to actually detect backspace + // presses in a sane way, this code checks for when that happens + // and simulates a backspace press in this case. + if (android && chrome && this.cm.options.gutters.length && isInGutter(sel.anchorNode)) { + this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs}) + this.blur() + this.focus() + return + } + if (this.composing) return + this.rememberSelection() + let anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset) + let head = domToPos(cm, sel.focusNode, sel.focusOffset) + if (anchor && head) runInOp(cm, () => { + setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll) + if (anchor.bad || head.bad) cm.curOp.selectionChanged = true + }) + } + + pollContent() { + if (this.readDOMTimeout != null) { + clearTimeout(this.readDOMTimeout) + this.readDOMTimeout = null + } + + let cm = this.cm, display = cm.display, sel = cm.doc.sel.primary() + let from = sel.from(), to = sel.to() + if (from.ch == 0 && from.line > cm.firstLine()) + from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length) + if (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 false + + let fromIndex, fromLine, fromNode + if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { + fromLine = lineNo(display.view[0].line) + fromNode = display.view[0].node + } else { + fromLine = lineNo(display.view[fromIndex].line) + fromNode = display.view[fromIndex - 1].node.nextSibling + } + let toIndex = findViewIndex(cm, to.line) + let toLine, toNode + 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 false + let newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)) + let oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)) + while (newText.length > 1 && oldText.length > 1) { + if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine-- } + else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++ } + else break + } + + let cutFront = 0, cutEnd = 0 + let newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length) + while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) + ++cutFront + let newBot = lst(newText), oldBot = lst(oldText) + let maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), + oldBot.length - (oldText.length == 1 ? cutFront : 0)) + while (cutEnd < maxCutEnd && + newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) + ++cutEnd + // Try to move start of change to start of selection if ambiguous + if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) { + while (cutFront && cutFront > from.ch && + newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { + cutFront-- + cutEnd++ + } + } + + newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "") + newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "") + + let chFrom = Pos(fromLine, cutFront) + let chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0) + if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { + replaceRange(cm.doc, newText, chFrom, chTo, "+input") + return true + } + } + + ensurePolled() { + this.forceCompositionEnd() + } + reset() { + this.forceCompositionEnd() + } + forceCompositionEnd() { + if (!this.composing) return + clearTimeout(this.readDOMTimeout) + this.composing = null + this.updateFromDOM() + this.div.blur() + this.div.focus() + } + readFromDOMSoon() { + if (this.readDOMTimeout != null) return + this.readDOMTimeout = setTimeout(() => { + this.readDOMTimeout = null + if (this.composing) { + if (this.composing.done) this.composing = null + else return + } + this.updateFromDOM() + }, 80) + } + + updateFromDOM() { + if (this.cm.isReadOnly() || !this.pollContent()) + runInOp(this.cm, () => regChange(this.cm)) + } + + setUneditable(node) { + node.contentEditable = "false" + } + + onKeyPress(e) { + if (e.charCode == 0) return + e.preventDefault() + if (!this.cm.isReadOnly()) + operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0) + } + + readOnlyChanged(val) { + this.div.contentEditable = String(val != "nocursor") + } + + onContextMenu() {} + resetPosition() {} +} + +ContentEditableInput.prototype.needsContentAttribute = true + +function posToDOM(cm, pos) { + let view = findViewForLine(cm, pos.line) + if (!view || view.hidden) return null + let line = getLine(cm.doc, pos.line) + let info = mapFromLineView(view, line, pos.line) + + let order = getOrder(line, cm.doc.direction), side = "left" + if (order) { + let partPos = getBidiPartAt(order, pos.ch) + side = partPos % 2 ? "right" : "left" + } + let result = nodeAndOffsetInLineMap(info.map, pos.ch, side) + result.offset = result.collapse == "right" ? result.end : result.start + return result +} + +function isInGutter(node) { + for (let scan = node; scan; scan = scan.parentNode) + if (/CodeMirror-gutter-wrapper/.test(scan.className)) return true + return false +} + +function badPos(pos, bad) { if (bad) pos.bad = true; return pos } + +function domTextBetween(cm, from, to, fromLine, toLine) { + let text = "", closing = false, lineSep = cm.doc.lineSeparator() + function recognizeMarker(id) { return marker => marker.id == id } + function close() { + if (closing) { + text += lineSep + closing = false + } + } + function addText(str) { + if (str) { + close() + text += str + } + } + function walk(node) { + if (node.nodeType == 1) { + let cmText = node.getAttribute("cm-text") + if (cmText != null) { + addText(cmText || node.textContent.replace(/\u200b/g, "")) + return + } + let markerID = node.getAttribute("cm-marker"), range + if (markerID) { + let found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)) + if (found.length && (range = found[0].find(0))) + addText(getBetween(cm.doc, range.from, range.to).join(lineSep)) + return + } + if (node.getAttribute("contenteditable") == "false") return + let isBlock = /^(pre|div|p)$/i.test(node.nodeName) + if (isBlock) close() + for (let i = 0; i < node.childNodes.length; i++) + walk(node.childNodes[i]) + if (isBlock) closing = true + } else if (node.nodeType == 3) { + addText(node.nodeValue) + } + } + for (;;) { + walk(from) + if (from == to) break + from = from.nextSibling + } + return text +} + +function domToPos(cm, node, offset) { + let lineNode + if (node == cm.display.lineDiv) { + lineNode = cm.display.lineDiv.childNodes[offset] + if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) + node = null; offset = 0 + } else { + for (lineNode = node;; lineNode = lineNode.parentNode) { + if (!lineNode || lineNode == cm.display.lineDiv) return null + if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break + } + } + for (let i = 0; i < cm.display.view.length; i++) { + let lineView = cm.display.view[i] + if (lineView.node == lineNode) + return locateNodeInLineView(lineView, node, offset) + } +} + +function locateNodeInLineView(lineView, node, offset) { + let wrapper = lineView.text.firstChild, bad = false + if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true) + if (node == wrapper) { + bad = true + node = wrapper.childNodes[offset] + offset = 0 + if (!node) { + let line = lineView.rest ? lst(lineView.rest) : lineView.line + return badPos(Pos(lineNo(line), line.text.length), bad) + } + } + + let textNode = node.nodeType == 3 ? node : null, topNode = node + if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { + textNode = node.firstChild + if (offset) offset = textNode.nodeValue.length + } + while (topNode.parentNode != wrapper) topNode = topNode.parentNode + let measure = lineView.measure, maps = measure.maps + + function find(textNode, topNode, offset) { + for (let i = -1; i < (maps ? maps.length : 0); i++) { + let map = i < 0 ? measure.map : maps[i] + for (let j = 0; j < map.length; j += 3) { + let curNode = map[j + 2] + if (curNode == textNode || curNode == topNode) { + let line = lineNo(i < 0 ? lineView.line : lineView.rest[i]) + let ch = map[j] + offset + if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)] + return Pos(line, ch) + } + } + } + } + let found = find(textNode, topNode, offset) + if (found) return badPos(found, bad) + + // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems + for (let after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { + found = find(after, after.firstChild, 0) + if (found) + return badPos(Pos(found.line, found.ch - dist), bad) + else + dist += after.textContent.length + } + for (let before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) { + found = find(before, before.firstChild, -1) + if (found) + return badPos(Pos(found.line, found.ch + dist), bad) + else + dist += before.textContent.length + } +} diff --git a/modules/editor/codemirror/src/input/indent.min.js b/modules/editor/codemirror/src/input/indent.min.js @@ -0,0 +1,71 @@ +import { getContextBefore } from "../line/highlight.js" +import { Pos } from "../line/pos.js" +import { getLine } from "../line/utils_line.js" +import { replaceRange } from "../model/changes.js" +import { Range } from "../model/selection.js" +import { replaceOneSelection } from "../model/selection_updates.js" +import { countColumn, Pass, spaceStr } from "../util/misc.js" + +// Indent the given line. The how parameter can be "smart", +// "add"/null, "subtract", or "prev". When aggressive is false +// (typically set to true for forced single-line indents), empty +// lines are not indented, and places where the mode returns Pass +// are left alone. +export function indentLine(cm, n, how, aggressive) { + let doc = cm.doc, state + if (how == null) how = "add" + if (how == "smart") { + // Fall back to "prev" when the mode doesn't have an indentation + // method. + if (!doc.mode.indent) how = "prev" + else state = getContextBefore(cm, n).state + } + + let tabSize = cm.options.tabSize + let line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize) + if (line.stateAfter) line.stateAfter = null + let curSpaceString = line.text.match(/^\s*/)[0], indentation + if (!aggressive && !/\S/.test(line.text)) { + indentation = 0 + how = "not" + } else if (how == "smart") { + indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text) + if (indentation == Pass || indentation > 150) { + if (!aggressive) return + how = "prev" + } + } + if (how == "prev") { + if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize) + else indentation = 0 + } else if (how == "add") { + indentation = curSpace + cm.options.indentUnit + } else if (how == "subtract") { + indentation = curSpace - cm.options.indentUnit + } else if (typeof how == "number") { + indentation = curSpace + how + } + indentation = Math.max(0, indentation) + + let indentString = "", pos = 0 + if (cm.options.indentWithTabs) + for (let i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t"} + if (pos < indentation) indentString += spaceStr(indentation - pos) + + if (indentString != curSpaceString) { + replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input") + line.stateAfter = null + return true + } else { + // Ensure that, if the cursor was in the whitespace at the start + // of the line, it is moved to the end of that space. + for (let i = 0; i < doc.sel.ranges.length; i++) { + let range = doc.sel.ranges[i] + if (range.head.line == n && range.head.ch < curSpaceString.length) { + let pos = Pos(n, curSpaceString.length) + replaceOneSelection(doc, i, new Range(pos, pos)) + break + } + } + } +} diff --git a/modules/editor/codemirror/src/input/input.min.js b/modules/editor/codemirror/src/input/input.min.js @@ -0,0 +1,135 @@ +import { runInOp } from "../display/operations.js" +import { ensureCursorVisible } from "../display/scrolling.js" +import { Pos } from "../line/pos.js" +import { getLine } from "../line/utils_line.js" +import { makeChange } from "../model/changes.js" +import { ios, webkit } from "../util/browser.js" +import { elt } from "../util/dom.js" +import { lst, map } from "../util/misc.js" +import { signalLater } from "../util/operation_group.js" +import { splitLinesAuto } from "../util/feature_detection.js" + +import { indentLine } from "./indent.js" + +// This will be set to a {lineWise: bool, text: [string]} object, so +// that, when pasting, we know what kind of selections the copied +// text was made out of. +export let lastCopied = null + +export function setLastCopied(newLastCopied) { + lastCopied = newLastCopied +} + +export function applyTextInput(cm, inserted, deleted, sel, origin) { + let doc = cm.doc + cm.display.shift = false + if (!sel) sel = doc.sel + + let paste = cm.state.pasteIncoming || origin == "paste" + let textLines = splitLinesAuto(inserted), multiPaste = null + // When pasing N lines into N selections, insert one line per selection + if (paste && sel.ranges.length > 1) { + if (lastCopied && lastCopied.text.join("\n") == inserted) { + if (sel.ranges.length % lastCopied.text.length == 0) { + multiPaste = [] + for (let i = 0; i < lastCopied.text.length; i++) + multiPaste.push(doc.splitLines(lastCopied.text[i])) + } + } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) { + multiPaste = map(textLines, l => [l]) + } + } + + let updateInput + // Normal behavior is to insert the new text into every selection + for (let i = sel.ranges.length - 1; i >= 0; i--) { + let range = sel.ranges[i] + let from = range.from(), to = range.to() + if (range.empty()) { + if (deleted && deleted > 0) // Handle deletion + from = Pos(from.line, from.ch - deleted) + else if (cm.state.overwrite && !paste) // Handle overwrite + to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)) + else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted) + from = to = Pos(from.line, 0) + } + updateInput = cm.curOp.updateInput + let changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines, + origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")} + makeChange(cm.doc, changeEvent) + signalLater(cm, "inputRead", cm, changeEvent) + } + if (inserted && !paste) + triggerElectric(cm, inserted) + + ensureCursorVisible(cm) + cm.curOp.updateInput = updateInput + cm.curOp.typing = true + cm.state.pasteIncoming = cm.state.cutIncoming = false +} + +export function handlePaste(e, cm) { + let pasted = e.clipboardData && e.clipboardData.getData("Text") + if (pasted) { + e.preventDefault() + if (!cm.isReadOnly() && !cm.options.disableInput) + runInOp(cm, () => applyTextInput(cm, pasted, 0, null, "paste")) + return true + } +} + +export function triggerElectric(cm, inserted) { + // When an 'electric' character is inserted, immediately trigger a reindent + if (!cm.options.electricChars || !cm.options.smartIndent) return + let sel = cm.doc.sel + + for (let i = sel.ranges.length - 1; i >= 0; i--) { + let range = sel.ranges[i] + if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue + let mode = cm.getModeAt(range.head) + let indented = false + if (mode.electricChars) { + for (let j = 0; j < mode.electricChars.length; j++) + if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { + indented = indentLine(cm, range.head.line, "smart") + break + } + } else if (mode.electricInput) { + if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch))) + indented = indentLine(cm, range.head.line, "smart") + } + if (indented) signalLater(cm, "electricInput", cm, range.head.line) + } +} + +export function copyableRanges(cm) { + let text = [], ranges = [] + for (let i = 0; i < cm.doc.sel.ranges.length; i++) { + let line = cm.doc.sel.ranges[i].head.line + let 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} +} + +export function disableBrowserMagic(field, spellcheck) { + field.setAttribute("autocorrect", "off") + field.setAttribute("autocapitalize", "off") + field.setAttribute("spellcheck", !!spellcheck) +} + +export function hiddenTextarea() { + let te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none") + let div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;") + // The textarea is kept positioned near the cursor to prevent the + // fact that it'll be scrolled into view on input from scrolling + // our fake cursor out of view. On webkit, when wrap=off, paste is + // very slow. So make the area wide instead. + if (webkit) te.style.width = "1000px" + else te.setAttribute("wrap", "off") + // If border: 0; -- iOS fails to open keyboard (issue #1287) + if (ios) te.style.border = "1px solid black" + disableBrowserMagic(te) + return div +} diff --git a/modules/editor/codemirror/src/input/keymap.min.js b/modules/editor/codemirror/src/input/keymap.min.js @@ -0,0 +1,145 @@ +import { flipCtrlCmd, mac, presto } from "../util/browser.js" +import { map } from "../util/misc.js" + +import { keyNames } from "./keynames.js" + +export let keyMap = {} + +keyMap.basic = { + "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", + "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", + "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore", + "Tab": "defaultTab", "Shift-Tab": "indentAuto", + "Enter": "newlineAndIndent", "Insert": "toggleOverwrite", + "Esc": "singleSelection" +} +// Note that the save and find-related commands aren't defined by +// default. User code or addons can define them. Unknown commands +// are simply ignored. +keyMap.pcDefault = { + "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", + "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown", + "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", + "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", + "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", + "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", + "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection", + fallthrough: "basic" +} +// Very basic readline/emacs-style bindings, which are standard on Mac. +keyMap.emacsy = { + "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", + "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", + "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", + "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars", + "Ctrl-O": "openLine" +} +keyMap.macDefault = { + "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", + "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", + "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore", + "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", + "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", + "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight", + "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd", + fallthrough: ["basic", "emacsy"] +} +keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault + +// KEYMAP DISPATCH + +function normalizeKeyName(name) { + let parts = name.split(/-(?!$)/) + name = parts[parts.length - 1] + let alt, ctrl, shift, cmd + for (let i = 0; i < parts.length - 1; i++) { + let mod = parts[i] + if (/^(cmd|meta|m)$/i.test(mod)) cmd = true + else if (/^a(lt)?$/i.test(mod)) alt = true + else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true + else if (/^s(hift)?$/i.test(mod)) shift = true + else throw new Error("Unrecognized modifier name: " + mod) + } + if (alt) name = "Alt-" + name + if (ctrl) name = "Ctrl-" + name + if (cmd) name = "Cmd-" + name + if (shift) name = "Shift-" + name + return name +} + +// This is a kludge to keep keymaps mostly working as raw objects +// (backwards compatibility) while at the same time support features +// like normalization and multi-stroke key bindings. It compiles a +// new normalized keymap, and then updates the old object to reflect +// this. +export function normalizeKeyMap(keymap) { + let copy = {} + for (let keyname in keymap) if (keymap.hasOwnProperty(keyname)) { + let value = keymap[keyname] + if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue + if (value == "...") { delete keymap[keyname]; continue } + + let keys = map(keyname.split(" "), normalizeKeyName) + for (let i = 0; i < keys.length; i++) { + let val, name + if (i == keys.length - 1) { + name = keys.join(" ") + val = value + } else { + name = keys.slice(0, i + 1).join(" ") + val = "..." + } + let prev = copy[name] + if (!prev) copy[name] = val + else if (prev != val) throw new Error("Inconsistent bindings for " + name) + } + delete keymap[keyname] + } + for (let prop in copy) keymap[prop] = copy[prop] + return keymap +} + +export function lookupKey(key, map, handle, context) { + map = getKeyMap(map) + let found = map.call ? map.call(key, context) : map[key] + if (found === false) return "nothing" + if (found === "...") return "multi" + if (found != null && handle(found)) return "handled" + + if (map.fallthrough) { + if (Object.prototype.toString.call(map.fallthrough) != "[object Array]") + return lookupKey(key, map.fallthrough, handle, context) + for (let i = 0; i < map.fallthrough.length; i++) { + let result = lookupKey(key, map.fallthrough[i], handle, context) + if (result) return result + } + } +} + +// Modifier key presses don't count as 'real' key presses for the +// purpose of keymap fallthrough. +export function isModifierKey(value) { + let name = typeof value == "string" ? value : keyNames[value.keyCode] + return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod" +} + +export function addModifierNames(name, event, noShift) { + let base = name + if (event.altKey && base != "Alt") name = "Alt-" + name + if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name + if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name + if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name + return name +} + +// Look up the name of a key as indicated by an event object. +export function keyName(event, noShift) { + if (presto && event.keyCode == 34 && event["char"]) return false + let name = keyNames[event.keyCode] + if (name == null || event.altGraphKey) return false + return addModifierNames(name, event, noShift) +} + +export function getKeyMap(val) { + return typeof val == "string" ? keyMap[val] : val +} diff --git a/modules/editor/codemirror/src/input/keynames.js b/modules/editor/codemirror/src/input/keynames.js @@ -0,0 +1,17 @@ +export let keyNames = { + 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", + 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", + 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", + 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", + 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete", + 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", + 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", + 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert" +} + +// Number keys +for (let i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i) +// Alphabetic keys +for (let i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i) +// Function keys +for (let i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i diff --git a/modules/editor/codemirror/src/line/highlight.min.js b/modules/editor/codemirror/src/line/highlight.min.js @@ -0,0 +1,284 @@ +import { countColumn } from "../util/misc.js" +import { copyState, innerMode, startState } from "../modes.js" +import StringStream from "../util/StringStream.js" + +import { getLine, lineNo } from "./utils_line.js" +import { clipPos } from "./pos.js" + +class SavedContext { + constructor(state, lookAhead) { + this.state = state + this.lookAhead = lookAhead + } +} + +class Context { + constructor(doc, state, line, lookAhead) { + this.state = state + this.doc = doc + this.line = line + this.maxLookAhead = lookAhead || 0 + this.baseTokens = null + this.baseTokenPos = 1 + } + + lookAhead(n) { + let line = this.doc.getLine(this.line + n) + if (line != null && n > this.maxLookAhead) this.maxLookAhead = n + return line + } + + baseToken(n) { + if (!this.baseTokens) return null + while (this.baseTokens[this.baseTokenPos] <= n) + this.baseTokenPos += 2 + let type = this.baseTokens[this.baseTokenPos + 1] + return {type: type && type.replace(/( |^)overlay .*/, ""), + size: this.baseTokens[this.baseTokenPos] - n} + } + + nextLine() { + this.line++ + if (this.maxLookAhead > 0) this.maxLookAhead-- + } + + static fromSaved(doc, saved, line) { + if (saved instanceof SavedContext) + return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) + else + return new Context(doc, copyState(doc.mode, saved), line) + } + + save(copy) { + let state = copy !== false ? copyState(this.doc.mode, this.state) : this.state + return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state + } +} + + +// Compute a style array (an array starting with a mode generation +// -- for invalidation -- followed by pairs of end positions and +// style strings), which is used to highlight the tokens on the +// line. +export function highlightLine(cm, line, context, forceToEnd) { + // A styles array always starts with a number identifying the + // mode/overlays that it is based on (for easy invalidation). + let st = [cm.state.modeGen], lineClasses = {} + // Compute the base array of styles + runMode(cm, line.text, cm.doc.mode, context, (end, style) => st.push(end, style), + lineClasses, forceToEnd) + let state = context.state + + // Run overlays, adjust style array. + for (let o = 0; o < cm.state.overlays.length; ++o) { + context.baseTokens = st + let overlay = cm.state.overlays[o], i = 1, at = 0 + context.state = true + runMode(cm, line.text, overlay.mode, context, (end, style) => { + let start = i + // Ensure there's a token end at the current position, and that i points at it + while (at < end) { + let i_end = st[i] + if (i_end > end) + st.splice(i, 1, end, st[i+1], i_end) + i += 2 + at = Math.min(end, i_end) + } + if (!style) return + if (overlay.opaque) { + st.splice(start, i - start, end, "overlay " + style) + i = start + 2 + } else { + for (; start < i; start += 2) { + let cur = st[start+1] + st[start+1] = (cur ? cur + " " : "") + "overlay " + style + } + } + }, lineClasses) + context.state = state + context.baseTokens = null + context.baseTokenPos = 1 + } + + return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null} +} + +export function getLineStyles(cm, line, updateFrontier) { + if (!line.styles || line.styles[0] != cm.state.modeGen) { + let context = getContextBefore(cm, lineNo(line)) + let resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state) + let result = highlightLine(cm, line, context) + if (resetState) context.state = resetState + line.stateAfter = context.save(!resetState) + line.styles = result.styles + if (result.classes) line.styleClasses = result.classes + else if (line.styleClasses) line.styleClasses = null + if (updateFrontier === cm.doc.highlightFrontier) + cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier) + } + return line.styles +} + +export function getContextBefore(cm, n, precise) { + let doc = cm.doc, display = cm.display + if (!doc.mode.startState) return new Context(doc, true, n) + let start = findStartLine(cm, n, precise) + let saved = start > doc.first && getLine(doc, start - 1).stateAfter + let context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start) + + doc.iter(start, n, line => { + processLine(cm, line.text, context) + let pos = context.line + line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null + context.nextLine() + }) + if (precise) doc.modeFrontier = context.line + return context +} + +// Lightweight form of highlight -- proceed over this line and +// update state, but don't save a style array. Used for lines that +// aren't currently visible. +export function processLine(cm, text, context, startAt) { + let mode = cm.doc.mode + let stream = new StringStream(text, cm.options.tabSize, context) + stream.start = stream.pos = startAt || 0 + if (text == "") callBlankLine(mode, context.state) + while (!stream.eol()) { + readToken(mode, stream, context.state) + stream.start = stream.pos + } +} + +function callBlankLine(mode, state) { + if (mode.blankLine) return mode.blankLine(state) + if (!mode.innerMode) return + let inner = innerMode(mode, state) + if (inner.mode.blankLine) return inner.mode.blankLine(inner.state) +} + +export function readToken(mode, stream, state, inner) { + for (let i = 0; i < 10; i++) { + if (inner) inner[0] = innerMode(mode, state).mode + let style = mode.token(stream, state) + if (stream.pos > stream.start) return style + } + throw new Error("Mode " + mode.name + " failed to advance stream.") +} + +class Token { + constructor(stream, type, state) { + this.start = stream.start; this.end = stream.pos + this.string = stream.current() + this.type = type || null + this.state = state + } +} + +// Utility for getTokenAt and getLineTokens +export function takeToken(cm, pos, precise, asArray) { + let doc = cm.doc, mode = doc.mode, style + pos = clipPos(doc, pos) + let line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise) + let stream = new StringStream(line.text, cm.options.tabSize, context), tokens + if (asArray) tokens = [] + while ((asArray || stream.pos < pos.ch) && !stream.eol()) { + stream.start = stream.pos + style = readToken(mode, stream, context.state) + if (asArray) tokens.push(new Token(stream, style, copyState(doc.mode, context.state))) + } + return asArray ? tokens : new Token(stream, style, context.state) +} + +function extractLineClasses(type, output) { + if (type) for (;;) { + let lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/) + if (!lineClass) break + type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length) + let prop = lineClass[1] ? "bgClass" : "textClass" + if (output[prop] == null) + output[prop] = lineClass[2] + else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop])) + output[prop] += " " + lineClass[2] + } + return type +} + +// Run the given mode's parser over a line, calling f for each token. +function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) { + let flattenSpans = mode.flattenSpans + if (flattenSpans == null) flattenSpans = cm.options.flattenSpans + let curStart = 0, curStyle = null + let stream = new StringStream(text, cm.options.tabSize, context), style + let inner = cm.options.addModeClass && [null] + if (text == "") extractLineClasses(callBlankLine(mode, context.state), lineClasses) + while (!stream.eol()) { + if (stream.pos > cm.options.maxHighlightLength) { + flattenSpans = false + if (forceToEnd) processLine(cm, text, context, stream.pos) + stream.pos = text.length + style = null + } else { + style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses) + } + if (inner) { + let mName = inner[0].name + if (mName) style = "m-" + (style ? mName + " " + style : mName) + } + if (!flattenSpans || curStyle != style) { + while (curStart < stream.start) { + curStart = Math.min(stream.start, curStart + 5000) + f(curStart, curStyle) + } + curStyle = style + } + stream.start = stream.pos + } + while (curStart < stream.pos) { + // Webkit seems to refuse to render text nodes longer than 57444 + // characters, and returns inaccurate measurements in nodes + // starting around 5000 chars. + let pos = Math.min(stream.pos, curStart + 5000) + f(pos, curStyle) + curStart = pos + } +} + +// Finds the line to start with when starting a parse. Tries to +// find a line with a stateAfter, so that it can start with a +// valid state. If that fails, it returns the line with the +// smallest indentation, which tends to need the least context to +// parse correctly. +function findStartLine(cm, n, precise) { + let minindent, minline, doc = cm.doc + let lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100) + for (let search = n; search > lim; --search) { + if (search <= doc.first) return doc.first + let line = getLine(doc, search - 1), after = line.stateAfter + if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier)) + return search + let indented = countColumn(line.text, null, cm.options.tabSize) + if (minline == null || minindent > indented) { + minline = search - 1 + minindent = indented + } + } + return minline +} + +export function retreatFrontier(doc, n) { + doc.modeFrontier = Math.min(doc.modeFrontier, n) + if (doc.highlightFrontier < n - 10) return + let start = doc.first + for (let line = n - 1; line > start; line--) { + let saved = getLine(doc, line).stateAfter + // change is on 3 + // state on line 1 looked ahead 2 -- so saw 3 + // test 1 + 2 < 3 should cover this + if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) { + start = line + 1 + break + } + } + doc.highlightFrontier = Math.min(doc.highlightFrontier, start) +} diff --git a/modules/editor/codemirror/src/line/saw_special_spans.min.js b/modules/editor/codemirror/src/line/saw_special_spans.min.js @@ -0,0 +1,10 @@ +// Optimize some code when these features are not used. +export let sawReadOnlySpans = false, sawCollapsedSpans = false + +export function seeReadOnlySpans() { + sawReadOnlySpans = true +} + +export function seeCollapsedSpans() { + sawCollapsedSpans = true +} diff --git a/modules/editor/codemirror/src/model/change_measurement.min.js b/modules/editor/codemirror/src/model/change_measurement.min.js @@ -0,0 +1,61 @@ +import { cmp, Pos } from "../line/pos.js" +import { lst } from "../util/misc.js" + +import { normalizeSelection, Range, Selection } from "./selection.js" + +// Compute the position of the end of a change (its 'to' property +// refers to the pre-change end). +export function changeEnd(change) { + if (!change.text) return change.to + return Pos(change.from.line + change.text.length - 1, + lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)) +} + +// Adjust a position to refer to the post-change position of the +// same text, or the end of the change if the change covers it. +function adjustForChange(pos, change) { + if (cmp(pos, change.from) < 0) return pos + if (cmp(pos, change.to) <= 0) return changeEnd(change) + + let line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch + if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch + return Pos(line, ch) +} + +export function computeSelAfterChange(doc, change) { + let out = [] + for (let i = 0; i < doc.sel.ranges.length; i++) { + let range = doc.sel.ranges[i] + out.push(new Range(adjustForChange(range.anchor, change), + adjustForChange(range.head, change))) + } + return normalizeSelection(out, doc.sel.primIndex) +} + +function offsetPos(pos, old, nw) { + if (pos.line == old.line) + return Pos(nw.line, pos.ch - old.ch + nw.ch) + else + return Pos(nw.line + (pos.line - old.line), pos.ch) +} + +// Used by replaceSelections to allow moving the selection to the +// start or around the replaced test. Hint may be "start" or "around". +export function computeReplacedSel(doc, changes, hint) { + let out = [] + let oldPrev = Pos(doc.first, 0), newPrev = oldPrev + for (let i = 0; i < changes.length; i++) { + let change = changes[i] + let from = offsetPos(change.from, oldPrev, newPrev) + let to = offsetPos(changeEnd(change), oldPrev, newPrev) + oldPrev = change.to + newPrev = to + if (hint == "around") { + let 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) +} diff --git a/modules/editor/codemirror/src/model/mark_text.min.js b/modules/editor/codemirror/src/model/mark_text.min.js @@ -0,0 +1,292 @@ +import { eltP } from "../util/dom.js" +import { eventMixin, hasHandler, on } from "../util/event.js" +import { endOperation, operation, runInOp, startOperation } from "../display/operations.js" +import { clipPos, cmp, Pos } from "../line/pos.js" +import { lineNo, updateLineHeight } from "../line/utils_line.js" +import { clearLineMeasurementCacheFor, findViewForLine, textHeight } from "../measurement/position_measurement.js" +import { seeReadOnlySpans, seeCollapsedSpans } from "../line/saw_special_spans.js" +import { addMarkedSpan, conflictingCollapsedRange, getMarkedSpanFor, lineIsHidden, lineLength, MarkedSpan, removeMarkedSpan, visualLine } from "../line/spans.js" +import { copyObj, indexOf, lst } from "../util/misc.js" +import { signalLater } from "../util/operation_group.js" +import { widgetHeight } from "../measurement/widgets.js" +import { regChange, regLineChange } from "../display/view_tracking.js" + +import { linkedDocs } from "./document_data.js" +import { addChangeToHistory } from "./history.js" +import { reCheckSelection } from "./selection_updates.js" + +// TEXTMARKERS + +// Created with markText and setBookmark methods. A TextMarker is a +// handle that can be used to clear or find a marked position in the +// document. Line objects hold arrays (markedSpans) containing +// {from, to, marker} object pointing to such marker objects, and +// indicating that such a marker is present on that line. Multiple +// lines may point to the same marker when it spans across lines. +// The spans will have null for their from/to properties when the +// marker continues beyond the start/end of the line. Markers have +// links back to the lines they currently touch. + +// Collapsed markers have unique ids, in order to be able to order +// them, which is needed for uniquely determining an outer marker +// when they overlap (they may nest, but not partially overlap). +let nextMarkerId = 0 + +export class TextMarker { + constructor(doc, type) { + this.lines = [] + this.type = type + this.doc = doc + this.id = ++nextMarkerId + } + + // Clear the marker. + clear() { + if (this.explicitlyCleared) return + let cm = this.doc.cm, withOp = cm && !cm.curOp + if (withOp) startOperation(cm) + if (hasHandler(this, "clear")) { + let found = this.find() + if (found) signalLater(this, "clear", found.from, found.to) + } + let min = null, max = null + for (let i = 0; i < this.lines.length; ++i) { + let line = this.lines[i] + let span = getMarkedSpanFor(line.markedSpans, this) + if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text") + else if (cm) { + if (span.to != null) max = lineNo(line) + if (span.from != null) min = lineNo(line) + } + line.markedSpans = removeMarkedSpan(line.markedSpans, span) + if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm) + updateLineHeight(line, textHeight(cm.display)) + } + if (cm && this.collapsed && !cm.options.lineWrapping) for (let i = 0; i < this.lines.length; ++i) { + let visual = visualLine(this.lines[i]), len = lineLength(visual) + if (len > cm.display.maxLineLength) { + cm.display.maxLine = visual + cm.display.maxLineLength = len + cm.display.maxLineChanged = true + } + } + + if (min != null && cm && this.collapsed) regChange(cm, min, max + 1) + this.lines.length = 0 + this.explicitlyCleared = true + if (this.atomic && this.doc.cantEdit) { + this.doc.cantEdit = false + if (cm) reCheckSelection(cm.doc) + } + if (cm) signalLater(cm, "markerCleared", cm, this, min, max) + if (withOp) endOperation(cm) + if (this.parent) this.parent.clear() + } + + // Find the position of the marker in the document. Returns a {from, + // to} object by default. Side can be passed to get a specific side + // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the + // Pos objects returned contain a line object, rather than a line + // number (used to prevent looking up the same line twice). + find(side, lineObj) { + if (side == null && this.type == "bookmark") side = 1 + let from, to + for (let i = 0; i < this.lines.length; ++i) { + let line = this.lines[i] + let span = getMarkedSpanFor(line.markedSpans, this) + if (span.from != null) { + from = Pos(lineObj ? line : lineNo(line), span.from) + if (side == -1) return from + } + if (span.to != null) { + to = Pos(lineObj ? line : lineNo(line), span.to) + if (side == 1) return to + } + } + return from && {from: from, to: to} + } + + // Signals that the marker's widget changed, and surrounding layout + // should be recomputed. + changed() { + let pos = this.find(-1, true), widget = this, cm = this.doc.cm + if (!pos || !cm) return + runInOp(cm, () => { + let line = pos.line, lineN = lineNo(pos.line) + let view = findViewForLine(cm, lineN) + if (view) { + clearLineMeasurementCacheFor(view) + cm.curOp.selectionChanged = cm.curOp.forceUpdate = true + } + cm.curOp.updateMaxLine = true + if (!lineIsHidden(widget.doc, line) && widget.height != null) { + let oldHeight = widget.height + widget.height = null + let dHeight = widgetHeight(widget) - oldHeight + if (dHeight) + updateLineHeight(line, line.height + dHeight) + } + signalLater(cm, "markerChanged", cm, this) + }) + } + + attachLine(line) { + if (!this.lines.length && this.doc.cm) { + let op = this.doc.cm.curOp + if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) + (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this) + } + this.lines.push(line) + } + + detachLine(line) { + this.lines.splice(indexOf(this.lines, line), 1) + if (!this.lines.length && this.doc.cm) { + let op = this.doc.cm.curOp + ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this) + } + } +} +eventMixin(TextMarker) + +// Create a marker, wire it up to the right lines, and +export function markText(doc, from, to, options, type) { + // Shared markers (across linked documents) are handled separately + // (markTextShared will call out to this again, once per + // document). + if (options && options.shared) return markTextShared(doc, from, to, options, type) + // Ensure we are in an operation. + if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type) + + let marker = new TextMarker(doc, type), diff = cmp(from, to) + if (options) copyObj(options, marker, false) + // Don't connect empty markers unless clearWhenEmpty is false + if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) + return marker + if (marker.replacedWith) { + // Showing up as a widget implies collapsed (widget replaces text) + marker.collapsed = true + marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget") + if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true") + if (options.insertLeft) marker.widgetNode.insertLeft = true + } + if (marker.collapsed) { + if (conflictingCollapsedRange(doc, from.line, from, to, marker) || + from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) + throw new Error("Inserting collapsed marker partially overlapping an existing one") + seeCollapsedSpans() + } + + if (marker.addToHistory) + addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN) + + let curLine = from.line, cm = doc.cm, updateMaxLine + doc.iter(curLine, to.line + 1, line => { + if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) + updateMaxLine = true + if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0) + addMarkedSpan(line, new MarkedSpan(marker, + curLine == from.line ? from.ch : null, + curLine == to.line ? to.ch : null)) + ++curLine + }) + // lineIsHidden depends on the presence of the spans, so needs a second pass + if (marker.collapsed) doc.iter(from.line, to.line + 1, line => { + if (lineIsHidden(doc, line)) updateLineHeight(line, 0) + }) + + if (marker.clearOnEnter) on(marker, "beforeCursorEnter", () => marker.clear()) + + if (marker.readOnly) { + seeReadOnlySpans() + if (doc.history.done.length || doc.history.undone.length) + doc.clearHistory() + } + if (marker.collapsed) { + marker.id = ++nextMarkerId + marker.atomic = true + } + if (cm) { + // Sync editor state + if (updateMaxLine) cm.curOp.updateMaxLine = true + if (marker.collapsed) + regChange(cm, from.line, to.line + 1) + else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css) + for (let i = from.line; i <= to.line; i++) regLineChange(cm, i, "text") + if (marker.atomic) reCheckSelection(cm.doc) + signalLater(cm, "markerAdded", cm, marker) + } + return marker +} + +// SHARED TEXTMARKERS + +// A shared marker spans multiple linked documents. It is +// implemented as a meta-marker-object controlling multiple normal +// markers. +export class SharedTextMarker { + constructor(markers, primary) { + this.markers = markers + this.primary = primary + for (let i = 0; i < markers.length; ++i) + markers[i].parent = this + } + + clear() { + if (this.explicitlyCleared) return + this.explicitlyCleared = true + for (let i = 0; i < this.markers.length; ++i) + this.markers[i].clear() + signalLater(this, "clear") + } + + find(side, lineObj) { + return this.primary.find(side, lineObj) + } +} +eventMixin(SharedTextMarker) + +function markTextShared(doc, from, to, options, type) { + options = copyObj(options) + options.shared = false + let markers = [markText(doc, from, to, options, type)], primary = markers[0] + let widget = options.widgetNode + linkedDocs(doc, doc => { + if (widget) options.widgetNode = widget.cloneNode(true) + markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)) + for (let i = 0; i < doc.linked.length; ++i) + if (doc.linked[i].isParent) return + primary = lst(markers) + }) + return new SharedTextMarker(markers, primary) +} + +export function findSharedMarkers(doc) { + return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), m => m.parent) +} + +export function copySharedMarkers(doc, markers) { + for (let i = 0; i < markers.length; i++) { + let marker = markers[i], pos = marker.find() + let mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to) + if (cmp(mFrom, mTo)) { + let subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type) + marker.markers.push(subMark) + subMark.parent = marker + } + } +} + +export function detachSharedMarkers(markers) { + for (let i = 0; i < markers.length; i++) { + let marker = markers[i], linked = [marker.primary.doc] + linkedDocs(marker.primary.doc, d => linked.push(d)) + for (let j = 0; j < marker.markers.length; j++) { + let subMarker = marker.markers[j] + if (indexOf(linked, subMarker.doc) == -1) { + subMarker.parent = null + marker.markers.splice(j--, 1) + } + } + } +} diff --git a/modules/editor/codemirror/src/util/browser.js b/modules/editor/codemirror/src/util/browser.js @@ -0,0 +1,33 @@ +// Kludges for bugs and behavior differences that can't be feature +// detected are enabled based on userAgent etc sniffing. +let userAgent = navigator.userAgent +let platform = navigator.platform + +export let gecko = /gecko\/\d/i.test(userAgent) +let ie_upto10 = /MSIE \d/.test(userAgent) +let ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent) +let edge = /Edge\/(\d+)/.exec(userAgent) +export let ie = ie_upto10 || ie_11up || edge +export let ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]) +export let webkit = !edge && /WebKit\//.test(userAgent) +let qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent) +export let chrome = !edge && /Chrome\//.test(userAgent) +export let presto = /Opera\//.test(userAgent) +export let safari = /Apple Computer/.test(navigator.vendor) +export let mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent) +export let phantom = /PhantomJS/.test(userAgent) + +export let ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent) +export let android = /Android/.test(userAgent) +// This is woefully incomplete. Suggestions for alternative methods welcome. +export let mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent) +export let mac = ios || /Mac/.test(platform) +export let chromeOS = /\bCrOS\b/.test(userAgent) +export let windows = /win/i.test(platform) + +let presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/) +if (presto_version) presto_version = Number(presto_version[1]) +if (presto_version && presto_version >= 15) { presto = false; webkit = true } +// Some browsers use the wrong event properties to signal cmd/ctrl on OS X +export let flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)) +export let captureRightClick = gecko || (ie && ie_version >= 9) diff --git a/modules/editor/codemirror/src/util/event.min.js b/modules/editor/codemirror/src/util/event.min.js @@ -0,0 +1,103 @@ +import { mac } from "./browser.js" +import { indexOf } from "./misc.js" + +// EVENT HANDLING + +// Lightweight event framework. on/off also work on DOM nodes, +// registering native DOM handlers. + +const noHandlers = [] + +export let on = function(emitter, type, f) { + if (emitter.addEventListener) { + emitter.addEventListener(type, f, false) + } else if (emitter.attachEvent) { + emitter.attachEvent("on" + type, f) + } else { + let map = emitter._handlers || (emitter._handlers = {}) + map[type] = (map[type] || noHandlers).concat(f) + } +} + +export function getHandlers(emitter, type) { + return emitter._handlers && emitter._handlers[type] || noHandlers +} + +export function off(emitter, type, f) { + if (emitter.removeEventListener) { + emitter.removeEventListener(type, f, false) + } else if (emitter.detachEvent) { + emitter.detachEvent("on" + type, f) + } else { + let map = emitter._handlers, arr = map && map[type] + if (arr) { + let index = indexOf(arr, f) + if (index > -1) + map[type] = arr.slice(0, index).concat(arr.slice(index + 1)) + } + } +} + +export function signal(emitter, type /*, values...*/) { + let handlers = getHandlers(emitter, type) + if (!handlers.length) return + let args = Array.prototype.slice.call(arguments, 2) + for (let i = 0; i < handlers.length; ++i) handlers[i].apply(null, args) +} + +// The DOM events that CodeMirror handles can be overridden by +// registering a (non-DOM) handler on the editor for the event name, +// and preventDefault-ing the event in that handler. +export function signalDOMEvent(cm, e, override) { + if (typeof e == "string") + e = {type: e, preventDefault: function() { this.defaultPrevented = true }} + signal(cm, override || e.type, cm, e) + return e_defaultPrevented(e) || e.codemirrorIgnore +} + +export function signalCursorActivity(cm) { + let arr = cm._handlers && cm._handlers.cursorActivity + if (!arr) return + let set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []) + for (let i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1) + set.push(arr[i]) +} + +export function hasHandler(emitter, type) { + return getHandlers(emitter, type).length > 0 +} + +// Add on and off methods to a constructor's prototype, to make +// registering events on such objects more convenient. +export function eventMixin(ctor) { + ctor.prototype.on = function(type, f) {on(this, type, f)} + ctor.prototype.off = function(type, f) {off(this, type, f)} +} + +// Due to the fact that we still support jurassic IE versions, some +// compatibility wrappers are needed. + +export function e_preventDefault(e) { + if (e.preventDefault) e.preventDefault() + else e.returnValue = false +} +export function e_stopPropagation(e) { + if (e.stopPropagation) e.stopPropagation() + else e.cancelBubble = true +} +export function e_defaultPrevented(e) { + return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false +} +export function e_stop(e) {e_preventDefault(e); e_stopPropagation(e)} + +export function e_target(e) {return e.target || e.srcElement} +export function e_button(e) { + let b = e.which + if (b == null) { + if (e.button & 1) b = 1 + else if (e.button & 2) b = 3 + else if (e.button & 4) b = 2 + } + if (mac && e.ctrlKey && b == 1) b = 3 + return b +} diff --git a/modules/editor/codemirror/src/util/feature_detection.min.js b/modules/editor/codemirror/src/util/feature_detection.min.js @@ -0,0 +1,84 @@ +import { elt, range, removeChildren, removeChildrenAndAdd } from "./dom.js" +import { ie, ie_version } from "./browser.js" + +// Detect drag-and-drop +export let dragAndDrop = function() { + // There is *some* kind of drag-and-drop support in IE6-8, but I + // couldn't get it to work yet. + if (ie && ie_version < 9) return false + let div = elt('div') + return "draggable" in div || "dragDrop" in div +}() + +let zwspSupported +export function zeroWidthElement(measure) { + if (zwspSupported == null) { + let test = elt("span", "\u200b") + removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])) + if (measure.firstChild.offsetHeight != 0) + zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8) + } + let node = zwspSupported ? elt("span", "\u200b") : + elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px") + node.setAttribute("cm-text", "") + return node +} + +// Feature-detect IE's crummy client rect reporting for bidi text +let badBidiRects +export function hasBadBidiRects(measure) { + if (badBidiRects != null) return badBidiRects + let txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")) + let r0 = range(txt, 0, 1).getBoundingClientRect() + let r1 = range(txt, 1, 2).getBoundingClientRect() + removeChildren(measure) + if (!r0 || r0.left == r0.right) return false // Safari returns null in some cases (#2780) + return badBidiRects = (r1.right - r0.right < 3) +} + +// See if "".split is the broken IE version, if so, provide an +// alternative way to split lines. +export let splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? string => { + let pos = 0, result = [], l = string.length + while (pos <= l) { + let nl = string.indexOf("\n", pos) + if (nl == -1) nl = string.length + let line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl) + let 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 +} : string => string.split(/\r\n?|\n/) + +export let hasSelection = window.getSelection ? te => { + try { return te.selectionStart != te.selectionEnd } + catch(e) { return false } +} : te => { + let range + try {range = te.ownerDocument.selection.createRange()} + catch(e) {} + if (!range || range.parentElement() != te) return false + return range.compareEndPoints("StartToEnd", range) != 0 +} + +export let hasCopyEvent = (() => { + let e = elt("div") + if ("oncopy" in e) return true + e.setAttribute("oncopy", "return;") + return typeof e.oncopy == "function" +})() + +let badZoomedRects = null +export function hasBadZoomedRects(measure) { + if (badZoomedRects != null) return badZoomedRects + let node = removeChildrenAndAdd(measure, elt("span", "x")) + let normal = node.getBoundingClientRect() + let fromRange = range(node, 0, 1).getBoundingClientRect() + return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1 +} diff --git a/modules/editor/codemirror/test/contenteditable_test.js b/modules/editor/codemirror/test/contenteditable_test.js @@ -0,0 +1,110 @@ +(function() { + "use strict"; + + namespace = "contenteditable_"; + var Pos = CodeMirror.Pos + + function findTextNode(dom, text) { + if (dom instanceof CodeMirror) dom = dom.getInputField() + if (dom.nodeType == 1) { + for (var ch = dom.firstChild; ch; ch = ch.nextSibling) { + var found = findTextNode(ch, text) + if (found) return found + } + } else if (dom.nodeType == 3 && dom.nodeValue == text) { + return dom + } + } + + function lineElt(node) { + for (;;) { + var parent = node.parentNode + if (/CodeMirror-code/.test(parent.className)) return node + node = parent + } + } + + testCM("insert_text", function(cm) { + findTextNode(cm, "foobar").nodeValue = "foo bar" + cm.display.input.updateFromDOM() + eq(cm.getValue(), "foo bar") + }, {inputStyle: "contenteditable", value: "foobar"}) + + testCM("split_line", function(cm) { + cm.setSelection(Pos(2, 3)) + var node = findTextNode(cm, "foobar") + node.nodeValue = "foo" + var lineNode = lineElt(node) + lineNode.parentNode.insertBefore(document.createElement("pre"), lineNode.nextSibling).textContent = "bar" + cm.display.input.updateFromDOM() + eq(cm.getValue(), "one\ntwo\nfoo\nbar\nthree\nfour\n") + }, {inputStyle: "contenteditable", value: "one\ntwo\nfoobar\nthree\nfour\n"}) + + testCM("join_line", function(cm) { + cm.setSelection(Pos(2, 3)) + var node = findTextNode(cm, "foo") + node.nodeValue = "foobar" + var lineNode = lineElt(node) + lineNode.parentNode.removeChild(lineNode.nextSibling) + cm.display.input.updateFromDOM() + eq(cm.getValue(), "one\ntwo\nfoobar\nthree\nfour\n") + }, {inputStyle: "contenteditable", value: "one\ntwo\nfoo\nbar\nthree\nfour\n"}) + + testCM("delete_multiple", function(cm) { + cm.setSelection(Pos(1, 3), Pos(4, 0)) + var text = findTextNode(cm, "two"), startLine = lineElt(text) + for (var i = 0; i < 3; i++) + startLine.parentNode.removeChild(startLine.nextSibling) + text.nodeValue = "twothree" + cm.display.input.updateFromDOM() + eq(cm.getValue(), "one\ntwothree\nfour\n") + }, {inputStyle: "contenteditable", value: "one\ntwo\nfoo\nbar\nthree\nfour\n"}) + + testCM("ambiguous_diff_middle", function(cm) { + cm.setSelection(Pos(0, 2)) + findTextNode(cm, "baah").nodeValue = "baaah" + cm.display.input.updateFromDOM() + eqCharPos(cm.getCursor(), Pos(0, 3)) + }, {inputStyle: "contenteditable", value: "baah"}) + + testCM("ambiguous_diff_start", function(cm) { + cm.setSelection(Pos(0, 1)) + findTextNode(cm, "baah").nodeValue = "baaah" + cm.display.input.updateFromDOM() + eqCharPos(cm.getCursor(), Pos(0, 2)) + }, {inputStyle: "contenteditable", value: "baah"}) + + testCM("ambiguous_diff_end", function(cm) { + cm.setSelection(Pos(0, 3)) + findTextNode(cm, "baah").nodeValue = "baaah" + cm.display.input.updateFromDOM() + eqCharPos(cm.getCursor(), Pos(0, 4)) + }, {inputStyle: "contenteditable", value: "baah"}) + + testCM("force_redraw", function(cm) { + findTextNode(cm, "foo").parentNode.appendChild(document.createElement("hr")).className = "inserted" + cm.display.input.updateFromDOM() + eq(byClassName(cm.getInputField(), "inserted").length, 0) + }, {inputStyle: "contenteditable", value: "foo"}) + + testCM("type_on_empty_line", function(cm) { + cm.setSelection(Pos(1, 0)) + findTextNode(cm, "\u200b").nodeValue += "hello" + cm.display.input.updateFromDOM() + eq(cm.getValue(), "foo\nhello\nbar") + }, {inputStyle: "contenteditable", value: "foo\n\nbar"}) + + testCM("type_after_empty_line", function(cm) { + cm.setSelection(Pos(2, 0)) + findTextNode(cm, "bar").nodeValue = "hellobar" + cm.display.input.updateFromDOM() + eq(cm.getValue(), "foo\n\nhellobar") + }, {inputStyle: "contenteditable", value: "foo\n\nbar"}) + + testCM("type_before_empty_line", function(cm) { + cm.setSelection(Pos(0, 3)) + findTextNode(cm, "foo").nodeValue = "foohello" + cm.display.input.updateFromDOM() + eq(cm.getValue(), "foohello\n\nbar") + }, {inputStyle: "contenteditable", value: "foo\n\nbar"}) +})(); diff --git a/modules/editor/codemirror/test/contenteditable_test.min.js b/modules/editor/codemirror/test/contenteditable_test.min.js @@ -0,0 +1,110 @@ +(function() { + "use strict"; + + namespace = "contenteditable_"; + var Pos = CodeMirror.Pos + + function findTextNode(dom, text) { + if (dom instanceof CodeMirror) dom = dom.getInputField() + if (dom.nodeType == 1) { + for (var ch = dom.firstChild; ch; ch = ch.nextSibling) { + var found = findTextNode(ch, text) + if (found) return found + } + } else if (dom.nodeType == 3 && dom.nodeValue == text) { + return dom + } + } + + function lineElt(node) { + for (;;) { + var parent = node.parentNode + if (/CodeMirror-code/.test(parent.className)) return node + node = parent + } + } + + testCM("insert_text", function(cm) { + findTextNode(cm, "foobar").nodeValue = "foo bar" + cm.display.input.updateFromDOM() + eq(cm.getValue(), "foo bar") + }, {inputStyle: "contenteditable", value: "foobar"}) + + testCM("split_line", function(cm) { + cm.setSelection(Pos(2, 3)) + var node = findTextNode(cm, "foobar") + node.nodeValue = "foo" + var lineNode = lineElt(node) + lineNode.parentNode.insertBefore(document.createElement("pre"), lineNode.nextSibling).textContent = "bar" + cm.display.input.updateFromDOM() + eq(cm.getValue(), "one\ntwo\nfoo\nbar\nthree\nfour\n") + }, {inputStyle: "contenteditable", value: "one\ntwo\nfoobar\nthree\nfour\n"}) + + testCM("join_line", function(cm) { + cm.setSelection(Pos(2, 3)) + var node = findTextNode(cm, "foo") + node.nodeValue = "foobar" + var lineNode = lineElt(node) + lineNode.parentNode.removeChild(lineNode.nextSibling) + cm.display.input.updateFromDOM() + eq(cm.getValue(), "one\ntwo\nfoobar\nthree\nfour\n") + }, {inputStyle: "contenteditable", value: "one\ntwo\nfoo\nbar\nthree\nfour\n"}) + + testCM("delete_multiple", function(cm) { + cm.setSelection(Pos(1, 3), Pos(4, 0)) + var text = findTextNode(cm, "two"), startLine = lineElt(text) + for (var i = 0; i < 3; i++) + startLine.parentNode.removeChild(startLine.nextSibling) + text.nodeValue = "twothree" + cm.display.input.updateFromDOM() + eq(cm.getValue(), "one\ntwothree\nfour\n") + }, {inputStyle: "contenteditable", value: "one\ntwo\nfoo\nbar\nthree\nfour\n"}) + + testCM("ambiguous_diff_middle", function(cm) { + cm.setSelection(Pos(0, 2)) + findTextNode(cm, "baah").nodeValue = "baaah" + cm.display.input.updateFromDOM() + eqCharPos(cm.getCursor(), Pos(0, 3)) + }, {inputStyle: "contenteditable", value: "baah"}) + + testCM("ambiguous_diff_start", function(cm) { + cm.setSelection(Pos(0, 1)) + findTextNode(cm, "baah").nodeValue = "baaah" + cm.display.input.updateFromDOM() + eqCharPos(cm.getCursor(), Pos(0, 2)) + }, {inputStyle: "contenteditable", value: "baah"}) + + testCM("ambiguous_diff_end", function(cm) { + cm.setSelection(Pos(0, 3)) + findTextNode(cm, "baah").nodeValue = "baaah" + cm.display.input.updateFromDOM() + eqCharPos(cm.getCursor(), Pos(0, 4)) + }, {inputStyle: "contenteditable", value: "baah"}) + + testCM("force_redraw", function(cm) { + findTextNode(cm, "foo").parentNode.appendChild(document.createElement("hr")).className = "inserted" + cm.display.input.updateFromDOM() + eq(byClassName(cm.getInputField(), "inserted").length, 0) + }, {inputStyle: "contenteditable", value: "foo"}) + + testCM("type_on_empty_line", function(cm) { + cm.setSelection(Pos(1, 0)) + findTextNode(cm, "\u200b").nodeValue += "hello" + cm.display.input.updateFromDOM() + eq(cm.getValue(), "foo\nhello\nbar") + }, {inputStyle: "contenteditable", value: "foo\n\nbar"}) + + testCM("type_after_empty_line", function(cm) { + cm.setSelection(Pos(2, 0)) + findTextNode(cm, "bar").nodeValue = "hellobar" + cm.display.input.updateFromDOM() + eq(cm.getValue(), "foo\n\nhellobar") + }, {inputStyle: "contenteditable", value: "foo\n\nbar"}) + + testCM("type_before_empty_line", function(cm) { + cm.setSelection(Pos(0, 3)) + findTextNode(cm, "foo").nodeValue = "foohello" + cm.display.input.updateFromDOM() + eq(cm.getValue(), "foohello\n\nbar") + }, {inputStyle: "contenteditable", value: "foo\n\nbar"}) +})(); diff --git a/modules/editor/codemirror/test/doc_test.js b/modules/editor/codemirror/test/doc_test.js @@ -0,0 +1,371 @@ +(function() { + // A minilanguage for instantiating linked CodeMirror instances and Docs + function instantiateSpec(spec, place, opts) { + var names = {}, pos = 0, l = spec.length, editors = []; + while (spec) { + var m = spec.match(/^(\w+)(\*?)(?:='([^\']*)'|<(~?)(\w+)(?:\/(\d+)-(\d+))?)\s*/); + var name = m[1], isDoc = m[2], cur; + if (m[3]) { + cur = isDoc ? CodeMirror.Doc(m[3]) : CodeMirror(place, clone(opts, {value: m[3]})); + } else { + var other = m[5]; + if (!names.hasOwnProperty(other)) { + names[other] = editors.length; + editors.push(CodeMirror(place, opts)); + } + var doc = editors[names[other]].linkedDoc({ + sharedHist: !m[4], + from: m[6] ? Number(m[6]) : null, + to: m[7] ? Number(m[7]) : null + }); + cur = isDoc ? doc : CodeMirror(place, clone(opts, {value: doc})); + } + names[name] = editors.length; + editors.push(cur); + spec = spec.slice(m[0].length); + } + return editors; + } + + function clone(obj, props) { + if (!obj) return; + clone.prototype = obj; + var inst = new clone(); + if (props) for (var n in props) if (props.hasOwnProperty(n)) + inst[n] = props[n]; + return inst; + } + + function eqAll(val) { + var end = arguments.length, msg = null; + if (typeof arguments[end-1] == "string") + msg = arguments[--end]; + if (i == end) throw new Error("No editors provided to eqAll"); + for (var i = 1; i < end; ++i) + eq(arguments[i].getValue(), val, msg) + } + + function testDoc(name, spec, run, opts, expectFail) { + if (!opts) opts = {}; + + return test("doc_" + name, function() { + var place = document.getElementById("testground"); + var editors = instantiateSpec(spec, place, opts); + var successful = false; + + try { + run.apply(null, editors); + successful = true; + } finally { + if (!successful || verbose) { + place.style.visibility = "visible"; + } else { + for (var i = 0; i < editors.length; ++i) + if (editors[i] instanceof CodeMirror) + place.removeChild(editors[i].getWrapperElement()); + } + } + }, expectFail); + } + + var ie_lt8 = /MSIE [1-7]\b/.test(navigator.userAgent); + + function testBasic(a, b) { + eqAll("x", a, b); + a.setValue("hey"); + eqAll("hey", a, b); + b.setValue("wow"); + eqAll("wow", a, b); + a.replaceRange("u\nv\nw", Pos(0, 3)); + b.replaceRange("i", Pos(0, 4)); + b.replaceRange("j", Pos(2, 1)); + eqAll("wowui\nv\nwj", a, b); + } + + testDoc("basic", "A='x' B<A", testBasic); + testDoc("basicSeparate", "A='x' B<~A", testBasic); + + testDoc("sharedHist", "A='ab\ncd\nef' B<A", function(a, b) { + a.replaceRange("x", Pos(0)); + b.replaceRange("y", Pos(1)); + a.replaceRange("z", Pos(2)); + eqAll("abx\ncdy\nefz", a, b); + a.undo(); + a.undo(); + eqAll("abx\ncd\nef", a, b); + a.redo(); + eqAll("abx\ncdy\nef", a, b); + b.redo(); + eqAll("abx\ncdy\nefz", a, b); + a.undo(); b.undo(); a.undo(); a.undo(); + eqAll("ab\ncd\nef", a, b); + }, null, ie_lt8); + + testDoc("undoIntact", "A='ab\ncd\nef' B<~A", function(a, b) { + a.replaceRange("x", Pos(0)); + b.replaceRange("y", Pos(1)); + a.replaceRange("z", Pos(2)); + a.replaceRange("q", Pos(0)); + eqAll("abxq\ncdy\nefz", a, b); + a.undo(); + a.undo(); + eqAll("abx\ncdy\nef", a, b); + b.undo(); + eqAll("abx\ncd\nef", a, b); + a.redo(); + eqAll("abx\ncd\nefz", a, b); + a.redo(); + eqAll("abxq\ncd\nefz", a, b); + a.undo(); a.undo(); a.undo(); a.undo(); + eqAll("ab\ncd\nef", a, b); + b.redo(); + eqAll("ab\ncdy\nef", a, b); + }); + + testDoc("undoConflict", "A='ab\ncd\nef' B<~A", function(a, b) { + a.replaceRange("x", Pos(0)); + a.replaceRange("z", Pos(2)); + // This should clear the first undo event in a, but not the second + b.replaceRange("y", Pos(0)); + a.undo(); a.undo(); + eqAll("abxy\ncd\nef", a, b); + a.replaceRange("u", Pos(2)); + a.replaceRange("v", Pos(0)); + // This should clear both events in a + b.replaceRange("w", Pos(0)); + a.undo(); a.undo(); + eqAll("abxyvw\ncd\nefu", a, b); + }); + + testDoc("doubleRebase", "A='ab\ncd\nef\ng' B<~A C<B", function(a, b, c) { + c.replaceRange("u", Pos(3)); + a.replaceRange("", Pos(0, 0), Pos(1, 0)); + c.undo(); + eqAll("cd\nef\ng", a, b, c); + }); + + testDoc("undoUpdate", "A='ab\ncd\nef' B<~A", function(a, b) { + a.replaceRange("x", Pos(2)); + b.replaceRange("u\nv\nw\n", Pos(0, 0)); + a.undo(); + eqAll("u\nv\nw\nab\ncd\nef", a, b); + a.redo(); + eqAll("u\nv\nw\nab\ncd\nefx", a, b); + a.undo(); + eqAll("u\nv\nw\nab\ncd\nef", a, b); + b.undo(); + a.redo(); + eqAll("ab\ncd\nefx", a, b); + a.undo(); + eqAll("ab\ncd\nef", a, b); + }); + + testDoc("undoKeepRanges", "A='abcdefg' B<A", function(a, b) { + var m = a.markText(Pos(0, 1), Pos(0, 3), {className: "foo"}); + b.replaceRange("x", Pos(0, 0)); + eqCharPos(m.find().from, Pos(0, 2)); + b.replaceRange("yzzy", Pos(0, 1), Pos(0)); + eq(m.find(), null); + b.undo(); + eqCharPos(m.find().from, Pos(0, 2)); + b.undo(); + eqCharPos(m.find().from, Pos(0, 1)); + }); + + testDoc("longChain", "A='uv' B<A C<B D<C", function(a, b, c, d) { + a.replaceSelection("X"); + eqAll("Xuv", a, b, c, d); + d.replaceRange("Y", Pos(0)); + eqAll("XuvY", a, b, c, d); + }); + + testDoc("broadCast", "B<A C<A D<A E<A", function(a, b, c, d, e) { + b.setValue("uu"); + eqAll("uu", a, b, c, d, e); + a.replaceRange("v", Pos(0, 1)); + eqAll("uvu", a, b, c, d, e); + }); + + // A and B share a history, C and D share a separate one + testDoc("islands", "A='x\ny\nz' B<A C<~A D<C", function(a, b, c, d) { + a.replaceRange("u", Pos(0)); + d.replaceRange("v", Pos(2)); + b.undo(); + eqAll("x\ny\nzv", a, b, c, d); + c.undo(); + eqAll("x\ny\nz", a, b, c, d); + a.redo(); + eqAll("xu\ny\nz", a, b, c, d); + d.redo(); + eqAll("xu\ny\nzv", a, b, c, d); + }); + + testDoc("unlink", "B<A C<A D<B", function(a, b, c, d) { + a.setValue("hi"); + b.unlinkDoc(a); + d.setValue("aye"); + eqAll("hi", a, c); + eqAll("aye", b, d); + a.setValue("oo"); + eqAll("oo", a, c); + eqAll("aye", b, d); + }); + + testDoc("bareDoc", "A*='foo' B*<A C<B", function(a, b, c) { + is(a instanceof CodeMirror.Doc); + is(b instanceof CodeMirror.Doc); + is(c instanceof CodeMirror); + eqAll("foo", a, b, c); + a.replaceRange("hey", Pos(0, 0), Pos(0)); + c.replaceRange("!", Pos(0)); + eqAll("hey!", a, b, c); + b.unlinkDoc(a); + b.setValue("x"); + eqAll("x", b, c); + eqAll("hey!", a); + }); + + testDoc("swapDoc", "A='a' B*='b' C<A", function(a, b, c) { + var d = a.swapDoc(b); + d.setValue("x"); + eqAll("x", c, d); + eqAll("b", a, b); + }); + + testDoc("docKeepsScroll", "A='x' B*='y'", function(a, b) { + addDoc(a, 200, 200); + a.scrollIntoView(Pos(199, 200)); + var c = a.swapDoc(b); + a.swapDoc(c); + var pos = a.getScrollInfo(); + is(pos.left > 0, "not at left"); + is(pos.top > 0, "not at top"); + }); + + testDoc("copyDoc", "A='u'", function(a) { + var copy = a.getDoc().copy(true); + a.setValue("foo"); + copy.setValue("bar"); + var old = a.swapDoc(copy); + eq(a.getValue(), "bar"); + a.undo(); + eq(a.getValue(), "u"); + a.swapDoc(old); + eq(a.getValue(), "foo"); + eq(old.historySize().undo, 1); + eq(old.copy(false).historySize().undo, 0); + }); + + testDoc("docKeepsMode", "A='1+1'", function(a) { + var other = CodeMirror.Doc("hi", "text/x-markdown"); + a.setOption("mode", "text/javascript"); + var old = a.swapDoc(other); + eq(a.getOption("mode"), "text/x-markdown"); + eq(a.getMode().name, "markdown"); + a.swapDoc(old); + eq(a.getOption("mode"), "text/javascript"); + eq(a.getMode().name, "javascript"); + }); + + testDoc("subview", "A='1\n2\n3\n4\n5' B<~A/1-3", function(a, b) { + eq(b.getValue(), "2\n3"); + eq(b.firstLine(), 1); + b.setCursor(Pos(4)); + eqCharPos(b.getCursor(), Pos(2, 1)); + a.replaceRange("-1\n0\n", Pos(0, 0)); + eq(b.firstLine(), 3); + eqCharPos(b.getCursor(), Pos(4, 1)); + a.undo(); + eqCharPos(b.getCursor(), Pos(2, 1)); + b.replaceRange("oyoy\n", Pos(2, 0)); + eq(a.getValue(), "1\n2\noyoy\n3\n4\n5"); + b.undo(); + eq(a.getValue(), "1\n2\n3\n4\n5"); + }); + + testDoc("subviewEditOnBoundary", "A='11\n22\n33\n44\n55' B<~A/1-4", function(a, b) { + a.replaceRange("x\nyy\nz", Pos(0, 1), Pos(2, 1)); + eq(b.firstLine(), 2); + eq(b.lineCount(), 2); + eq(b.getValue(), "z3\n44"); + a.replaceRange("q\nrr\ns", Pos(3, 1), Pos(4, 1)); + eq(b.firstLine(), 2); + eq(b.getValue(), "z3\n4q"); + eq(a.getValue(), "1x\nyy\nz3\n4q\nrr\ns5"); + a.execCommand("selectAll"); + a.replaceSelection("!"); + eqAll("!", a, b); + }); + + + testDoc("sharedMarker", "A='ab\ncd\nef\ngh' B<A C<~A/1-2", function(a, b, c) { + var mark = b.markText(Pos(0, 1), Pos(3, 1), + {className: "cm-searching", shared: true}); + var found = a.findMarksAt(Pos(0, 2)); + eq(found.length, 1); + eq(found[0], mark); + eq(c.findMarksAt(Pos(1, 1)).length, 1); + eqCharPos(mark.find().from, Pos(0, 1)); + eqCharPos(mark.find().to, Pos(3, 1)); + b.replaceRange("x\ny\n", Pos(0, 0)); + eqCharPos(mark.find().from, Pos(2, 1)); + eqCharPos(mark.find().to, Pos(5, 1)); + var cleared = 0; + CodeMirror.on(mark, "clear", function() {++cleared;}); + b.operation(function(){mark.clear();}); + eq(a.findMarksAt(Pos(3, 1)).length, 0); + eq(b.findMarksAt(Pos(3, 1)).length, 0); + eq(c.findMarksAt(Pos(3, 1)).length, 0); + eq(mark.find(), null); + eq(cleared, 1); + }); + + testDoc("sharedMarkerCopy", "A='abcde'", function(a) { + var shared = a.markText(Pos(0, 1), Pos(0, 3), {shared: true}); + var b = a.linkedDoc(); + var found = b.findMarksAt(Pos(0, 2)); + eq(found.length, 1); + eq(found[0], shared); + shared.clear(); + eq(b.findMarksAt(Pos(0, 2)), 0); + }); + + testDoc("sharedMarkerDetach", "A='abcde' B<A C<B", function(a, b, c) { + var shared = a.markText(Pos(0, 1), Pos(0, 3), {shared: true}); + a.unlinkDoc(b); + var inB = b.findMarksAt(Pos(0, 2)); + eq(inB.length, 1); + is(inB[0] != shared); + var inC = c.findMarksAt(Pos(0, 2)); + eq(inC.length, 1); + is(inC[0] != shared); + inC[0].clear(); + is(shared.find()); + }); + + testDoc("sharedBookmark", "A='ab\ncd\nef\ngh' B<A C<~A/1-2", function(a, b, c) { + var mark = b.setBookmark(Pos(1, 1), {shared: true}); + var found = a.findMarksAt(Pos(1, 1)); + eq(found.length, 1); + eq(found[0], mark); + eq(c.findMarksAt(Pos(1, 1)).length, 1); + eqCharPos(mark.find(), Pos(1, 1)); + b.replaceRange("x\ny\n", Pos(0, 0)); + eqCharPos(mark.find(), Pos(3, 1)); + var cleared = 0; + CodeMirror.on(mark, "clear", function() {++cleared;}); + b.operation(function() {mark.clear();}); + eq(a.findMarks(Pos(0, 0), Pos(5)).length, 0); + eq(b.findMarks(Pos(0, 0), Pos(5)).length, 0); + eq(c.findMarks(Pos(0, 0), Pos(5)).length, 0); + eq(mark.find(), null); + eq(cleared, 1); + }); + + testDoc("undoInSubview", "A='line 0\nline 1\nline 2\nline 3\nline 4' B<A/1-4", function(a, b) { + b.replaceRange("x", Pos(2, 0)); + a.undo(); + eq(a.getValue(), "line 0\nline 1\nline 2\nline 3\nline 4"); + eq(b.getValue(), "line 1\nline 2\nline 3"); + }); +})(); diff --git a/modules/editor/codemirror/test/emacs_test.min.js b/modules/editor/codemirror/test/emacs_test.min.js @@ -0,0 +1,149 @@ +(function() { + "use strict"; + + var Pos = CodeMirror.Pos; + namespace = "emacs_"; + + var eventCache = {}; + function fakeEvent(keyName) { + var event = eventCache[key]; + if (event) return event; + + var ctrl, shift, alt; + var key = keyName.replace(/\w+-/g, function(type) { + if (type == "Ctrl-") ctrl = true; + else if (type == "Alt-") alt = true; + else if (type == "Shift-") shift = true; + return ""; + }); + var code; + for (var c in CodeMirror.keyNames) + if (CodeMirror.keyNames[c] == key) { code = c; break; } + if (code == null) throw new Error("Unknown key: " + key); + + return eventCache[keyName] = { + type: "keydown", keyCode: code, ctrlKey: ctrl, shiftKey: shift, altKey: alt, + preventDefault: function(){}, stopPropagation: function(){} + }; + } + + function sim(name, start /*, actions... */) { + var keys = Array.prototype.slice.call(arguments, 2); + testCM(name, function(cm) { + for (var i = 0; i < keys.length; ++i) { + var cur = keys[i]; + if (cur instanceof Pos) cm.setCursor(cur); + else if (cur.call) cur(cm); + else cm.triggerOnKeyDown(fakeEvent(cur)); + } + }, {keyMap: "emacs", value: start, mode: "javascript"}); + } + + function at(line, ch, sticky) { return function(cm) { eqCursorPos(cm.getCursor(), Pos(line, ch, sticky)); }; } + function txt(str) { return function(cm) { eq(cm.getValue(), str); }; } + + sim("motionHSimple", "abc", "Ctrl-F", "Ctrl-F", "Ctrl-B", at(0, 1, "after")); + sim("motionHMulti", "abcde", + "Ctrl-4", "Ctrl-F", at(0, 4, "before"), "Ctrl--", "Ctrl-2", "Ctrl-F", at(0, 2, "after"), + "Ctrl-5", "Ctrl-B", at(0, 0, "after")); + + sim("motionHWord", "abc. def ghi", + "Alt-F", at(0, 3, "before"), "Alt-F", at(0, 8, "before"), + "Ctrl-B", "Alt-B", at(0, 5, "after"), "Alt-B", at(0, 0, "after")); + sim("motionHWordMulti", "abc. def ghi ", + "Ctrl-3", "Alt-F", at(0, 12, "before"), "Ctrl-2", "Alt-B", at(0, 5, "after"), + "Ctrl--", "Alt-B", at(0, 8, "before")); + + sim("motionVSimple", "a\nb\nc\n", "Ctrl-N", "Ctrl-N", "Ctrl-P", at(1, 0, "after")); + sim("motionVMulti", "a\nb\nc\nd\ne\n", + "Ctrl-2", "Ctrl-N", at(2, 0, "after"), "Ctrl-F", "Ctrl--", "Ctrl-N", at(1, 1, "before"), + "Ctrl--", "Ctrl-3", "Ctrl-P", at(4, 1, "before")); + + sim("killYank", "abc\ndef\nghi", + "Ctrl-F", "Ctrl-Space", "Ctrl-N", "Ctrl-N", "Ctrl-W", "Ctrl-E", "Ctrl-Y", + txt("ahibc\ndef\ng")); + sim("killRing", "abcdef", + "Ctrl-Space", "Ctrl-F", "Ctrl-W", "Ctrl-Space", "Ctrl-F", "Ctrl-W", + "Ctrl-Y", "Alt-Y", + txt("acdef")); + sim("copyYank", "abcd", + "Ctrl-Space", "Ctrl-E", "Alt-W", "Ctrl-Y", + txt("abcdabcd")); + + sim("killLineSimple", "foo\nbar", "Ctrl-F", "Ctrl-K", txt("f\nbar")); + sim("killLineEmptyLine", "foo\n \nbar", "Ctrl-N", "Ctrl-K", txt("foo\nbar")); + sim("killLineMulti", "foo\nbar\nbaz", + "Ctrl-F", "Ctrl-F", "Ctrl-K", "Ctrl-K", "Ctrl-K", "Ctrl-A", "Ctrl-Y", + txt("o\nbarfo\nbaz")); + + sim("moveByParagraph", "abc\ndef\n\n\nhij\nklm\n\n", + "Ctrl-F", "Ctrl-Down", at(2, 0), "Ctrl-Down", at(6, 0), + "Ctrl-N", "Ctrl-Up", at(3, 0), "Ctrl-Up", at(0, 0), + Pos(1, 2), "Ctrl-Down", at(2, 0), Pos(4, 2), "Ctrl-Up", at(3, 0)); + sim("moveByParagraphMulti", "abc\n\ndef\n\nhij\n\nklm", + "Ctrl-U", "2", "Ctrl-Down", at(3, 0), + "Shift-Alt-.", "Ctrl-3", "Ctrl-Up", at(1, 0)); + + sim("moveBySentence", "sentence one! sentence\ntwo\n\nparagraph two", + "Alt-E", at(0, 13), "Alt-E", at(1, 3), "Ctrl-F", "Alt-A", at(0, 13)); + + sim("moveByExpr", "function foo(a, b) {}", + "Ctrl-Alt-F", at(0, 8), "Ctrl-Alt-F", at(0, 12), "Ctrl-Alt-F", at(0, 18), + "Ctrl-Alt-B", at(0, 12), "Ctrl-Alt-B", at(0, 9)); + sim("moveByExprMulti", "foo bar baz bug", + "Ctrl-2", "Ctrl-Alt-F", at(0, 7), + "Ctrl--", "Ctrl-Alt-F", at(0, 4), + "Ctrl--", "Ctrl-2", "Ctrl-Alt-B", at(0, 11)); + sim("delExpr", "var x = [\n a,\n b\n c\n];", + Pos(0, 8), "Ctrl-Alt-K", txt("var x = ;"), "Ctrl-/", + Pos(4, 1), "Ctrl-Alt-Backspace", txt("var x = ;")); + sim("delExprMulti", "foo bar baz", + "Ctrl-2", "Ctrl-Alt-K", txt(" baz"), + "Ctrl-/", "Ctrl-E", "Ctrl-2", "Ctrl-Alt-Backspace", txt("foo ")); + + sim("justOneSpace", "hi bye ", + Pos(0, 4), "Alt-Space", txt("hi bye "), + Pos(0, 4), "Alt-Space", txt("hi b ye "), + "Ctrl-A", "Alt-Space", "Ctrl-E", "Alt-Space", txt(" hi b ye ")); + + sim("openLine", "foo bar", "Alt-F", "Ctrl-O", txt("foo\n bar")) + + sim("transposeChar", "abcd\ne", + "Ctrl-F", "Ctrl-T", "Ctrl-T", txt("bcad\ne"), at(0, 3), + "Ctrl-F", "Ctrl-T", "Ctrl-T", "Ctrl-T", txt("bcda\ne"), at(0, 4), + "Ctrl-F", "Ctrl-T", txt("bcde\na"), at(1, 1)); + + sim("manipWordCase", "foo BAR bAZ", + "Alt-C", "Alt-L", "Alt-U", txt("Foo bar BAZ"), + "Ctrl-A", "Alt-U", "Alt-L", "Alt-C", txt("FOO bar Baz")); + sim("manipWordCaseMulti", "foo Bar bAz", + "Ctrl-2", "Alt-U", txt("FOO BAR bAz"), + "Ctrl-A", "Ctrl-3", "Alt-C", txt("Foo Bar Baz")); + + sim("upExpr", "foo {\n bar[];\n baz(blah);\n}", + Pos(2, 7), "Ctrl-Alt-U", at(2, 5), "Ctrl-Alt-U", at(0, 4)); + sim("transposeExpr", "do foo[bar] dah", + Pos(0, 6), "Ctrl-Alt-T", txt("do [bar]foo dah")); + + sim("clearMark", "abcde", Pos(0, 2), "Ctrl-Space", "Ctrl-F", "Ctrl-F", + "Ctrl-G", "Ctrl-W", txt("abcde")); + + sim("delRegion", "abcde", "Ctrl-Space", "Ctrl-F", "Ctrl-F", "Delete", txt("cde")); + sim("backspaceRegion", "abcde", "Ctrl-Space", "Ctrl-F", "Ctrl-F", "Backspace", txt("cde")); + + sim("backspaceDoesntAddToRing", "foobar", "Ctrl-F", "Ctrl-F", "Ctrl-F", "Ctrl-K", "Backspace", "Backspace", "Ctrl-Y", txt("fbar")); + + testCM("save", function(cm) { + var saved = false; + CodeMirror.commands.save = function(cm) { saved = cm.getValue(); }; + cm.triggerOnKeyDown(fakeEvent("Ctrl-X")); + cm.triggerOnKeyDown(fakeEvent("Ctrl-S")); + is(saved, "hi"); + }, {value: "hi", keyMap: "emacs"}); + + testCM("gotoInvalidLineFloat", function(cm) { + cm.openDialog = function(_, cb) { cb("2.2"); }; + cm.triggerOnKeyDown(fakeEvent("Alt-G")); + cm.triggerOnKeyDown(fakeEvent("G")); + }, {value: "1\n2\n3\n4", keyMap: "emacs"}); +})(); diff --git a/modules/editor/codemirror/test/mode_test.js b/modules/editor/codemirror/test/mode_test.js @@ -0,0 +1,193 @@ +/** + * Helper to test CodeMirror highlighting modes. It pretty prints output of the + * highlighter and can check against expected styles. + * + * Mode tests are registered by calling test.mode(testName, mode, + * tokens), where mode is a mode object as returned by + * CodeMirror.getMode, and tokens is an array of lines that make up + * the test. + * + * These lines are strings, in which styled stretches of code are + * enclosed in brackets `[]`, and prefixed by their style. For + * example, `[keyword if]`. Brackets in the code itself must be + * duplicated to prevent them from being interpreted as token + * boundaries. For example `a[[i]]` for `a[i]`. If a token has + * multiple styles, the styles must be separated by ampersands, for + * example `[tag&error </hmtl>]`. + * + * See the test.js files in the css, markdown, gfm, and stex mode + * directories for examples. + */ +(function() { + function findSingle(str, pos, ch) { + for (;;) { + var found = str.indexOf(ch, pos); + if (found == -1) return null; + if (str.charAt(found + 1) != ch) return found; + pos = found + 2; + } + } + + var styleName = /[\w&-_]+/g; + function parseTokens(strs) { + var tokens = [], plain = ""; + for (var i = 0; i < strs.length; ++i) { + if (i) plain += "\n"; + var str = strs[i], pos = 0; + while (pos < str.length) { + var style = null, text; + if (str.charAt(pos) == "[" && str.charAt(pos+1) != "[") { + styleName.lastIndex = pos + 1; + var m = styleName.exec(str); + style = m[0].replace(/&/g, " "); + var textStart = pos + style.length + 2; + var end = findSingle(str, textStart, "]"); + if (end == null) throw new Error("Unterminated token at " + pos + " in '" + str + "'" + style); + text = str.slice(textStart, end); + pos = end + 1; + } else { + var end = findSingle(str, pos, "["); + if (end == null) end = str.length; + text = str.slice(pos, end); + pos = end; + } + text = text.replace(/\[\[|\]\]/g, function(s) {return s.charAt(0);}); + tokens.push({style: style, text: text}); + plain += text; + } + } + return {tokens: tokens, plain: plain}; + } + + test.mode = function(name, mode, tokens, modeName) { + var data = parseTokens(tokens); + return test((modeName || mode.name) + "_" + name, function() { + return compare(data.plain, data.tokens, mode); + }); + }; + + function esc(str) { + return str.replace('&', '&amp;').replace('<', '&lt;').replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;"); + } + + function compare(text, expected, mode) { + + var expectedOutput = []; + for (var i = 0; i < expected.length; ++i) { + var sty = expected[i].style; + if (sty && sty.indexOf(" ")) sty = sty.split(' ').sort().join(' '); + expectedOutput.push({style: sty, text: expected[i].text}); + } + + var observedOutput = highlight(text, mode); + + var s = ""; + var diff = highlightOutputsDifferent(expectedOutput, observedOutput); + if (diff != null) { + s += '<div class="mt-test mt-fail">'; + s += '<pre>' + esc(text) + '</pre>'; + s += '<div class="cm-s-default">'; + s += 'expected:'; + s += prettyPrintOutputTable(expectedOutput, diff); + s += 'observed: [<a onclick="this.parentElement.className+=\' mt-state-unhide\'">display states</a>]'; + s += prettyPrintOutputTable(observedOutput, diff); + s += '</div>'; + s += '</div>'; + } + if (observedOutput.indentFailures) { + for (var i = 0; i < observedOutput.indentFailures.length; i++) + s += "<div class='mt-test mt-fail'>" + esc(observedOutput.indentFailures[i]) + "</div>"; + } + if (s) throw new Failure(s); + } + + function stringify(obj) { + function replacer(key, obj) { + if (typeof obj == "function") { + var m = obj.toString().match(/function\s*[^\s(]*/); + return m ? m[0] : "function"; + } + return obj; + } + if (window.JSON && JSON.stringify) + return JSON.stringify(obj, replacer, 2); + return "[unsupported]"; // Fail safely if no native JSON. + } + + function highlight(string, mode) { + var state = mode.startState(); + + var lines = string.replace(/\r\n/g,'\n').split('\n'); + var st = [], pos = 0; + for (var i = 0; i < lines.length; ++i) { + var line = lines[i], newLine = true; + if (mode.indent) { + var ws = line.match(/^\s*/)[0]; + var indent = mode.indent(state, line.slice(ws.length)); + if (indent != CodeMirror.Pass && indent != ws.length) + (st.indentFailures || (st.indentFailures = [])).push( + "Indentation of line " + (i + 1) + " is " + indent + " (expected " + ws.length + ")"); + } + var stream = new CodeMirror.StringStream(line, 4, { + lookAhead: function(n) { return lines[i + n] } + }); + if (line == "" && mode.blankLine) mode.blankLine(state); + /* Start copied code from CodeMirror.highlight */ + while (!stream.eol()) { + for (var j = 0; j < 10 && stream.start >= stream.pos; j++) + var compare = mode.token(stream, state); + if (j == 10) + throw new Failure("Failed to advance the stream." + stream.string + " " + stream.pos); + var substr = stream.current(); + if (compare && compare.indexOf(" ") > -1) compare = compare.split(' ').sort().join(' '); + stream.start = stream.pos; + if (pos && st[pos-1].style == compare && !newLine) { + st[pos-1].text += substr; + } else if (substr) { + st[pos++] = {style: compare, text: substr, state: stringify(state)}; + } + // Give up when line is ridiculously long + if (stream.pos > 5000) { + st[pos++] = {style: null, text: this.text.slice(stream.pos)}; + break; + } + newLine = false; + } + } + + return st; + } + + function highlightOutputsDifferent(o1, o2) { + var minLen = Math.min(o1.length, o2.length); + for (var i = 0; i < minLen; ++i) + if (o1[i].style != o2[i].style || o1[i].text != o2[i].text) return i; + if (o1.length > minLen || o2.length > minLen) return minLen; + } + + function prettyPrintOutputTable(output, diffAt) { + var s = '<table class="mt-output">'; + s += '<tr>'; + for (var i = 0; i < output.length; ++i) { + var style = output[i].style, val = output[i].text; + s += + '<td class="mt-token"' + (i == diffAt ? " style='background: pink'" : "") + '>' + + '<span class="cm-' + esc(String(style)) + '">' + + esc(val.replace(/ /g,'\xb7')) + // · MIDDLE DOT + '</span>' + + '</td>'; + } + s += '</tr><tr>'; + for (var i = 0; i < output.length; ++i) { + s += '<td class="mt-style"><span>' + (output[i].style || null) + '</span></td>'; + } + if(output[0].state) { + s += '</tr><tr class="mt-state-row" title="State AFTER each token">'; + for (var i = 0; i < output.length; ++i) { + s += '<td class="mt-state"><pre>' + esc(output[i].state) + '</pre></td>'; + } + } + s += '</tr></table>'; + return s; + } +})(); diff --git a/modules/editor/codemirror/test/run.js b/modules/editor/codemirror/test/run.js @@ -0,0 +1,31 @@ +#!/usr/bin/env node + +var ok = require("./lint").ok; + +var files = new (require('node-static').Server)(); + +var server = require('http').createServer(function (req, res) { + req.addListener('end', function () { + files.serve(req, res, function (err/*, result */) { + if (err) { + console.error(err); + process.exit(1); + } + }); + }).resume(); +}).addListener('error', function (err) { + throw err; +}).listen(3000, function () { + var childProcess = require('child_process'); + var phantomjs = require("phantomjs-prebuilt"); + var childArgs = [ + require("path").join(__dirname, 'phantom_driver.js') + ]; + childProcess.execFile(phantomjs.path, childArgs, function (err, stdout, stderr) { + server.close(); + console.log(stdout); + if (err) console.error(err); + if (stderr) console.error(stderr); + process.exit(err || stderr || !ok ? 1 : 0); + }); +}); diff --git a/modules/editor/codemirror/test/scroll_test.min.js b/modules/editor/codemirror/test/scroll_test.min.js @@ -0,0 +1,126 @@ +(function() { + "use strict"; + + namespace = "scroll_"; + + testCM("bars_hidden", function(cm) { + for (var i = 0;; i++) { + var wrapBox = cm.getWrapperElement().getBoundingClientRect(); + var scrollBox = cm.getScrollerElement().getBoundingClientRect(); + is(wrapBox.bottom < scrollBox.bottom - 10); + is(wrapBox.right < scrollBox.right - 10); + if (i == 1) break; + cm.getWrapperElement().style.height = "auto"; + cm.refresh(); + } + }); + + function barH(cm) { return byClassName(cm.getWrapperElement(), "CodeMirror-hscrollbar")[0]; } + function barV(cm) { return byClassName(cm.getWrapperElement(), "CodeMirror-vscrollbar")[0]; } + + function displayBottom(cm, scrollbar) { + if (scrollbar && cm.display.scroller.offsetHeight > cm.display.scroller.clientHeight) + return barH(cm).getBoundingClientRect().top; + else + return cm.getWrapperElement().getBoundingClientRect().bottom - 1; + } + + function displayRight(cm, scrollbar) { + if (scrollbar && cm.display.scroller.offsetWidth > cm.display.scroller.clientWidth) + return barV(cm).getBoundingClientRect().left; + else + return cm.getWrapperElement().getBoundingClientRect().right - 1; + } + + function testMovedownFixed(cm, hScroll) { + cm.setSize("100px", "100px"); + if (hScroll) cm.setValue(new Array(100).join("x")); + var bottom = displayBottom(cm, hScroll); + for (var i = 0; i < 30; i++) { + cm.replaceSelection("x\n"); + var cursorBottom = cm.cursorCoords(null, "window").bottom; + is(cursorBottom <= bottom); + } + is(cursorBottom >= bottom - 5); + } + + testCM("movedown_fixed", function(cm) {testMovedownFixed(cm, false);}); + testCM("movedown_hscroll_fixed", function(cm) {testMovedownFixed(cm, true);}); + + function testMovedownResize(cm, hScroll) { + cm.getWrapperElement().style.height = "auto"; + if (hScroll) cm.setValue(new Array(100).join("x")); + cm.refresh(); + for (var i = 0; i < 30; i++) { + cm.replaceSelection("x\n"); + var bottom = displayBottom(cm, hScroll); + var cursorBottom = cm.cursorCoords(null, "window").bottom; + is(cursorBottom <= bottom); + is(cursorBottom >= bottom - 5); + } + } + + testCM("movedown_resize", function(cm) {testMovedownResize(cm, false);}); + testCM("movedown_hscroll_resize", function(cm) {testMovedownResize(cm, true);}); + + function testMoveright(cm, wrap, scroll) { + cm.setSize("100px", "100px"); + if (wrap) cm.setOption("lineWrapping", true); + if (scroll) { + cm.setValue("\n" + new Array(100).join("x\n")); + cm.setCursor(Pos(0, 0)); + } + var right = displayRight(cm, scroll); + for (var i = 0; i < 10; i++) { + cm.replaceSelection("xxxxxxxxxx"); + var cursorRight = cm.cursorCoords(null, "window").right; + is(cursorRight < right); + } + if (!wrap) is(cursorRight > right - 20); + } + + testCM("moveright", function(cm) {testMoveright(cm, false, false);}); + testCM("moveright_wrap", function(cm) {testMoveright(cm, true, false);}); + testCM("moveright_scroll", function(cm) {testMoveright(cm, false, true);}); + testCM("moveright_scroll_wrap", function(cm) {testMoveright(cm, true, true);}); + + testCM("suddenly_wide", function(cm) { + addDoc(cm, 100, 100); + cm.replaceSelection(new Array(600).join("l ") + "\n"); + cm.execCommand("goLineUp"); + cm.execCommand("goLineEnd"); + is(barH(cm).scrollLeft > cm.getScrollerElement().scrollLeft - 1); + }); + + testCM("wrap_changes_height", function(cm) { + var line = new Array(20).join("a ") + "\n"; + cm.setValue(new Array(20).join(line)); + var box = cm.getWrapperElement().getBoundingClientRect(); + cm.setSize(cm.cursorCoords(Pos(0), "window").right - box.left + 2, + cm.cursorCoords(Pos(19, 0), "window").bottom - box.top + 2); + cm.setCursor(Pos(19, 0)); + cm.replaceSelection("\n"); + is(cm.cursorCoords(null, "window").bottom < displayBottom(cm, false)); + }, {lineWrapping: true}); + + testCM("height_auto_with_gutter_expect_no_scroll_after_line_delete", function(cm) { + cm.setSize(null, "auto"); + cm.setValue("x\n"); + cm.execCommand("goDocEnd"); + cm.execCommand("delCharBefore"); + eq(cm.getScrollInfo().top, 0); + cm.scrollTo(null, 10); + is(cm.getScrollInfo().top < 5); + }, {lineNumbers: true}); + + testCM("bidi_ensureCursorVisible", function(cm) { + cm.setValue("<dd>وضع الاستخدام. عندما لا تعطى، وهذا الافتراضي إلى الطريقة الاولى\n"); + cm.execCommand("goLineStart"); + eq(cm.getScrollInfo().left, 0); + cm.execCommand("goCharRight"); + cm.execCommand("goCharRight"); + cm.execCommand("goCharRight"); + eqCursorPos(cm.getCursor(), Pos(0, 3, "before")); + eq(cm.getScrollInfo().left, 0); + }, {lineWrapping: false}); +})(); diff --git a/modules/editor/codemirror/test/search_test.js b/modules/editor/codemirror/test/search_test.js @@ -0,0 +1,85 @@ +(function() { + "use strict"; + + function run(doc, query, options) { + var cursor = doc.getSearchCursor(query, null, options); + for (var i = 3; i < arguments.length; i += 4) { + var found = cursor.findNext(); + is(found, "not enough results (forward)"); + eqCharPos(Pos(arguments[i], arguments[i + 1]), cursor.from(), "from, forward, " + (i - 3) / 4); + eqCharPos(Pos(arguments[i + 2], arguments[i + 3]), cursor.to(), "to, forward, " + (i - 3) / 4); + } + is(!cursor.findNext(), "too many matches (forward)"); + for (var i = arguments.length - 4; i >= 3; i -= 4) { + var found = cursor.findPrevious(); + is(found, "not enough results (backwards)"); + eqCharPos(Pos(arguments[i], arguments[i + 1]), cursor.from(), "from, backwards, " + (i - 3) / 4); + eqCharPos(Pos(arguments[i + 2], arguments[i + 3]), cursor.to(), "to, backwards, " + (i - 3) / 4); + } + is(!cursor.findPrevious(), "too many matches (backwards)"); + } + + function test(name, f) { window.test("search_" + name, f) } + + test("simple", function() { + var doc = new CodeMirror.Doc("abcdefg\nabcdefg") + run(doc, "cde", false, 0, 2, 0, 5, 1, 2, 1, 5); + }); + + test("multiline", function() { + var doc = new CodeMirror.Doc("hallo\na\nb\ngoodbye") + run(doc, "llo\na\nb\ngoo", false, 0, 2, 3, 3); + run(doc, "blah\na\nb\nhall", false); + run(doc, "bye\nx\neye", false); + }); + + test("regexp", function() { + var doc = new CodeMirror.Doc("abcde\nabcde") + run(doc, /bcd/, false, 0, 1, 0, 4, 1, 1, 1, 4); + run(doc, /BCD/, false); + run(doc, /BCD/i, false, 0, 1, 0, 4, 1, 1, 1, 4); + }); + + test("regexpMultiline", function() { + var doc = new CodeMirror.Doc("foo foo\nbar\nbaz") + run(doc, /fo[^]*az/, {multiline: true}, 0, 0, 2, 3) + run(doc, /[oa][^u]/, {multiline: true}, 0, 1, 0, 3, 0, 5, 0, 7, 1, 1, 1, 3, 2, 1, 2, 3) + run(doc, /[a][^u]{2}/, {multiline: true}, 1, 1, 2, 0) + }) + + test("insensitive", function() { + var doc = new CodeMirror.Doc("hallo\nHALLO\noink\nhAllO") + run(doc, "All", false, 3, 1, 3, 4); + run(doc, "All", true, 0, 1, 0, 4, 1, 1, 1, 4, 3, 1, 3, 4); + }); + + test("multilineInsensitive", function() { + var doc = new CodeMirror.Doc("zie ginds komT\nDe Stoomboot\nuit Spanje weer aan") + run(doc, "komt\nde stoomboot\nuit", false); + run(doc, "komt\nde stoomboot\nuit", {caseFold: true}, 0, 10, 2, 3); + run(doc, "kOMt\ndE stOOmboot\nuiT", {caseFold: true}, 0, 10, 2, 3); + }); + + test("multilineInsensitiveSlow", function() { + var text = "" + for (var i = 0; i < 1000; i++) text += "foo\nbar\n" + var doc = new CodeMirror.Doc("find\nme\n" + text + "find\nme\n") + var t0 = +new Date + run(doc, /find\nme/, {multiline: true}, 0, 0, 1, 2, 2002, 0, 2003, 2) + is(+new Date - t0 < 100) + }) + + test("expandingCaseFold", function() { + var doc = new CodeMirror.Doc("<b>İİ İİ</b>\n<b>uu uu</b>") + run(doc, "</b>", true, 0, 8, 0, 12, 1, 8, 1, 12); + run(doc, "İİ", true, 0, 3, 0, 5, 0, 6, 0, 8); + }); + + test("normalize", function() { + if (!String.prototype.normalize) return + var doc = new CodeMirror.Doc("yılbaşı\n수 있을까\nLe taux d'humidité à London") + run(doc, "s", false, 0, 5, 0, 6) + run(doc, "이", false, 1, 2, 1, 3) + run(doc, "a", false, 0, 4, 0, 5, 2, 4, 2, 5, 2, 19, 2, 20) + }) +})(); diff --git a/modules/editor/codemirror/test/test.js b/modules/editor/codemirror/test/test.js @@ -0,0 +1,2550 @@ +var Pos = CodeMirror.Pos; + +CodeMirror.defaults.rtlMoveVisually = true; + +function forEach(arr, f) { + for (var i = 0, e = arr.length; i < e; ++i) f(arr[i], i); +} + +function addDoc(cm, width, height) { + var content = [], line = ""; + for (var i = 0; i < width; ++i) line += "x"; + for (var i = 0; i < height; ++i) content.push(line); + cm.setValue(content.join("\n")); +} + +function byClassName(elt, cls) { + if (elt.getElementsByClassName) return elt.getElementsByClassName(cls); + var found = [], re = new RegExp("\\b" + cls + "\\b"); + function search(elt) { + if (elt.nodeType == 3) return; + if (re.test(elt.className)) found.push(elt); + for (var i = 0, e = elt.childNodes.length; i < e; ++i) + search(elt.childNodes[i]); + } + search(elt); + return found; +} + +var ie_lt8 = /MSIE [1-7]\b/.test(navigator.userAgent); +var ie_lt9 = /MSIE [1-8]\b/.test(navigator.userAgent); +var mac = /Mac/.test(navigator.platform); +var phantom = /PhantomJS/.test(navigator.userAgent); +var opera = /Opera\/\./.test(navigator.userAgent); +var opera_version = opera && navigator.userAgent.match(/Version\/(\d+\.\d+)/); +if (opera_version) opera_version = Number(opera_version); +var opera_lt10 = opera && (!opera_version || opera_version < 10); + +namespace = "core_"; + +test("core_fromTextArea", function() { + var te = document.getElementById("code"); + te.value = "CONTENT"; + var cm = CodeMirror.fromTextArea(te); + is(!te.offsetHeight); + eq(cm.getValue(), "CONTENT"); + cm.setValue("foo\nbar"); + eq(cm.getValue(), "foo\nbar"); + cm.save(); + is(/^foo\r?\nbar$/.test(te.value)); + cm.setValue("xxx"); + cm.toTextArea(); + is(te.offsetHeight); + eq(te.value, "xxx"); +}); + +testCM("getRange", function(cm) { + eq(cm.getLine(0), "1234"); + eq(cm.getLine(1), "5678"); + eq(cm.getLine(2), null); + eq(cm.getLine(-1), null); + eq(cm.getRange(Pos(0, 0), Pos(0, 3)), "123"); + eq(cm.getRange(Pos(0, -1), Pos(0, 200)), "1234"); + eq(cm.getRange(Pos(0, 2), Pos(1, 2)), "34\n56"); + eq(cm.getRange(Pos(1, 2), Pos(100, 0)), "78"); +}, {value: "1234\n5678"}); + +testCM("replaceRange", function(cm) { + eq(cm.getValue(), ""); + cm.replaceRange("foo\n", Pos(0, 0)); + eq(cm.getValue(), "foo\n"); + cm.replaceRange("a\nb", Pos(0, 1)); + eq(cm.getValue(), "fa\nboo\n"); + eq(cm.lineCount(), 3); + cm.replaceRange("xyzzy", Pos(0, 0), Pos(1, 1)); + eq(cm.getValue(), "xyzzyoo\n"); + cm.replaceRange("abc", Pos(0, 0), Pos(10, 0)); + eq(cm.getValue(), "abc"); + eq(cm.lineCount(), 1); +}); + +testCM("selection", function(cm) { + cm.setSelection(Pos(0, 4), Pos(2, 2)); + is(cm.somethingSelected()); + eq(cm.getSelection(), "11\n222222\n33"); + eqCursorPos(cm.getCursor(false), Pos(2, 2)); + eqCursorPos(cm.getCursor(true), Pos(0, 4)); + cm.setSelection(Pos(1, 0)); + is(!cm.somethingSelected()); + eq(cm.getSelection(), ""); + eqCursorPos(cm.getCursor(true), Pos(1, 0)); + cm.replaceSelection("abc", "around"); + eq(cm.getSelection(), "abc"); + eq(cm.getValue(), "111111\nabc222222\n333333"); + cm.replaceSelection("def", "end"); + eq(cm.getSelection(), ""); + eqCursorPos(cm.getCursor(true), Pos(1, 3)); + cm.setCursor(Pos(2, 1)); + eqCursorPos(cm.getCursor(true), Pos(2, 1)); + cm.setCursor(1, 2); + eqCursorPos(cm.getCursor(true), Pos(1, 2)); +}, {value: "111111\n222222\n333333"}); + +testCM("extendSelection", function(cm) { + cm.setExtending(true); + addDoc(cm, 10, 10); + cm.setSelection(Pos(3, 5)); + eqCursorPos(cm.getCursor("head"), Pos(3, 5)); + eqCursorPos(cm.getCursor("anchor"), Pos(3, 5)); + cm.setSelection(Pos(2, 5), Pos(5, 5)); + eqCursorPos(cm.getCursor("head"), Pos(5, 5)); + eqCursorPos(cm.getCursor("anchor"), Pos(2, 5)); + eqCursorPos(cm.getCursor("start"), Pos(2, 5)); + eqCursorPos(cm.getCursor("end"), Pos(5, 5)); + cm.setSelection(Pos(5, 5), Pos(2, 5)); + eqCursorPos(cm.getCursor("head"), Pos(2, 5)); + eqCursorPos(cm.getCursor("anchor"), Pos(5, 5)); + eqCursorPos(cm.getCursor("start"), Pos(2, 5)); + eqCursorPos(cm.getCursor("end"), Pos(5, 5)); + cm.extendSelection(Pos(3, 2)); + eqCursorPos(cm.getCursor("head"), Pos(3, 2)); + eqCursorPos(cm.getCursor("anchor"), Pos(5, 5)); + cm.extendSelection(Pos(6, 2)); + eqCursorPos(cm.getCursor("head"), Pos(6, 2)); + eqCursorPos(cm.getCursor("anchor"), Pos(5, 5)); + cm.extendSelection(Pos(6, 3), Pos(6, 4)); + eqCursorPos(cm.getCursor("head"), Pos(6, 4)); + eqCursorPos(cm.getCursor("anchor"), Pos(5, 5)); + cm.extendSelection(Pos(0, 3), Pos(0, 4)); + eqCursorPos(cm.getCursor("head"), Pos(0, 3)); + eqCursorPos(cm.getCursor("anchor"), Pos(5, 5)); + cm.extendSelection(Pos(4, 5), Pos(6, 5)); + eqCursorPos(cm.getCursor("head"), Pos(6, 5)); + eqCursorPos(cm.getCursor("anchor"), Pos(4, 5)); + cm.setExtending(false); + cm.extendSelection(Pos(0, 3), Pos(0, 4)); + eqCursorPos(cm.getCursor("head"), Pos(0, 3)); + eqCursorPos(cm.getCursor("anchor"), Pos(0, 4)); +}); + +testCM("lines", function(cm) { + eq(cm.getLine(0), "111111"); + eq(cm.getLine(1), "222222"); + eq(cm.getLine(-1), null); + cm.replaceRange("", Pos(1, 0), Pos(2, 0)) + cm.replaceRange("abc", Pos(1, 0), Pos(1)); + eq(cm.getValue(), "111111\nabc"); +}, {value: "111111\n222222\n333333"}); + +testCM("indent", function(cm) { + cm.indentLine(1); + eq(cm.getLine(1), " blah();"); + cm.setOption("indentUnit", 8); + cm.indentLine(1); + eq(cm.getLine(1), "\tblah();"); + cm.setOption("indentUnit", 10); + cm.setOption("tabSize", 4); + cm.indentLine(1); + eq(cm.getLine(1), "\t\t blah();"); +}, {value: "if (x) {\nblah();\n}", indentUnit: 3, indentWithTabs: true, tabSize: 8}); + +testCM("indentByNumber", function(cm) { + cm.indentLine(0, 2); + eq(cm.getLine(0), " foo"); + cm.indentLine(0, -200); + eq(cm.getLine(0), "foo"); + cm.setSelection(Pos(0, 0), Pos(1, 2)); + cm.indentSelection(3); + eq(cm.getValue(), " foo\n bar\nbaz"); +}, {value: "foo\nbar\nbaz"}); + +test("core_defaults", function() { + var defsCopy = {}, defs = CodeMirror.defaults; + for (var opt in defs) defsCopy[opt] = defs[opt]; + defs.indentUnit = 5; + defs.value = "uu"; + defs.indentWithTabs = true; + defs.tabindex = 55; + var place = document.getElementById("testground"), cm = CodeMirror(place); + try { + eq(cm.getOption("indentUnit"), 5); + cm.setOption("indentUnit", 10); + eq(defs.indentUnit, 5); + eq(cm.getValue(), "uu"); + eq(cm.getOption("indentWithTabs"), true); + eq(cm.getInputField().tabIndex, 55); + } + finally { + for (var opt in defsCopy) defs[opt] = defsCopy[opt]; + place.removeChild(cm.getWrapperElement()); + } +}); + +testCM("lineInfo", function(cm) { + eq(cm.lineInfo(-1), null); + var mark = document.createElement("span"); + var lh = cm.setGutterMarker(1, "FOO", mark); + var info = cm.lineInfo(1); + eq(info.text, "222222"); + eq(info.gutterMarkers.FOO, mark); + eq(info.line, 1); + eq(cm.lineInfo(2).gutterMarkers, null); + cm.setGutterMarker(lh, "FOO", null); + eq(cm.lineInfo(1).gutterMarkers, null); + cm.setGutterMarker(1, "FOO", mark); + cm.setGutterMarker(0, "FOO", mark); + cm.clearGutter("FOO"); + eq(cm.lineInfo(0).gutterMarkers, null); + eq(cm.lineInfo(1).gutterMarkers, null); +}, {value: "111111\n222222\n333333"}); + +testCM("coords", function(cm) { + cm.setSize(null, 100); + addDoc(cm, 32, 200); + var top = cm.charCoords(Pos(0, 0)); + var bot = cm.charCoords(Pos(200, 30)); + is(top.left < bot.left); + is(top.top < bot.top); + is(top.top < top.bottom); + cm.scrollTo(null, 100); + var top2 = cm.charCoords(Pos(0, 0)); + is(top.top > top2.top); + eq(top.left, top2.left); +}); + +testCM("coordsChar", function(cm) { + addDoc(cm, 35, 70); + for (var i = 0; i < 2; ++i) { + var sys = i ? "local" : "page"; + for (var ch = 0; ch <= 35; ch += 5) { + for (var line = 0; line < 70; line += 5) { + cm.setCursor(line, ch); + var coords = cm.charCoords(Pos(line, ch), sys); + var pos = cm.coordsChar({left: coords.left + 1, top: coords.top + 1}, sys); + eqCharPos(pos, Pos(line, ch)); + } + } + } +}, {lineNumbers: true}); + +testCM("coordsCharBidi", function(cm) { + addDoc(cm, 35, 70); + // Put an rtl character into each line to trigger the bidi code path in coordsChar + cm.setValue(cm.getValue().replace(/\bx/g, 'و')) + for (var i = 0; i < 2; ++i) { + var sys = i ? "local" : "page"; + for (var ch = 2; ch <= 35; ch += 5) { + for (var line = 0; line < 70; line += 5) { + cm.setCursor(line, ch); + var coords = cm.charCoords(Pos(line, ch), sys); + var pos = cm.coordsChar({left: coords.left + 1, top: coords.top + 1}, sys); + eqCharPos(pos, Pos(line, ch)); + } + } + } +}, {lineNumbers: true}); + +testCM("badBidiOptimization", function(cm) { + var coords = cm.charCoords(Pos(0, 34)) + eqCharPos(cm.coordsChar({left: coords.right, top: coords.top + 2}), Pos(0, 34)) +}, {value: "----------<p class=\"title\">هل يمكنك اختيار مستوى قسط التأمين الذي ترغب بدفعه؟</p>"}) + +testCM("posFromIndex", function(cm) { + cm.setValue( + "This function should\n" + + "convert a zero based index\n" + + "to line and ch." + ); + + var examples = [ + { index: -1, line: 0, ch: 0 }, // <- Tests clipping + { index: 0, line: 0, ch: 0 }, + { index: 10, line: 0, ch: 10 }, + { index: 39, line: 1, ch: 18 }, + { index: 55, line: 2, ch: 7 }, + { index: 63, line: 2, ch: 15 }, + { index: 64, line: 2, ch: 15 } // <- Tests clipping + ]; + + for (var i = 0; i < examples.length; i++) { + var example = examples[i]; + var pos = cm.posFromIndex(example.index); + eq(pos.line, example.line); + eq(pos.ch, example.ch); + if (example.index >= 0 && example.index < 64) + eq(cm.indexFromPos(pos), example.index); + } +}); + +testCM("undo", function(cm) { + cm.replaceRange("def", Pos(0, 0), Pos(0)); + eq(cm.historySize().undo, 1); + cm.undo(); + eq(cm.getValue(), "abc"); + eq(cm.historySize().undo, 0); + eq(cm.historySize().redo, 1); + cm.redo(); + eq(cm.getValue(), "def"); + eq(cm.historySize().undo, 1); + eq(cm.historySize().redo, 0); + cm.setValue("1\n\n\n2"); + cm.clearHistory(); + eq(cm.historySize().undo, 0); + for (var i = 0; i < 20; ++i) { + cm.replaceRange("a", Pos(0, 0)); + cm.replaceRange("b", Pos(3, 0)); + } + eq(cm.historySize().undo, 40); + for (var i = 0; i < 40; ++i) + cm.undo(); + eq(cm.historySize().redo, 40); + eq(cm.getValue(), "1\n\n\n2"); +}, {value: "abc"}); + +testCM("undoDepth", function(cm) { + cm.replaceRange("d", Pos(0)); + cm.replaceRange("e", Pos(0)); + cm.replaceRange("f", Pos(0)); + cm.undo(); cm.undo(); cm.undo(); + eq(cm.getValue(), "abcd"); +}, {value: "abc", undoDepth: 4}); + +testCM("undoDoesntClearValue", function(cm) { + cm.undo(); + eq(cm.getValue(), "x"); +}, {value: "x"}); + +testCM("undoMultiLine", function(cm) { + cm.operation(function() { + cm.replaceRange("x", Pos(0, 0)); + cm.replaceRange("y", Pos(1, 0)); + }); + cm.undo(); + eq(cm.getValue(), "abc\ndef\nghi"); + cm.operation(function() { + cm.replaceRange("y", Pos(1, 0)); + cm.replaceRange("x", Pos(0, 0)); + }); + cm.undo(); + eq(cm.getValue(), "abc\ndef\nghi"); + cm.operation(function() { + cm.replaceRange("y", Pos(2, 0)); + cm.replaceRange("x", Pos(1, 0)); + cm.replaceRange("z", Pos(2, 0)); + }); + cm.undo(); + eq(cm.getValue(), "abc\ndef\nghi", 3); +}, {value: "abc\ndef\nghi"}); + +testCM("undoComposite", function(cm) { + cm.replaceRange("y", Pos(1)); + cm.operation(function() { + cm.replaceRange("x", Pos(0)); + cm.replaceRange("z", Pos(2)); + }); + eq(cm.getValue(), "ax\nby\ncz\n"); + cm.undo(); + eq(cm.getValue(), "a\nby\nc\n"); + cm.undo(); + eq(cm.getValue(), "a\nb\nc\n"); + cm.redo(); cm.redo(); + eq(cm.getValue(), "ax\nby\ncz\n"); +}, {value: "a\nb\nc\n"}); + +testCM("undoSelection", function(cm) { + cm.setSelection(Pos(0, 2), Pos(0, 4)); + cm.replaceSelection(""); + cm.setCursor(Pos(1, 0)); + cm.undo(); + eqCursorPos(cm.getCursor(true), Pos(0, 2)); + eqCursorPos(cm.getCursor(false), Pos(0, 4)); + cm.setCursor(Pos(1, 0)); + cm.redo(); + eqCursorPos(cm.getCursor(true), Pos(0, 2)); + eqCursorPos(cm.getCursor(false), Pos(0, 2)); +}, {value: "abcdefgh\n"}); + +testCM("undoSelectionAsBefore", function(cm) { + cm.replaceSelection("abc", "around"); + cm.undo(); + cm.redo(); + eq(cm.getSelection(), "abc"); +}); + +testCM("selectionChangeConfusesHistory", function(cm) { + cm.replaceSelection("abc", null, "dontmerge"); + cm.operation(function() { + cm.setCursor(Pos(0, 0)); + cm.replaceSelection("abc", null, "dontmerge"); + }); + eq(cm.historySize().undo, 2); +}); + +testCM("markTextSingleLine", function(cm) { + forEach([{a: 0, b: 1, c: "", f: 2, t: 5}, + {a: 0, b: 4, c: "", f: 0, t: 2}, + {a: 1, b: 2, c: "x", f: 3, t: 6}, + {a: 4, b: 5, c: "", f: 3, t: 5}, + {a: 4, b: 5, c: "xx", f: 3, t: 7}, + {a: 2, b: 5, c: "", f: 2, t: 3}, + {a: 2, b: 5, c: "abcd", f: 6, t: 7}, + {a: 2, b: 6, c: "x", f: null, t: null}, + {a: 3, b: 6, c: "", f: null, t: null}, + {a: 0, b: 9, c: "hallo", f: null, t: null}, + {a: 4, b: 6, c: "x", f: 3, t: 4}, + {a: 4, b: 8, c: "", f: 3, t: 4}, + {a: 6, b: 6, c: "a", f: 3, t: 6}, + {a: 8, b: 9, c: "", f: 3, t: 6}], function(test) { + cm.setValue("1234567890"); + var r = cm.markText(Pos(0, 3), Pos(0, 6), {className: "foo"}); + cm.replaceRange(test.c, Pos(0, test.a), Pos(0, test.b)); + var f = r.find(); + eq(f && f.from.ch, test.f); eq(f && f.to.ch, test.t); + }); +}); + +testCM("markTextMultiLine", function(cm) { + function p(v) { return v && Pos(v[0], v[1]); } + forEach([{a: [0, 0], b: [0, 5], c: "", f: [0, 0], t: [2, 5]}, + {a: [0, 0], b: [0, 5], c: "foo\n", f: [1, 0], t: [3, 5]}, + {a: [0, 1], b: [0, 10], c: "", f: [0, 1], t: [2, 5]}, + {a: [0, 5], b: [0, 6], c: "x", f: [0, 6], t: [2, 5]}, + {a: [0, 0], b: [1, 0], c: "", f: [0, 0], t: [1, 5]}, + {a: [0, 6], b: [2, 4], c: "", f: [0, 5], t: [0, 7]}, + {a: [0, 6], b: [2, 4], c: "aa", f: [0, 5], t: [0, 9]}, + {a: [1, 2], b: [1, 8], c: "", f: [0, 5], t: [2, 5]}, + {a: [0, 5], b: [2, 5], c: "xx", f: null, t: null}, + {a: [0, 0], b: [2, 10], c: "x", f: null, t: null}, + {a: [1, 5], b: [2, 5], c: "", f: [0, 5], t: [1, 5]}, + {a: [2, 0], b: [2, 3], c: "", f: [0, 5], t: [2, 2]}, + {a: [2, 5], b: [3, 0], c: "a\nb", f: [0, 5], t: [2, 5]}, + {a: [2, 3], b: [3, 0], c: "x", f: [0, 5], t: [2, 3]}, + {a: [1, 1], b: [1, 9], c: "1\n2\n3", f: [0, 5], t: [4, 5]}], function(test) { + cm.setValue("aaaaaaaaaa\nbbbbbbbbbb\ncccccccccc\ndddddddd\n"); + var r = cm.markText(Pos(0, 5), Pos(2, 5), + {className: "CodeMirror-matchingbracket"}); + cm.replaceRange(test.c, p(test.a), p(test.b)); + var f = r.find(); + eqCursorPos(f && f.from, p(test.f)); eqCursorPos(f && f.to, p(test.t)); + }); +}); + +testCM("markTextUndo", function(cm) { + var marker1, marker2, bookmark; + marker1 = cm.markText(Pos(0, 1), Pos(0, 3), + {className: "CodeMirror-matchingbracket"}); + marker2 = cm.markText(Pos(0, 0), Pos(2, 1), + {className: "CodeMirror-matchingbracket"}); + bookmark = cm.setBookmark(Pos(1, 5)); + cm.operation(function(){ + cm.replaceRange("foo", Pos(0, 2)); + cm.replaceRange("bar\nbaz\nbug\n", Pos(2, 0), Pos(3, 0)); + }); + var v1 = cm.getValue(); + cm.setValue(""); + eq(marker1.find(), null); eq(marker2.find(), null); eq(bookmark.find(), null); + cm.undo(); + eqCursorPos(bookmark.find(), Pos(1, 5), "still there"); + cm.undo(); + var m1Pos = marker1.find(), m2Pos = marker2.find(); + eqCursorPos(m1Pos.from, Pos(0, 1)); eqCursorPos(m1Pos.to, Pos(0, 3)); + eqCursorPos(m2Pos.from, Pos(0, 0)); eqCursorPos(m2Pos.to, Pos(2, 1)); + eqCursorPos(bookmark.find(), Pos(1, 5)); + cm.redo(); cm.redo(); + eq(bookmark.find(), null); + cm.undo(); + eqCursorPos(bookmark.find(), Pos(1, 5)); + eq(cm.getValue(), v1); +}, {value: "1234\n56789\n00\n"}); + +testCM("markTextStayGone", function(cm) { + var m1 = cm.markText(Pos(0, 0), Pos(0, 1)); + cm.replaceRange("hi", Pos(0, 2)); + m1.clear(); + cm.undo(); + eq(m1.find(), null); +}, {value: "hello"}); + +testCM("markTextAllowEmpty", function(cm) { + var m1 = cm.markText(Pos(0, 1), Pos(0, 2), {clearWhenEmpty: false}); + is(m1.find()); + cm.replaceRange("x", Pos(0, 0)); + is(m1.find()); + cm.replaceRange("y", Pos(0, 2)); + is(m1.find()); + cm.replaceRange("z", Pos(0, 3), Pos(0, 4)); + is(!m1.find()); + var m2 = cm.markText(Pos(0, 1), Pos(0, 2), {clearWhenEmpty: false, + inclusiveLeft: true, + inclusiveRight: true}); + cm.replaceRange("q", Pos(0, 1), Pos(0, 2)); + is(m2.find()); + cm.replaceRange("", Pos(0, 0), Pos(0, 3)); + is(!m2.find()); + var m3 = cm.markText(Pos(0, 1), Pos(0, 1), {clearWhenEmpty: false}); + cm.replaceRange("a", Pos(0, 3)); + is(m3.find()); + cm.replaceRange("b", Pos(0, 1)); + is(!m3.find()); +}, {value: "abcde"}); + +testCM("markTextStacked", function(cm) { + var m1 = cm.markText(Pos(0, 0), Pos(0, 0), {clearWhenEmpty: false}); + var m2 = cm.markText(Pos(0, 0), Pos(0, 0), {clearWhenEmpty: false}); + cm.replaceRange("B", Pos(0, 1)); + is(m1.find() && m2.find()); +}, {value: "A"}); + +testCM("undoPreservesNewMarks", function(cm) { + cm.markText(Pos(0, 3), Pos(0, 4)); + cm.markText(Pos(1, 1), Pos(1, 3)); + cm.replaceRange("", Pos(0, 3), Pos(3, 1)); + var mBefore = cm.markText(Pos(0, 0), Pos(0, 1)); + var mAfter = cm.markText(Pos(0, 5), Pos(0, 6)); + var mAround = cm.markText(Pos(0, 2), Pos(0, 4)); + cm.undo(); + eqCursorPos(mBefore.find().from, Pos(0, 0)); + eqCursorPos(mBefore.find().to, Pos(0, 1)); + eqCursorPos(mAfter.find().from, Pos(3, 3)); + eqCursorPos(mAfter.find().to, Pos(3, 4)); + eqCursorPos(mAround.find().from, Pos(0, 2)); + eqCursorPos(mAround.find().to, Pos(3, 2)); + var found = cm.findMarksAt(Pos(2, 2)); + eq(found.length, 1); + eq(found[0], mAround); +}, {value: "aaaa\nbbbb\ncccc\ndddd"}); + +testCM("markClearBetween", function(cm) { + cm.setValue("aaa\nbbb\nccc\nddd\n"); + cm.markText(Pos(0, 0), Pos(2)); + cm.replaceRange("aaa\nbbb\nccc", Pos(0, 0), Pos(2)); + eq(cm.findMarksAt(Pos(1, 1)).length, 0); +}); + +testCM("findMarksMiddle", function(cm) { + var mark = cm.markText(Pos(1, 1), Pos(3, 1)); + var found = cm.findMarks(Pos(2, 1), Pos(2, 2)); + eq(found.length, 1); + eq(found[0], mark); +}, {value: "line 0\nline 1\nline 2\nline 3"}); + +testCM("deleteSpanCollapsedInclusiveLeft", function(cm) { + var from = Pos(1, 0), to = Pos(1, 1); + var m = cm.markText(from, to, {collapsed: true, inclusiveLeft: true}); + // Delete collapsed span. + cm.replaceRange("", from, to); +}, {value: "abc\nX\ndef"}); + +testCM("markTextCSS", function(cm) { + function present() { + var spans = cm.display.lineDiv.getElementsByTagName("span"); + for (var i = 0; i < spans.length; i++) + if (spans[i].style.color == "cyan" && span[i].textContent == "cdefg") return true; + } + var m = cm.markText(Pos(0, 2), Pos(0, 6), {css: "color: cyan"}); + m.clear(); + is(!present()); +}, {value: "abcdefgh"}); + +testCM("bookmark", function(cm) { + function p(v) { return v && Pos(v[0], v[1]); } + forEach([{a: [1, 0], b: [1, 1], c: "", d: [1, 4]}, + {a: [1, 1], b: [1, 1], c: "xx", d: [1, 7]}, + {a: [1, 4], b: [1, 5], c: "ab", d: [1, 6]}, + {a: [1, 4], b: [1, 6], c: "", d: null}, + {a: [1, 5], b: [1, 6], c: "abc", d: [1, 5]}, + {a: [1, 6], b: [1, 8], c: "", d: [1, 5]}, + {a: [1, 4], b: [1, 4], c: "\n\n", d: [3, 1]}, + {bm: [1, 9], a: [1, 1], b: [1, 1], c: "\n", d: [2, 8]}], function(test) { + cm.setValue("1234567890\n1234567890\n1234567890"); + var b = cm.setBookmark(p(test.bm) || Pos(1, 5)); + cm.replaceRange(test.c, p(test.a), p(test.b)); + eqCursorPos(b.find(), p(test.d)); + }); +}); + +testCM("bookmarkInsertLeft", function(cm) { + var br = cm.setBookmark(Pos(0, 2), {insertLeft: false}); + var bl = cm.setBookmark(Pos(0, 2), {insertLeft: true}); + cm.setCursor(Pos(0, 2)); + cm.replaceSelection("hi"); + eqCursorPos(br.find(), Pos(0, 2)); + eqCursorPos(bl.find(), Pos(0, 4)); + cm.replaceRange("", Pos(0, 4), Pos(0, 5)); + cm.replaceRange("", Pos(0, 2), Pos(0, 4)); + cm.replaceRange("", Pos(0, 1), Pos(0, 2)); + // Verify that deleting next to bookmarks doesn't kill them + eqCursorPos(br.find(), Pos(0, 1)); + eqCursorPos(bl.find(), Pos(0, 1)); +}, {value: "abcdef"}); + +testCM("bookmarkCursor", function(cm) { + var pos01 = cm.cursorCoords(Pos(0, 1)), pos11 = cm.cursorCoords(Pos(1, 1)), + pos20 = cm.cursorCoords(Pos(2, 0)), pos30 = cm.cursorCoords(Pos(3, 0)), + pos41 = cm.cursorCoords(Pos(4, 1)); + cm.setBookmark(Pos(0, 1), {widget: document.createTextNode("←"), insertLeft: true}); + cm.setBookmark(Pos(2, 0), {widget: document.createTextNode("←"), insertLeft: true}); + cm.setBookmark(Pos(1, 1), {widget: document.createTextNode("→")}); + cm.setBookmark(Pos(3, 0), {widget: document.createTextNode("→")}); + var new01 = cm.cursorCoords(Pos(0, 1)), new11 = cm.cursorCoords(Pos(1, 1)), + new20 = cm.cursorCoords(Pos(2, 0)), new30 = cm.cursorCoords(Pos(3, 0)); + near(new01.left, pos01.left, 1); + near(new01.top, pos01.top, 1); + is(new11.left > pos11.left, "at right, middle of line"); + near(new11.top == pos11.top, 1); + near(new20.left, pos20.left, 1); + near(new20.top, pos20.top, 1); + is(new30.left > pos30.left, "at right, empty line"); + near(new30.top, pos30, 1); + cm.setBookmark(Pos(4, 0), {widget: document.createTextNode("→")}); + is(cm.cursorCoords(Pos(4, 1)).left > pos41.left, "single-char bug"); +}, {value: "foo\nbar\n\n\nx\ny"}); + +testCM("multiBookmarkCursor", function(cm) { + if (phantom) return; + var ms = [], m; + function add(insertLeft) { + for (var i = 0; i < 3; ++i) { + var node = document.createElement("span"); + node.innerHTML = "X"; + ms.push(cm.setBookmark(Pos(0, 1), {widget: node, insertLeft: insertLeft})); + } + } + var base1 = cm.cursorCoords(Pos(0, 1)).left, base4 = cm.cursorCoords(Pos(0, 4)).left; + add(true); + near(base1, cm.cursorCoords(Pos(0, 1)).left, 1); + while (m = ms.pop()) m.clear(); + add(false); + near(base4, cm.cursorCoords(Pos(0, 1)).left, 1); +}, {value: "abcdefg"}); + +testCM("getAllMarks", function(cm) { + addDoc(cm, 10, 10); + var m1 = cm.setBookmark(Pos(0, 2)); + var m2 = cm.markText(Pos(0, 2), Pos(3, 2)); + var m3 = cm.markText(Pos(1, 2), Pos(1, 8)); + var m4 = cm.markText(Pos(8, 0), Pos(9, 0)); + eq(cm.getAllMarks().length, 4); + m1.clear(); + m3.clear(); + eq(cm.getAllMarks().length, 2); +}); + +testCM("setValueClears", function(cm) { + cm.addLineClass(0, "wrap", "foo"); + var mark = cm.markText(Pos(0, 0), Pos(1, 1), {inclusiveLeft: true, inclusiveRight: true}); + cm.setValue("foo"); + is(!cm.lineInfo(0).wrapClass); + is(!mark.find()); +}, {value: "a\nb"}); + +testCM("bug577", function(cm) { + cm.setValue("a\nb"); + cm.clearHistory(); + cm.setValue("fooooo"); + cm.undo(); +}); + +testCM("scrollSnap", function(cm) { + cm.setSize(100, 100); + addDoc(cm, 200, 200); + cm.setCursor(Pos(100, 180)); + var info = cm.getScrollInfo(); + is(info.left > 0 && info.top > 0); + cm.setCursor(Pos(0, 0)); + info = cm.getScrollInfo(); + is(info.left == 0 && info.top == 0, "scrolled clean to top"); + cm.setCursor(Pos(100, 180)); + cm.setCursor(Pos(199, 0)); + info = cm.getScrollInfo(); + is(info.left == 0 && info.top + 2 > info.height - cm.getScrollerElement().clientHeight, "scrolled clean to bottom"); +}); + +testCM("scrollIntoView", function(cm) { + if (phantom) return; + function test(line, ch, msg) { + var pos = Pos(line, ch); + cm.scrollIntoView(pos); + var outer = cm.getWrapperElement().getBoundingClientRect(); + var box = cm.charCoords(pos, "window"); + is(box.left >= outer.left, msg + " (left)"); + is(box.right <= outer.right, msg + " (right)"); + is(box.top >= outer.top, msg + " (top)"); + is(box.bottom <= outer.bottom, msg + " (bottom)"); + } + addDoc(cm, 200, 200); + test(199, 199, "bottom right"); + test(0, 0, "top left"); + test(100, 100, "center"); + test(199, 0, "bottom left"); + test(0, 199, "top right"); + test(100, 100, "center again"); +}); + +testCM("scrollBackAndForth", function(cm) { + addDoc(cm, 1, 200); + cm.operation(function() { + cm.scrollIntoView(Pos(199, 0)); + cm.scrollIntoView(Pos(4, 0)); + }); + is(cm.getScrollInfo().top > 0); +}); + +testCM("selectAllNoScroll", function(cm) { + addDoc(cm, 1, 200); + cm.execCommand("selectAll"); + eq(cm.getScrollInfo().top, 0); + cm.setCursor(199); + cm.execCommand("selectAll"); + is(cm.getScrollInfo().top > 0); +}); + +testCM("selectionPos", function(cm) { + if (phantom || cm.getOption("inputStyle") != "textarea") return; + cm.setSize(100, 100); + addDoc(cm, 200, 100); + cm.setSelection(Pos(1, 100), Pos(98, 100)); + var lineWidth = cm.charCoords(Pos(0, 200), "local").left; + var lineHeight = (cm.charCoords(Pos(99)).top - cm.charCoords(Pos(0)).top) / 100; + cm.scrollTo(0, 0); + var selElt = byClassName(cm.getWrapperElement(), "CodeMirror-selected"); + var outer = cm.getWrapperElement().getBoundingClientRect(); + var sawMiddle, sawTop, sawBottom; + for (var i = 0, e = selElt.length; i < e; ++i) { + var box = selElt[i].getBoundingClientRect(); + var atLeft = box.left - outer.left < 30; + var width = box.right - box.left; + var atRight = box.right - outer.left > .8 * lineWidth; + if (atLeft && atRight) { + sawMiddle = true; + is(box.bottom - box.top > 90 * lineHeight, "middle high"); + is(width > .9 * lineWidth, "middle wide"); + } else { + is(width > .4 * lineWidth, "top/bot wide enough"); + is(width < .6 * lineWidth, "top/bot slim enough"); + if (atLeft) { + sawBottom = true; + is(box.top - outer.top > 96 * lineHeight, "bot below"); + } else if (atRight) { + sawTop = true; + is(box.top - outer.top < 2.1 * lineHeight, "top above"); + } + } + } + is(sawTop && sawBottom && sawMiddle, "all parts"); +}, null); + +testCM("restoreHistory", function(cm) { + cm.setValue("abc\ndef"); + cm.replaceRange("hello", Pos(1, 0), Pos(1)); + cm.replaceRange("goop", Pos(0, 0), Pos(0)); + cm.undo(); + var storedVal = cm.getValue(), storedHist = cm.getHistory(); + if (window.JSON) storedHist = JSON.parse(JSON.stringify(storedHist)); + eq(storedVal, "abc\nhello"); + cm.setValue(""); + cm.clearHistory(); + eq(cm.historySize().undo, 0); + cm.setValue(storedVal); + cm.setHistory(storedHist); + cm.redo(); + eq(cm.getValue(), "goop\nhello"); + cm.undo(); cm.undo(); + eq(cm.getValue(), "abc\ndef"); +}); + +testCM("doubleScrollbar", function(cm) { + var dummy = document.body.appendChild(document.createElement("p")); + dummy.style.cssText = "height: 50px; overflow: scroll; width: 50px"; + var scrollbarWidth = dummy.offsetWidth + 1 - dummy.clientWidth; + document.body.removeChild(dummy); + if (scrollbarWidth < 2) return; + cm.setSize(null, 100); + addDoc(cm, 1, 300); + var wrap = cm.getWrapperElement(); + is(wrap.offsetWidth - byClassName(wrap, "CodeMirror-lines")[0].offsetWidth <= scrollbarWidth * 1.5); +}); + +testCM("weirdLinebreaks", function(cm) { + cm.setValue("foo\nbar\rbaz\r\nquux\n\rplop"); + is(cm.getValue(), "foo\nbar\nbaz\nquux\n\nplop"); + is(cm.lineCount(), 6); + cm.setValue("\n\n"); + is(cm.lineCount(), 3); +}); + +testCM("setSize", function(cm) { + cm.setSize(100, 100); + var wrap = cm.getWrapperElement(); + is(wrap.offsetWidth, 100); + is(wrap.offsetHeight, 100); + cm.setSize("100%", "3em"); + is(wrap.style.width, "100%"); + is(wrap.style.height, "3em"); + cm.setSize(null, 40); + is(wrap.style.width, "100%"); + is(wrap.style.height, "40px"); +}); + +function foldLines(cm, start, end, autoClear) { + return cm.markText(Pos(start, 0), Pos(end - 1), { + inclusiveLeft: true, + inclusiveRight: true, + collapsed: true, + clearOnEnter: autoClear + }); +} + +testCM("collapsedLines", function(cm) { + addDoc(cm, 4, 10); + var range = foldLines(cm, 4, 5), cleared = 0; + CodeMirror.on(range, "clear", function() {cleared++;}); + cm.setCursor(Pos(3, 0)); + CodeMirror.commands.goLineDown(cm); + eqCharPos(cm.getCursor(), Pos(5, 0)); + cm.replaceRange("abcdefg", Pos(3, 0), Pos(3)); + cm.setCursor(Pos(3, 6)); + CodeMirror.commands.goLineDown(cm); + eqCharPos(cm.getCursor(), Pos(5, 4)); + cm.replaceRange("ab", Pos(3, 0), Pos(3)); + cm.setCursor(Pos(3, 2)); + CodeMirror.commands.goLineDown(cm); + eqCharPos(cm.getCursor(), Pos(5, 2)); + cm.operation(function() {range.clear(); range.clear();}); + eq(cleared, 1); +}); + +testCM("collapsedRangeCoordsChar", function(cm) { + var pos_1_3 = cm.charCoords(Pos(1, 3)); + pos_1_3.left += 2; pos_1_3.top += 2; + var opts = {collapsed: true, inclusiveLeft: true, inclusiveRight: true}; + var m1 = cm.markText(Pos(0, 0), Pos(2, 0), opts); + eqCharPos(cm.coordsChar(pos_1_3), Pos(3, 3)); + m1.clear(); + var m1 = cm.markText(Pos(0, 0), Pos(1, 1), {collapsed: true, inclusiveLeft: true}); + var m2 = cm.markText(Pos(1, 1), Pos(2, 0), {collapsed: true, inclusiveRight: true}); + eqCharPos(cm.coordsChar(pos_1_3), Pos(3, 3)); + m1.clear(); m2.clear(); + var m1 = cm.markText(Pos(0, 0), Pos(1, 6), opts); + eqCharPos(cm.coordsChar(pos_1_3), Pos(3, 3)); +}, {value: "123456\nabcdef\nghijkl\nmnopqr\n"}); + +testCM("collapsedRangeBetweenLinesSelected", function(cm) { + if (cm.getOption("inputStyle") != "textarea") return; + var widget = document.createElement("span"); + widget.textContent = "\u2194"; + cm.markText(Pos(0, 3), Pos(1, 0), {replacedWith: widget}); + cm.setSelection(Pos(0, 3), Pos(1, 0)); + var selElts = byClassName(cm.getWrapperElement(), "CodeMirror-selected"); + for (var i = 0, w = 0; i < selElts.length; i++) + w += selElts[i].offsetWidth; + is(w > 0); +}, {value: "one\ntwo"}); + +testCM("randomCollapsedRanges", function(cm) { + addDoc(cm, 20, 500); + cm.operation(function() { + for (var i = 0; i < 200; i++) { + var start = Pos(Math.floor(Math.random() * 500), Math.floor(Math.random() * 20)); + if (i % 4) + try { cm.markText(start, Pos(start.line + 2, 1), {collapsed: true}); } + catch(e) { if (!/overlapping/.test(String(e))) throw e; } + else + cm.markText(start, Pos(start.line, start.ch + 4), {"className": "foo"}); + } + }); +}); + +testCM("hiddenLinesAutoUnfold", function(cm) { + var range = foldLines(cm, 1, 3, true), cleared = 0; + CodeMirror.on(range, "clear", function() {cleared++;}); + cm.setCursor(Pos(3, 0)); + eq(cleared, 0); + cm.execCommand("goCharLeft"); + eq(cleared, 1); + range = foldLines(cm, 1, 3, true); + CodeMirror.on(range, "clear", function() {cleared++;}); + eqCursorPos(cm.getCursor(), Pos(3, 0)); + cm.setCursor(Pos(0, 3)); + cm.execCommand("goCharRight"); + eq(cleared, 2); +}, {value: "abc\ndef\nghi\njkl"}); + +testCM("hiddenLinesSelectAll", function(cm) { // Issue #484 + addDoc(cm, 4, 20); + foldLines(cm, 0, 10); + foldLines(cm, 11, 20); + CodeMirror.commands.selectAll(cm); + eqCursorPos(cm.getCursor(true), Pos(10, 0)); + eqCursorPos(cm.getCursor(false), Pos(10, 4)); +}); + + +testCM("everythingFolded", function(cm) { + addDoc(cm, 2, 2); + function enterPress() { + cm.triggerOnKeyDown({type: "keydown", keyCode: 13, preventDefault: function(){}, stopPropagation: function(){}}); + } + var fold = foldLines(cm, 0, 2); + enterPress(); + eq(cm.getValue(), "xx\nxx"); + fold.clear(); + fold = foldLines(cm, 0, 2, true); + eq(fold.find(), null); + enterPress(); + eq(cm.getValue(), "\nxx\nxx"); +}); + +testCM("structuredFold", function(cm) { + if (phantom) return; + addDoc(cm, 4, 8); + var range = cm.markText(Pos(1, 2), Pos(6, 2), { + replacedWith: document.createTextNode("Q") + }); + cm.setCursor(0, 3); + CodeMirror.commands.goLineDown(cm); + eqCharPos(cm.getCursor(), Pos(6, 2)); + CodeMirror.commands.goCharLeft(cm); + eqCharPos(cm.getCursor(), Pos(1, 2)); + CodeMirror.commands.delCharAfter(cm); + eq(cm.getValue(), "xxxx\nxxxx\nxxxx"); + addDoc(cm, 4, 8); + range = cm.markText(Pos(1, 2), Pos(6, 2), { + replacedWith: document.createTextNode("M"), + clearOnEnter: true + }); + var cleared = 0; + CodeMirror.on(range, "clear", function(){++cleared;}); + cm.setCursor(0, 3); + CodeMirror.commands.goLineDown(cm); + eqCharPos(cm.getCursor(), Pos(6, 2)); + CodeMirror.commands.goCharLeft(cm); + eqCharPos(cm.getCursor(), Pos(6, 1)); + eq(cleared, 1); + range.clear(); + eq(cleared, 1); + range = cm.markText(Pos(1, 2), Pos(6, 2), { + replacedWith: document.createTextNode("Q"), + clearOnEnter: true + }); + range.clear(); + cm.setCursor(1, 2); + CodeMirror.commands.goCharRight(cm); + eqCharPos(cm.getCursor(), Pos(1, 3)); + range = cm.markText(Pos(2, 0), Pos(4, 4), { + replacedWith: document.createTextNode("M") + }); + cm.setCursor(1, 0); + CodeMirror.commands.goLineDown(cm); + eqCharPos(cm.getCursor(), Pos(2, 0)); +}, null); + +testCM("nestedFold", function(cm) { + addDoc(cm, 10, 3); + function fold(ll, cl, lr, cr) { + return cm.markText(Pos(ll, cl), Pos(lr, cr), {collapsed: true}); + } + var inner1 = fold(0, 6, 1, 3), inner2 = fold(0, 2, 1, 8), outer = fold(0, 1, 2, 3), inner0 = fold(0, 5, 0, 6); + cm.setCursor(0, 1); + CodeMirror.commands.goCharRight(cm); + eqCursorPos(cm.getCursor(), Pos(2, 3)); + inner0.clear(); + CodeMirror.commands.goCharLeft(cm); + eqCursorPos(cm.getCursor(), Pos(0, 1)); + outer.clear(); + CodeMirror.commands.goCharRight(cm); + eqCursorPos(cm.getCursor(), Pos(0, 2, "before")); + CodeMirror.commands.goCharRight(cm); + eqCursorPos(cm.getCursor(), Pos(1, 8)); + inner2.clear(); + CodeMirror.commands.goCharLeft(cm); + eqCursorPos(cm.getCursor(), Pos(1, 7, "after")); + cm.setCursor(0, 5); + CodeMirror.commands.goCharRight(cm); + eqCursorPos(cm.getCursor(), Pos(0, 6, "before")); + CodeMirror.commands.goCharRight(cm); + eqCursorPos(cm.getCursor(), Pos(1, 3)); +}); + +testCM("badNestedFold", function(cm) { + addDoc(cm, 4, 4); + cm.markText(Pos(0, 2), Pos(3, 2), {collapsed: true}); + var caught; + try {cm.markText(Pos(0, 1), Pos(0, 3), {collapsed: true});} + catch(e) {caught = e;} + is(caught instanceof Error, "no error"); + is(/overlap/i.test(caught.message), "wrong error"); +}); + +testCM("nestedFoldOnSide", function(cm) { + var m1 = cm.markText(Pos(0, 1), Pos(2, 1), {collapsed: true, inclusiveRight: true}); + var m2 = cm.markText(Pos(0, 1), Pos(0, 2), {collapsed: true}); + cm.markText(Pos(0, 1), Pos(0, 2), {collapsed: true}).clear(); + try { cm.markText(Pos(0, 1), Pos(0, 2), {collapsed: true, inclusiveLeft: true}); } + catch(e) { var caught = e; } + is(caught && /overlap/i.test(caught.message)); + var m3 = cm.markText(Pos(2, 0), Pos(2, 1), {collapsed: true}); + var m4 = cm.markText(Pos(2, 0), Pos(2, 1), {collapse: true, inclusiveRight: true}); + m1.clear(); m4.clear(); + m1 = cm.markText(Pos(0, 1), Pos(2, 1), {collapsed: true}); + cm.markText(Pos(2, 0), Pos(2, 1), {collapsed: true}).clear(); + try { cm.markText(Pos(2, 0), Pos(2, 1), {collapsed: true, inclusiveRight: true}); } + catch(e) { var caught = e; } + is(caught && /overlap/i.test(caught.message)); +}, {value: "ab\ncd\ef"}); + +testCM("editInFold", function(cm) { + addDoc(cm, 4, 6); + var m = cm.markText(Pos(1, 2), Pos(3, 2), {collapsed: true}); + cm.replaceRange("", Pos(0, 0), Pos(1, 3)); + cm.replaceRange("", Pos(2, 1), Pos(3, 3)); + cm.replaceRange("a\nb\nc\nd", Pos(0, 1), Pos(1, 0)); + cm.cursorCoords(Pos(0, 0)); +}); + +testCM("wrappingInlineWidget", function(cm) { + cm.setSize("11em"); + var w = document.createElement("span"); + w.style.color = "red"; + w.innerHTML = "one two three four"; + cm.markText(Pos(0, 6), Pos(0, 9), {replacedWith: w}); + var cur0 = cm.cursorCoords(Pos(0, 0)), cur1 = cm.cursorCoords(Pos(0, 10)); + is(cur0.top < cur1.top); + is(cur0.bottom < cur1.bottom); + var curL = cm.cursorCoords(Pos(0, 6)), curR = cm.cursorCoords(Pos(0, 9)); + eq(curL.top, cur0.top); + eq(curL.bottom, cur0.bottom); + eq(curR.top, cur1.top); + eq(curR.bottom, cur1.bottom); + cm.replaceRange("", Pos(0, 9), Pos(0)); + curR = cm.cursorCoords(Pos(0, 9)); + if (phantom) return; + eq(curR.top, cur1.top); + eq(curR.bottom, cur1.bottom); +}, {value: "1 2 3 xxx 4", lineWrapping: true}); + +testCM("showEmptyWidgetSpan", function(cm) { + var marker = cm.markText(Pos(0, 2), Pos(0, 2), { + clearWhenEmpty: false, + replacedWith: document.createTextNode("X") + }); + var text = cm.display.view[0].text; + eq(text.textContent || text.innerText, "abXc"); +}, {value: "abc"}); + +testCM("changedInlineWidget", function(cm) { + cm.setSize("10em"); + var w = document.createElement("span"); + w.innerHTML = "x"; + var m = cm.markText(Pos(0, 4), Pos(0, 5), {replacedWith: w}); + w.innerHTML = "and now the widget is really really long all of a sudden and a scrollbar is needed"; + m.changed(); + var hScroll = byClassName(cm.getWrapperElement(), "CodeMirror-hscrollbar")[0]; + is(hScroll.scrollWidth > hScroll.clientWidth); +}, {value: "hello there"}); + +testCM("changedBookmark", function(cm) { + cm.setSize("10em"); + var w = document.createElement("span"); + w.innerHTML = "x"; + var m = cm.setBookmark(Pos(0, 4), {widget: w}); + w.innerHTML = "and now the widget is really really long all of a sudden and a scrollbar is needed"; + m.changed(); + var hScroll = byClassName(cm.getWrapperElement(), "CodeMirror-hscrollbar")[0]; + is(hScroll.scrollWidth > hScroll.clientWidth); +}, {value: "abcdefg"}); + +testCM("inlineWidget", function(cm) { + var w = cm.setBookmark(Pos(0, 2), {widget: document.createTextNode("uu")}); + cm.setCursor(0, 2); + CodeMirror.commands.goLineDown(cm); + eqCharPos(cm.getCursor(), Pos(1, 4)); + cm.setCursor(0, 2); + cm.replaceSelection("hi"); + eqCharPos(w.find(), Pos(0, 2)); + cm.setCursor(0, 1); + cm.replaceSelection("ay"); + eqCharPos(w.find(), Pos(0, 4)); + eq(cm.getLine(0), "uayuhiuu"); +}, {value: "uuuu\nuuuuuu"}); + +testCM("wrappingAndResizing", function(cm) { + cm.setSize(null, "auto"); + cm.setOption("lineWrapping", true); + var wrap = cm.getWrapperElement(), h0 = wrap.offsetHeight; + var doc = "xxx xxx xxx xxx xxx"; + cm.setValue(doc); + for (var step = 10, w = cm.charCoords(Pos(0, 18), "div").right;; w += step) { + cm.setSize(w); + if (wrap.offsetHeight <= h0 * (opera_lt10 ? 1.2 : 1.5)) { + if (step == 10) { w -= 10; step = 1; } + else break; + } + } + // Ensure that putting the cursor at the end of the maximally long + // line doesn't cause wrapping to happen. + cm.setCursor(Pos(0, doc.length)); + eq(wrap.offsetHeight, h0); + cm.replaceSelection("x"); + is(wrap.offsetHeight > h0, "wrapping happens"); + // Now add a max-height and, in a document consisting of + // almost-wrapped lines, go over it so that a scrollbar appears. + cm.setValue(doc + "\n" + doc + "\n"); + cm.getScrollerElement().style.maxHeight = "100px"; + cm.replaceRange("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n!\n", Pos(2, 0)); + forEach([Pos(0, doc.length), Pos(0, doc.length - 1), + Pos(0, 0), Pos(1, doc.length), Pos(1, doc.length - 1)], + function(pos) { + var coords = cm.charCoords(pos); + eqCharPos(pos, cm.coordsChar({left: coords.left + 2, top: coords.top + 5})); + }); +}, null, ie_lt8); + +testCM("measureEndOfLine", function(cm) { + if (phantom) return; + cm.setSize(null, "auto"); + var inner = byClassName(cm.getWrapperElement(), "CodeMirror-lines")[0].firstChild; + var lh = inner.offsetHeight; + for (var step = 10, w = cm.charCoords(Pos(0, 7), "div").right;; w += step) { + cm.setSize(w); + if (inner.offsetHeight < 2.5 * lh) { + if (step == 10) { w -= 10; step = 1; } + else break; + } + } + cm.setValue(cm.getValue() + "\n\n"); + var endPos = cm.charCoords(Pos(0, 18), "local"); + is(endPos.top > lh * .8, "not at top"); + is(endPos.left > w - 20, "at right"); + endPos = cm.charCoords(Pos(0, 18)); + eqCursorPos(cm.coordsChar({left: endPos.left, top: endPos.top + 5}), Pos(0, 18, "before")); + + var wrapPos = cm.cursorCoords(Pos(0, 9, "before")); + is(wrapPos.top < endPos.top, "wrapPos is actually in first line"); + eqCursorPos(cm.coordsChar({left: wrapPos.left + 10, top: wrapPos.top}), Pos(0, 9, "before")); +}, {mode: "text/html", value: "<!-- foo barrr -->", lineWrapping: true}, ie_lt8 || opera_lt10); + +testCM("measureWrappedEndOfLine", function(cm) { + if (phantom) return; + cm.setSize(null, "auto"); + var inner = byClassName(cm.getWrapperElement(), "CodeMirror-lines")[0].firstChild; + var lh = inner.offsetHeight; + for (var step = 10, w = cm.charCoords(Pos(0, 7), "div").right;; w += step) { + cm.setSize(w); + if (inner.offsetHeight < 2.5 * lh) { + if (step == 10) { w -= 10; step = 1; } + else break; + } + } + for (var i = 0; i < 3; ++i) { + var endPos = cm.charCoords(Pos(0, 12)); // Next-to-last since last would wrap (#1862) + endPos.left += w; // Add width of editor just to be sure that we are behind last character + eqCursorPos(cm.coordsChar(endPos), Pos(0, 13, "before")); + endPos.left += w * 100; + eqCursorPos(cm.coordsChar(endPos), Pos(0, 13, "before")); + cm.setValue("0123456789abcابجابجابجابج"); + if (i == 1) { + var node = document.createElement("div"); + node.innerHTML = "hi"; node.style.height = "30px"; + cm.addLineWidget(0, node, {above: true}); + } + } +}, {mode: "text/html", value: "0123456789abcde0123456789", lineWrapping: true}, ie_lt8 || opera_lt10); + +testCM("measureEndOfLineBidi", function(cm) { + eqCursorPos(cm.coordsChar({left: 5000, top: cm.charCoords(Pos(0, 0)).top}), Pos(0, 8, "after")) +}, {value: "إإإإuuuuإإإإ"}) + +testCM("measureWrappedBidiLevel2", function(cm) { + cm.setSize(cm.charCoords(Pos(0, 6), "editor").right + 60) + var c9 = cm.charCoords(Pos(0, 9)) + eqCharPos(cm.coordsChar({left: c9.right - 1, top: c9.top + 1}), Pos(0, 9)) +}, {value: "foobar إإ إإ إإ إإ 555 بببببب", lineWrapping: true}) + +testCM("measureWrappedBeginOfLine", function(cm) { + if (phantom) return; + cm.setSize(null, "auto"); + var inner = byClassName(cm.getWrapperElement(), "CodeMirror-lines")[0].firstChild; + var lh = inner.offsetHeight; + for (var step = 10, w = cm.charCoords(Pos(0, 7), "div").right;; w += step) { + cm.setSize(w); + if (inner.offsetHeight < 2.5 * lh) { + if (step == 10) { w -= 10; step = 1; } + else break; + } + } + var beginOfSecondLine = Pos(0, 13, "after"); + for (var i = 0; i < 2; ++i) { + var beginPos = cm.charCoords(Pos(0, 0)); + beginPos.left -= w; + eqCursorPos(cm.coordsChar(beginPos), Pos(0, 0, "after")); + beginPos = cm.cursorCoords(beginOfSecondLine); + beginPos.left = 0; + eqCursorPos(cm.coordsChar(beginPos), beginOfSecondLine); + cm.setValue("0123456789abcابجابجابجابج"); + beginOfSecondLine = Pos(0, 25, "before"); + } +}, {mode: "text/html", value: "0123456789abcde0123456789", lineWrapping: true}); + +testCM("scrollVerticallyAndHorizontally", function(cm) { + if (cm.getOption("inputStyle") != "textarea") return; + cm.setSize(100, 100); + addDoc(cm, 40, 40); + cm.setCursor(39); + var wrap = cm.getWrapperElement(), bar = byClassName(wrap, "CodeMirror-vscrollbar")[0]; + is(bar.offsetHeight < wrap.offsetHeight, "vertical scrollbar limited by horizontal one"); + var cursorBox = byClassName(wrap, "CodeMirror-cursor")[0].getBoundingClientRect(); + var editorBox = wrap.getBoundingClientRect(); + is(cursorBox.bottom < editorBox.top + cm.getScrollerElement().clientHeight, + "bottom line visible"); +}, {lineNumbers: true}); + +testCM("moveVstuck", function(cm) { + var lines = byClassName(cm.getWrapperElement(), "CodeMirror-lines")[0].firstChild, h0 = lines.offsetHeight; + var val = "fooooooooooooooooooooooooo baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaar\n"; + cm.setValue(val); + for (var w = cm.charCoords(Pos(0, 26), "div").right * 2.8;; w += 5) { + cm.setSize(w); + if (lines.offsetHeight <= 3.5 * h0) break; + } + cm.setCursor(Pos(0, val.length - 1)); + cm.moveV(-1, "line"); + eqCursorPos(cm.getCursor(), Pos(0, 27, "before")); + is(cm.cursorCoords(null, "local").top < h0, "cursor is in first visual line"); +}, {lineWrapping: true}, ie_lt8 || opera_lt10); + +testCM("collapseOnMove", function(cm) { + cm.setSelection(Pos(0, 1), Pos(2, 4)); + cm.execCommand("goLineUp"); + is(!cm.somethingSelected()); + eqCharPos(cm.getCursor(), Pos(0, 1)); + cm.setSelection(Pos(0, 1), Pos(2, 4)); + cm.execCommand("goPageDown"); + is(!cm.somethingSelected()); + eqCharPos(cm.getCursor(), Pos(2, 4)); + cm.execCommand("goLineUp"); + cm.execCommand("goLineUp"); + eqCharPos(cm.getCursor(), Pos(0, 4)); + cm.setSelection(Pos(0, 1), Pos(2, 4)); + cm.execCommand("goCharLeft"); + is(!cm.somethingSelected()); + eqCharPos(cm.getCursor(), Pos(0, 1)); +}, {value: "aaaaa\nb\nccccc"}); + +testCM("clickTab", function(cm) { + var p0 = cm.charCoords(Pos(0, 0)); + eqCharPos(cm.coordsChar({left: p0.left + 5, top: p0.top + 5}), Pos(0, 0)); + eqCharPos(cm.coordsChar({left: p0.right - 5, top: p0.top + 5}), Pos(0, 1)); +}, {value: "\t\n\n", lineWrapping: true, tabSize: 8}); + +testCM("verticalScroll", function(cm) { + cm.setSize(100, 200); + cm.setValue("foo\nbar\nbaz\n"); + var sc = cm.getScrollerElement(), baseWidth = sc.scrollWidth; + cm.replaceRange("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah", Pos(0, 0), Pos(0)); + is(sc.scrollWidth > baseWidth, "scrollbar present"); + cm.replaceRange("foo", Pos(0, 0), Pos(0)); + if (!phantom) eq(sc.scrollWidth, baseWidth, "scrollbar gone"); + cm.replaceRange("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah", Pos(0, 0), Pos(0)); + cm.replaceRange("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbh", Pos(1, 0), Pos(1)); + is(sc.scrollWidth > baseWidth, "present again"); + var curWidth = sc.scrollWidth; + cm.replaceRange("foo", Pos(0, 0), Pos(0)); + is(sc.scrollWidth < curWidth, "scrollbar smaller"); + is(sc.scrollWidth > baseWidth, "but still present"); +}); + +testCM("extraKeys", function(cm) { + var outcome; + function fakeKey(expected, code, props) { + if (typeof code == "string") code = code.charCodeAt(0); + var e = {type: "keydown", keyCode: code, preventDefault: function(){}, stopPropagation: function(){}}; + if (props) for (var n in props) e[n] = props[n]; + outcome = null; + cm.triggerOnKeyDown(e); + eq(outcome, expected); + } + CodeMirror.commands.testCommand = function() {outcome = "tc";}; + CodeMirror.commands.goTestCommand = function() {outcome = "gtc";}; + cm.setOption("extraKeys", {"Shift-X": function() {outcome = "sx";}, + "X": function() {outcome = "x";}, + "Ctrl-Alt-U": function() {outcome = "cau";}, + "End": "testCommand", + "Home": "goTestCommand", + "Tab": false}); + fakeKey(null, "U"); + fakeKey("cau", "U", {ctrlKey: true, altKey: true}); + fakeKey(null, "U", {shiftKey: true, ctrlKey: true, altKey: true}); + fakeKey("x", "X"); + fakeKey("sx", "X", {shiftKey: true}); + fakeKey("tc", 35); + fakeKey(null, 35, {shiftKey: true}); + fakeKey("gtc", 36); + fakeKey("gtc", 36, {shiftKey: true}); + fakeKey(null, 9); +}, null, window.opera && mac); + +testCM("wordMovementCommands", function(cm) { + cm.execCommand("goWordLeft"); + eqCursorPos(cm.getCursor(), Pos(0, 0)); + cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); + eqCursorPos(cm.getCursor(), Pos(0, 7, "before")); + cm.execCommand("goWordLeft"); + eqCursorPos(cm.getCursor(), Pos(0, 5, "after")); + cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); + eqCursorPos(cm.getCursor(), Pos(0, 12, "before")); + cm.execCommand("goWordLeft"); + eqCursorPos(cm.getCursor(), Pos(0, 9, "after")); + cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); + eqCursorPos(cm.getCursor(), Pos(0, 24, "before")); + cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); + eqCursorPos(cm.getCursor(), Pos(1, 9, "before")); + cm.execCommand("goWordRight"); + eqCursorPos(cm.getCursor(), Pos(1, 13, "before")); + cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); + eqCharPos(cm.getCursor(), Pos(2, 0)); +}, {value: "this is (the) firstline.\na foo12\u00e9\u00f8\u00d7bar\n"}); + +testCM("groupMovementCommands", function(cm) { + cm.execCommand("goGroupLeft"); + eqCursorPos(cm.getCursor(), Pos(0, 0)); + cm.execCommand("goGroupRight"); + eqCursorPos(cm.getCursor(), Pos(0, 4, "before")); + cm.execCommand("goGroupRight"); + eqCursorPos(cm.getCursor(), Pos(0, 7, "before")); + cm.execCommand("goGroupRight"); + eqCursorPos(cm.getCursor(), Pos(0, 10, "before")); + cm.execCommand("goGroupLeft"); + eqCursorPos(cm.getCursor(), Pos(0, 7, "after")); + cm.execCommand("goGroupRight"); cm.execCommand("goGroupRight"); cm.execCommand("goGroupRight"); + eqCursorPos(cm.getCursor(), Pos(0, 15, "before")); + cm.setCursor(Pos(0, 17)); + cm.execCommand("goGroupLeft"); + eqCursorPos(cm.getCursor(), Pos(0, 16, "after")); + cm.execCommand("goGroupLeft"); + eqCursorPos(cm.getCursor(), Pos(0, 14, "after")); + cm.execCommand("goGroupRight"); cm.execCommand("goGroupRight"); + eqCursorPos(cm.getCursor(), Pos(0, 20, "before")); + cm.execCommand("goGroupRight"); + eqCursorPos(cm.getCursor(), Pos(1, 0, "after")); + cm.execCommand("goGroupRight"); + eqCursorPos(cm.getCursor(), Pos(1, 2, "before")); + cm.execCommand("goGroupRight"); + eqCursorPos(cm.getCursor(), Pos(1, 5, "before")); + cm.execCommand("goGroupLeft"); cm.execCommand("goGroupLeft"); + eqCursorPos(cm.getCursor(), Pos(1, 0, "after")); + cm.execCommand("goGroupLeft"); + eqCursorPos(cm.getCursor(), Pos(0, 20, "after")); + cm.execCommand("goGroupLeft"); + eqCursorPos(cm.getCursor(), Pos(0, 16, "after")); +}, {value: "booo ba---quux. ffff\n abc d"}); + +testCM("groupsAndWhitespace", function(cm) { + var positions = [Pos(0, 0), Pos(0, 2), Pos(0, 5), Pos(0, 9), Pos(0, 11), + Pos(1, 0), Pos(1, 2), Pos(1, 5)]; + for (var i = 1; i < positions.length; i++) { + cm.execCommand("goGroupRight"); + eqCharPos(cm.getCursor(), positions[i]); + } + for (var i = positions.length - 2; i >= 0; i--) { + cm.execCommand("goGroupLeft"); + eqCharPos(cm.getCursor(), i == 2 ? Pos(0, 6, "before") : positions[i]); + } +}, {value: " foo +++ \n bar"}); + +testCM("charMovementCommands", function(cm) { + cm.execCommand("goCharLeft"); cm.execCommand("goColumnLeft"); + eqCursorPos(cm.getCursor(), Pos(0, 0)); + cm.execCommand("goCharRight"); cm.execCommand("goCharRight"); + eqCursorPos(cm.getCursor(), Pos(0, 2, "before")); + cm.setCursor(Pos(1, 0)); + cm.execCommand("goColumnLeft"); + eqCursorPos(cm.getCursor(), Pos(1, 0)); + cm.execCommand("goCharLeft"); + eqCursorPos(cm.getCursor(), Pos(0, 5, "before")); + cm.execCommand("goColumnRight"); + eqCursorPos(cm.getCursor(), Pos(0, 5, "before")); + cm.execCommand("goCharRight"); + eqCursorPos(cm.getCursor(), Pos(1, 0, "after")); + cm.execCommand("goLineEnd"); + eqCursorPos(cm.getCursor(), Pos(1, 5, "before")); + cm.execCommand("goLineStartSmart"); + eqCursorPos(cm.getCursor(), Pos(1, 1, "after")); + cm.execCommand("goLineStartSmart"); + eqCursorPos(cm.getCursor(), Pos(1, 0, "after")); + cm.setCursor(Pos(2, 0)); + cm.execCommand("goCharRight"); cm.execCommand("goColumnRight"); + eqCursorPos(cm.getCursor(), Pos(2, 0)); +}, {value: "line1\n ine2\n"}); + +testCM("verticalMovementCommands", function(cm) { + cm.execCommand("goLineUp"); + eqCharPos(cm.getCursor(), Pos(0, 0)); + cm.execCommand("goLineDown"); + if (!phantom) // This fails in PhantomJS, though not in a real Webkit + eqCharPos(cm.getCursor(), Pos(1, 0)); + cm.setCursor(Pos(1, 12)); + cm.execCommand("goLineDown"); + eqCharPos(cm.getCursor(), Pos(2, 5)); + cm.execCommand("goLineDown"); + eqCharPos(cm.getCursor(), Pos(3, 0)); + cm.execCommand("goLineUp"); + eqCharPos(cm.getCursor(), Pos(2, 5)); + cm.execCommand("goLineUp"); + eqCharPos(cm.getCursor(), Pos(1, 12)); + cm.execCommand("goPageDown"); + eqCharPos(cm.getCursor(), Pos(5, 0)); + cm.execCommand("goPageDown"); cm.execCommand("goLineDown"); + eqCharPos(cm.getCursor(), Pos(5, 0)); + cm.execCommand("goPageUp"); + eqCharPos(cm.getCursor(), Pos(0, 0)); +}, {value: "line1\nlong long line2\nline3\n\nline5\n"}); + +testCM("verticalMovementCommandsWrapping", function(cm) { + cm.setSize(120); + cm.setCursor(Pos(0, 5)); + cm.execCommand("goLineDown"); + eq(cm.getCursor().line, 0); + is(cm.getCursor().ch > 5, "moved beyond wrap"); + for (var i = 0; ; ++i) { + is(i < 20, "no endless loop"); + cm.execCommand("goLineDown"); + var cur = cm.getCursor(); + if (cur.line == 1) eq(cur.ch, 5); + if (cur.line == 2) { eq(cur.ch, 1); break; } + } +}, {value: "a very long line that wraps around somehow so that we can test cursor movement\nshortone\nk", + lineWrapping: true}); + +testCM("verticalMovementCommandsSingleLine", function(cm) { + cm.display.wrapper.style.height = "auto"; + cm.refresh(); + cm.execCommand("goLineUp"); + eqCursorPos(cm.getCursor(), Pos(0, 0)); + cm.execCommand("goLineDown"); + eqCursorPos(cm.getCursor(), Pos(0, 11)); + cm.setCursor(Pos(0, 5)); + cm.execCommand("goLineDown"); + eqCursorPos(cm.getCursor(), Pos(0, 11)); + cm.execCommand("goLineDown"); + eqCursorPos(cm.getCursor(), Pos(0, 11)); + cm.execCommand("goLineUp"); + eqCursorPos(cm.getCursor(), Pos(0, 0)); + cm.execCommand("goLineUp"); + eqCursorPos(cm.getCursor(), Pos(0, 0)); + cm.execCommand("goPageDown"); + eqCursorPos(cm.getCursor(), Pos(0, 11)); + cm.execCommand("goPageDown"); cm.execCommand("goLineDown"); + eqCursorPos(cm.getCursor(), Pos(0, 11)); + cm.execCommand("goPageUp"); + eqCursorPos(cm.getCursor(), Pos(0, 0)); + cm.setCursor(Pos(0, 5)); + cm.execCommand("goPageUp"); + eqCursorPos(cm.getCursor(), Pos(0, 0)); + cm.setCursor(Pos(0, 5)); + cm.execCommand("goPageDown"); + eqCursorPos(cm.getCursor(), Pos(0, 11)); +}, {value: "single line"}); + + +testCM("rtlMovement", function(cm) { + if (cm.getOption("inputStyle") != "textarea") return; + forEach(["خحج", "خحabcخحج", "abخحخحجcd", "abخde", "abخح2342خ1حج", "خ1ح2خح3حxج", + "خحcd", "1خحcd", "abcdeح1ج", "خمرحبها مها!", "foobarر", "خ ة ق", + "<img src=\"/בדיקה3.jpg\">", "يتم السحب في 05 فبراير 2014"], function(line) { + cm.setValue(line + "\n"); cm.execCommand("goLineStart"); + var cursors = byClassName(cm.getWrapperElement(), "CodeMirror-cursors")[0]; + var cursor = cursors.firstChild; + var prevX = cursor.offsetLeft, prevY = cursor.offsetTop; + for (var i = 0; i <= line.length; ++i) { + cm.execCommand("goCharRight"); + cursor = cursors.firstChild; + if (i == line.length) is(cursor.offsetTop > prevY, "next line"); + else is(cursor.offsetLeft > prevX, "moved right"); + prevX = cursor.offsetLeft; prevY = cursor.offsetTop; + } + cm.setCursor(0, 0); cm.execCommand("goLineEnd"); + prevX = cursors.firstChild.offsetLeft; + for (var i = 0; i < line.length; ++i) { + cm.execCommand("goCharLeft"); + cursor = cursors.firstChild; + is(cursor.offsetLeft < prevX, "moved left"); + prevX = cursor.offsetLeft; + } + }); +}, null, ie_lt9); + +// Verify that updating a line clears its bidi ordering +testCM("bidiUpdate", function(cm) { + cm.setCursor(Pos(0, 2, "before")); + cm.replaceSelection("خحج", "start"); + cm.execCommand("goCharRight"); + eqCursorPos(cm.getCursor(), Pos(0, 6, "before")); +}, {value: "abcd\n"}); + +testCM("movebyTextUnit", function(cm) { + cm.setValue("בְּרֵאשִ\nééé́\n"); + cm.execCommand("goLineStart"); + for (var i = 0; i < 4; ++i) cm.execCommand("goCharRight"); + eqCursorPos(cm.getCursor(), Pos(0, 0, "after")); + cm.execCommand("goCharRight"); + eqCursorPos(cm.getCursor(), Pos(1, 0, "after")); + cm.execCommand("goCharRight"); + cm.execCommand("goCharRight"); + eqCursorPos(cm.getCursor(), Pos(1, 4, "before")); + cm.execCommand("goCharRight"); + eqCursorPos(cm.getCursor(), Pos(1, 7, "before")); +}); + +testCM("lineChangeEvents", function(cm) { + addDoc(cm, 3, 5); + var log = [], want = ["ch 0", "ch 1", "del 2", "ch 0", "ch 0", "del 1", "del 3", "del 4"]; + for (var i = 0; i < 5; ++i) { + CodeMirror.on(cm.getLineHandle(i), "delete", function(i) { + return function() {log.push("del " + i);}; + }(i)); + CodeMirror.on(cm.getLineHandle(i), "change", function(i) { + return function() {log.push("ch " + i);}; + }(i)); + } + cm.replaceRange("x", Pos(0, 1)); + cm.replaceRange("xy", Pos(1, 1), Pos(2)); + cm.replaceRange("foo\nbar", Pos(0, 1)); + cm.replaceRange("", Pos(0, 0), Pos(cm.lineCount())); + eq(log.length, want.length, "same length"); + for (var i = 0; i < log.length; ++i) + eq(log[i], want[i]); +}); + +testCM("scrollEntirelyToRight", function(cm) { + if (phantom || cm.getOption("inputStyle") != "textarea") return; + addDoc(cm, 500, 2); + cm.setCursor(Pos(0, 500)); + var wrap = cm.getWrapperElement(), cur = byClassName(wrap, "CodeMirror-cursor")[0]; + is(wrap.getBoundingClientRect().right > cur.getBoundingClientRect().left); +}); + +testCM("lineWidgets", function(cm) { + addDoc(cm, 500, 3); + var last = cm.charCoords(Pos(2, 0)); + var node = document.createElement("div"); + node.innerHTML = "hi"; + var widget = cm.addLineWidget(1, node); + is(last.top < cm.charCoords(Pos(2, 0)).top, "took up space"); + cm.setCursor(Pos(1, 1)); + cm.execCommand("goLineDown"); + eqCharPos(cm.getCursor(), Pos(2, 1)); + cm.execCommand("goLineUp"); + eqCharPos(cm.getCursor(), Pos(1, 1)); +}); + +testCM("lineWidgetFocus", function(cm) { + var place = document.getElementById("testground"); + place.className = "offscreen"; + try { + addDoc(cm, 500, 10); + var node = document.createElement("input"); + var widget = cm.addLineWidget(1, node); + node.focus(); + eq(document.activeElement, node); + cm.replaceRange("new stuff", Pos(1, 0)); + eq(document.activeElement, node); + } finally { + place.className = ""; + } +}); + +testCM("lineWidgetCautiousRedraw", function(cm) { + var node = document.createElement("div"); + node.innerHTML = "hahah"; + var w = cm.addLineWidget(0, node); + var redrawn = false; + w.on("redraw", function() { redrawn = true; }); + cm.replaceSelection("0"); + is(!redrawn); +}, {value: "123\n456"}); + + +var knownScrollbarWidth; +function scrollbarWidth(measure) { + if (knownScrollbarWidth != null) return knownScrollbarWidth; + var div = document.createElement('div'); + div.style.cssText = "width: 50px; height: 50px; overflow-x: scroll"; + document.body.appendChild(div); + knownScrollbarWidth = div.offsetHeight - div.clientHeight; + document.body.removeChild(div); + return knownScrollbarWidth || 0; +} + +testCM("lineWidgetChanged", function(cm) { + addDoc(cm, 2, 300); + var halfScrollbarWidth = scrollbarWidth(cm.display.measure)/2; + cm.setOption('lineNumbers', true); + cm.setSize(600, cm.defaultTextHeight() * 50); + cm.scrollTo(null, cm.heightAtLine(125, "local")); + + var expectedWidgetHeight = 60; + var expectedLinesInWidget = 3; + function w() { + var node = document.createElement("div"); + // we use these children with just under half width of the line to check measurements are made with correct width + // when placed in the measure div. + // If the widget is measured at a width much narrower than it is displayed at, the underHalf children will span two lines and break the test. + // If the widget is measured at a width much wider than it is displayed at, the overHalf children will combine and break the test. + // Note that this test only checks widgets where coverGutter is true, because these require extra styling to get the width right. + // It may also be worthwhile to check this for non-coverGutter widgets. + // Visually: + // Good: + // | ------------- display width ------------- | + // | ------- widget-width when measured ------ | + // | | -- under-half -- | | -- under-half -- | | + // | | --- over-half --- | | + // | | --- over-half --- | | + // Height: measured as 3 lines, same as it will be when actually displayed + + // Bad (too narrow): + // | ------------- display width ------------- | + // | ------ widget-width when measured ----- | < -- uh oh + // | | -- under-half -- | | + // | | -- under-half -- | | < -- when measured, shoved to next line + // | | --- over-half --- | | + // | | --- over-half --- | | + // Height: measured as 4 lines, more than expected . Will be displayed as 3 lines! + + // Bad (too wide): + // | ------------- display width ------------- | + // | -------- widget-width when measured ------- | < -- uh oh + // | | -- under-half -- | | -- under-half -- | | + // | | --- over-half --- | | --- over-half --- | | < -- when measured, combined on one line + // Height: measured as 2 lines, less than expected. Will be displayed as 3 lines! + + var barelyUnderHalfWidthHtml = '<div style="display: inline-block; height: 1px; width: '+(285 - halfScrollbarWidth)+'px;"></div>'; + var barelyOverHalfWidthHtml = '<div style="display: inline-block; height: 1px; width: '+(305 - halfScrollbarWidth)+'px;"></div>'; + node.innerHTML = new Array(3).join(barelyUnderHalfWidthHtml) + new Array(3).join(barelyOverHalfWidthHtml); + node.style.cssText = "background: yellow;font-size:0;line-height: " + (expectedWidgetHeight/expectedLinesInWidget) + "px;"; + return node; + } + var info0 = cm.getScrollInfo(); + var w0 = cm.addLineWidget(0, w(), { coverGutter: true }); + var w150 = cm.addLineWidget(150, w(), { coverGutter: true }); + var w300 = cm.addLineWidget(300, w(), { coverGutter: true }); + var info1 = cm.getScrollInfo(); + eq(info0.height + (3 * expectedWidgetHeight), info1.height); + eq(info0.top + expectedWidgetHeight, info1.top); + expectedWidgetHeight = 12; + w0.node.style.lineHeight = w150.node.style.lineHeight = w300.node.style.lineHeight = (expectedWidgetHeight/expectedLinesInWidget) + "px"; + w0.changed(); w150.changed(); w300.changed(); + var info2 = cm.getScrollInfo(); + eq(info0.height + (3 * expectedWidgetHeight), info2.height); + eq(info0.top + expectedWidgetHeight, info2.top); +}); + +testCM("getLineNumber", function(cm) { + addDoc(cm, 2, 20); + var h1 = cm.getLineHandle(1); + eq(cm.getLineNumber(h1), 1); + cm.replaceRange("hi\nbye\n", Pos(0, 0)); + eq(cm.getLineNumber(h1), 3); + cm.setValue(""); + eq(cm.getLineNumber(h1), null); +}); + +testCM("jumpTheGap", function(cm) { + if (phantom) return; + var longLine = "abcdef ghiklmnop qrstuvw xyz "; + longLine += longLine; longLine += longLine; longLine += longLine; + cm.replaceRange(longLine, Pos(2, 0), Pos(2)); + cm.setSize("200px", null); + cm.getWrapperElement().style.lineHeight = 2; + cm.refresh(); + cm.setCursor(Pos(0, 1)); + cm.execCommand("goLineDown"); + eqCharPos(cm.getCursor(), Pos(1, 1)); + cm.execCommand("goLineDown"); + eqCharPos(cm.getCursor(), Pos(2, 1)); + cm.execCommand("goLineDown"); + eq(cm.getCursor().line, 2); + is(cm.getCursor().ch > 1); + cm.execCommand("goLineUp"); + eqCharPos(cm.getCursor(), Pos(2, 1)); + cm.execCommand("goLineUp"); + eqCharPos(cm.getCursor(), Pos(1, 1)); + var node = document.createElement("div"); + node.innerHTML = "hi"; node.style.height = "30px"; + cm.addLineWidget(0, node); + cm.addLineWidget(1, node.cloneNode(true), {above: true}); + cm.setCursor(Pos(0, 2)); + cm.execCommand("goLineDown"); + eqCharPos(cm.getCursor(), Pos(1, 2)); + cm.execCommand("goLineUp"); + eqCharPos(cm.getCursor(), Pos(0, 2)); +}, {lineWrapping: true, value: "abc\ndef\nghi\njkl\n"}); + +testCM("addLineClass", function(cm) { + function cls(line, text, bg, wrap, gutter) { + var i = cm.lineInfo(line); + eq(i.textClass, text); + eq(i.bgClass, bg); + eq(i.wrapClass, wrap); + if (typeof i.handle.gutterClass !== 'undefined') { + eq(i.handle.gutterClass, gutter); + } + } + cm.addLineClass(0, "text", "foo"); + cm.addLineClass(0, "text", "bar"); + cm.addLineClass(1, "background", "baz"); + cm.addLineClass(1, "wrap", "foo"); + cm.addLineClass(1, "gutter", "gutter-class"); + cls(0, "foo bar", null, null, null); + cls(1, null, "baz", "foo", "gutter-class"); + var lines = cm.display.lineDiv; + eq(byClassName(lines, "foo").length, 2); + eq(byClassName(lines, "bar").length, 1); + eq(byClassName(lines, "baz").length, 1); + eq(byClassName(lines, "gutter-class").length, 2); // Gutter classes are reflected in 2 nodes + cm.removeLineClass(0, "text", "foo"); + cls(0, "bar", null, null, null); + cm.removeLineClass(0, "text", "foo"); + cls(0, "bar", null, null, null); + cm.removeLineClass(0, "text", "bar"); + cls(0, null, null, null); + + cm.addLineClass(1, "wrap", "quux"); + cls(1, null, "baz", "foo quux", "gutter-class"); + cm.removeLineClass(1, "wrap"); + cls(1, null, "baz", null, "gutter-class"); + cm.removeLineClass(1, "gutter", "gutter-class"); + eq(byClassName(lines, "gutter-class").length, 0); + cls(1, null, "baz", null, null); + + cm.addLineClass(1, "gutter", "gutter-class"); + cls(1, null, "baz", null, "gutter-class"); + cm.removeLineClass(1, "gutter", "gutter-class"); + cls(1, null, "baz", null, null); + +}, {value: "hohoho\n", lineNumbers: true}); + +testCM("atomicMarker", function(cm) { + addDoc(cm, 10, 10); + function atom(ll, cl, lr, cr, li, ri) { + return cm.markText(Pos(ll, cl), Pos(lr, cr), + {atomic: true, inclusiveLeft: li, inclusiveRight: ri}); + } + var m = atom(0, 1, 0, 5); + cm.setCursor(Pos(0, 1)); + cm.execCommand("goCharRight"); + eqCursorPos(cm.getCursor(), Pos(0, 5)); + cm.execCommand("goCharLeft"); + eqCursorPos(cm.getCursor(), Pos(0, 1)); + m.clear(); + m = atom(0, 0, 0, 5, true); + eqCursorPos(cm.getCursor(), Pos(0, 5), "pushed out"); + cm.execCommand("goCharLeft"); + eqCursorPos(cm.getCursor(), Pos(0, 5)); + m.clear(); + m = atom(8, 4, 9, 10, false, true); + cm.setCursor(Pos(9, 8)); + eqCursorPos(cm.getCursor(), Pos(8, 4), "set"); + cm.execCommand("goCharRight"); + eqCursorPos(cm.getCursor(), Pos(8, 4), "char right"); + cm.execCommand("goLineDown"); + eqCursorPos(cm.getCursor(), Pos(8, 4), "line down"); + cm.execCommand("goCharLeft"); + eqCursorPos(cm.getCursor(), Pos(8, 3, "after")); + m.clear(); + m = atom(1, 1, 3, 8); + cm.setCursor(Pos(0, 0)); + cm.setCursor(Pos(2, 0)); + eqCursorPos(cm.getCursor(), Pos(3, 8)); + cm.execCommand("goCharLeft"); + eqCursorPos(cm.getCursor(), Pos(1, 1)); + cm.execCommand("goCharRight"); + eqCursorPos(cm.getCursor(), Pos(3, 8)); + cm.execCommand("goLineUp"); + eqCursorPos(cm.getCursor(), Pos(1, 1)); + cm.execCommand("goLineDown"); + eqCursorPos(cm.getCursor(), Pos(3, 8)); + cm.execCommand("delCharBefore"); + eq(cm.getValue().length, 80, "del chunk"); + m = atom(3, 0, 5, 5); + cm.setCursor(Pos(3, 0)); + cm.execCommand("delWordAfter"); + eq(cm.getValue().length, 53, "del chunk"); +}); + +testCM("selectionBias", function(cm) { + cm.markText(Pos(0, 1), Pos(0, 3), {atomic: true}); + cm.setCursor(Pos(0, 2)); + eqCursorPos(cm.getCursor(), Pos(0, 1)); + cm.setCursor(Pos(0, 2)); + eqCursorPos(cm.getCursor(), Pos(0, 3)); + cm.setCursor(Pos(0, 2)); + eqCursorPos(cm.getCursor(), Pos(0, 1)); + cm.setCursor(Pos(0, 2), null, {bias: -1}); + eqCursorPos(cm.getCursor(), Pos(0, 1)); + cm.setCursor(Pos(0, 4)); + cm.setCursor(Pos(0, 2), null, {bias: 1}); + eqCursorPos(cm.getCursor(), Pos(0, 3)); +}, {value: "12345"}); + +testCM("selectionHomeEnd", function(cm) { + cm.markText(Pos(1, 0), Pos(1, 1), {atomic: true, inclusiveLeft: true}); + cm.markText(Pos(1, 3), Pos(1, 4), {atomic: true, inclusiveRight: true}); + cm.setCursor(Pos(1, 2)); + cm.execCommand("goLineStart"); + eqCursorPos(cm.getCursor(), Pos(1, 1)); + cm.execCommand("goLineEnd"); + eqCursorPos(cm.getCursor(), Pos(1, 3)); +}, {value: "ab\ncdef\ngh"}); + +testCM("readOnlyMarker", function(cm) { + function mark(ll, cl, lr, cr, at) { + return cm.markText(Pos(ll, cl), Pos(lr, cr), + {readOnly: true, atomic: at}); + } + var m = mark(0, 1, 0, 4); + cm.setCursor(Pos(0, 2)); + cm.replaceSelection("hi", "end"); + eqCursorPos(cm.getCursor(), Pos(0, 2)); + eq(cm.getLine(0), "abcde"); + cm.execCommand("selectAll"); + cm.replaceSelection("oops", "around"); + eq(cm.getValue(), "oopsbcd"); + cm.undo(); + eqCursorPos(m.find().from, Pos(0, 1)); + eqCursorPos(m.find().to, Pos(0, 4)); + m.clear(); + cm.setCursor(Pos(0, 2)); + cm.replaceSelection("hi", "around"); + eq(cm.getLine(0), "abhicde"); + eqCursorPos(cm.getCursor(), Pos(0, 4)); + m = mark(0, 2, 2, 2, true); + cm.setSelection(Pos(1, 1), Pos(2, 4)); + cm.replaceSelection("t", "end"); + eqCursorPos(cm.getCursor(), Pos(2, 3)); + eq(cm.getLine(2), "klto"); + cm.execCommand("goCharLeft"); + cm.execCommand("goCharLeft"); + eqCursorPos(cm.getCursor(), Pos(0, 2)); + cm.setSelection(Pos(0, 1), Pos(0, 3)); + cm.replaceSelection("xx", "around"); + eqCursorPos(cm.getCursor(), Pos(0, 3)); + eq(cm.getLine(0), "axxhicde"); +}, {value: "abcde\nfghij\nklmno\n"}); + +testCM("dirtyBit", function(cm) { + eq(cm.isClean(), true); + cm.replaceSelection("boo", null, "test"); + eq(cm.isClean(), false); + cm.undo(); + eq(cm.isClean(), true); + cm.replaceSelection("boo", null, "test"); + cm.replaceSelection("baz", null, "test"); + cm.undo(); + eq(cm.isClean(), false); + cm.markClean(); + eq(cm.isClean(), true); + cm.undo(); + eq(cm.isClean(), false); + cm.redo(); + eq(cm.isClean(), true); +}); + +testCM("changeGeneration", function(cm) { + cm.replaceSelection("x"); + var softGen = cm.changeGeneration(); + cm.replaceSelection("x"); + cm.undo(); + eq(cm.getValue(), ""); + is(!cm.isClean(softGen)); + cm.replaceSelection("x"); + var hardGen = cm.changeGeneration(true); + cm.replaceSelection("x"); + cm.undo(); + eq(cm.getValue(), "x"); + is(cm.isClean(hardGen)); +}); + +testCM("addKeyMap", function(cm) { + function sendKey(code) { + cm.triggerOnKeyDown({type: "keydown", keyCode: code, + preventDefault: function(){}, stopPropagation: function(){}}); + } + + sendKey(39); + eqCursorPos(cm.getCursor(), Pos(0, 1, "before")); + var test = 0; + var map1 = {Right: function() { ++test; }}, map2 = {Right: function() { test += 10; }} + cm.addKeyMap(map1); + sendKey(39); + eqCursorPos(cm.getCursor(), Pos(0, 1, "before")); + eq(test, 1); + cm.addKeyMap(map2, true); + sendKey(39); + eq(test, 2); + cm.removeKeyMap(map1); + sendKey(39); + eq(test, 12); + cm.removeKeyMap(map2); + sendKey(39); + eq(test, 12); + eqCursorPos(cm.getCursor(), Pos(0, 2, "before")); + cm.addKeyMap({Right: function() { test = 55; }, name: "mymap"}); + sendKey(39); + eq(test, 55); + cm.removeKeyMap("mymap"); + sendKey(39); + eqCursorPos(cm.getCursor(), Pos(0, 3, "before")); +}, {value: "abc"}); + +function mouseDown(cm, button, pos, mods) { + var coords = cm.charCoords(pos, "window") + var event = {type: "mousedown", + preventDefault: Math.min, + which: button, + target: cm.display.lineDiv, + clientX: coords.left, clientY: coords.top} + if (mods) for (var prop in mods) event[prop] = mods[prop] + cm.triggerOnMouseDown(event) +} + +testCM("mouseBinding", function(cm) { + var fired = [] + cm.addKeyMap({ + "Shift-LeftClick": function(_cm, pos) { + eqCharPos(pos, Pos(1, 2)) + fired.push("a") + }, + "Shift-LeftDoubleClick": function() { fired.push("b") }, + "Shift-LeftTripleClick": function() { fired.push("c") } + }) + + function send(button, mods) { mouseDown(cm, button, Pos(1, 2), mods) } + send(1, {shiftKey: true}) + send(1, {shiftKey: true}) + send(1, {shiftKey: true}) + send(1, {}) + send(2, {ctrlKey: true}) + send(2, {ctrlKey: true}) + eq(fired.join(" "), "a b c") +}, {value: "foo\nbar\nbaz"}) + +testCM("configureMouse", function(cm) { + cm.setOption("configureMouse", function() { return {unit: "word"} }) + mouseDown(cm, 1, Pos(0, 5)) + eqCharPos(cm.getCursor("from"), Pos(0, 4)) + eqCharPos(cm.getCursor("to"), Pos(0, 7)) + cm.setOption("configureMouse", function() { return {extend: true} }) + mouseDown(cm, 1, Pos(0, 0)) + eqCharPos(cm.getCursor("from"), Pos(0, 0)) + eqCharPos(cm.getCursor("to"), Pos(0, 4)) +}, {value: "foo bar baz"}) + +testCM("findPosH", function(cm) { + forEach([{from: Pos(0, 0), to: Pos(0, 1, "before"), by: 1}, + {from: Pos(0, 0), to: Pos(0, 0), by: -1, hitSide: true}, + {from: Pos(0, 0), to: Pos(0, 4, "before"), by: 1, unit: "word"}, + {from: Pos(0, 0), to: Pos(0, 8, "before"), by: 2, unit: "word"}, + {from: Pos(0, 0), to: Pos(2, 0, "after"), by: 20, unit: "word", hitSide: true}, + {from: Pos(0, 7), to: Pos(0, 5, "after"), by: -1, unit: "word"}, + {from: Pos(0, 4), to: Pos(0, 8, "before"), by: 1, unit: "word"}, + {from: Pos(1, 0), to: Pos(1, 18, "before"), by: 3, unit: "word"}, + {from: Pos(1, 22), to: Pos(1, 5, "after"), by: -3, unit: "word"}, + {from: Pos(1, 15), to: Pos(1, 10, "after"), by: -5}, + {from: Pos(1, 15), to: Pos(1, 10, "after"), by: -5, unit: "column"}, + {from: Pos(1, 15), to: Pos(1, 0, "after"), by: -50, unit: "column", hitSide: true}, + {from: Pos(1, 15), to: Pos(1, 24, "before"), by: 50, unit: "column", hitSide: true}, + {from: Pos(1, 15), to: Pos(2, 0, "after"), by: 50, hitSide: true}], function(t) { + var r = cm.findPosH(t.from, t.by, t.unit || "char"); + eqCursorPos(r, t.to); + eq(!!r.hitSide, !!t.hitSide); + }); +}, {value: "line one\nline two.something.other\n"}); + +testCM("beforeChange", function(cm) { + cm.on("beforeChange", function(cm, change) { + var text = []; + for (var i = 0; i < change.text.length; ++i) + text.push(change.text[i].replace(/\s/g, "_")); + change.update(null, null, text); + }); + cm.setValue("hello, i am a\nnew document\n"); + eq(cm.getValue(), "hello,_i_am_a\nnew_document\n"); + CodeMirror.on(cm.getDoc(), "beforeChange", function(doc, change) { + if (change.from.line == 0) change.cancel(); + }); + cm.setValue("oops"); // Canceled + eq(cm.getValue(), "hello,_i_am_a\nnew_document\n"); + cm.replaceRange("hey hey hey", Pos(1, 0), Pos(2, 0)); + eq(cm.getValue(), "hello,_i_am_a\nhey_hey_hey"); +}, {value: "abcdefghijk"}); + +testCM("beforeChangeUndo", function(cm) { + cm.replaceRange("hi", Pos(0, 0), Pos(0)); + cm.replaceRange("bye", Pos(0, 0), Pos(0)); + eq(cm.historySize().undo, 2); + cm.on("beforeChange", function(cm, change) { + is(!change.update); + change.cancel(); + }); + cm.undo(); + eq(cm.historySize().undo, 0); + eq(cm.getValue(), "bye\ntwo"); +}, {value: "one\ntwo"}); + +testCM("beforeSelectionChange", function(cm) { + function notAtEnd(cm, pos) { + var len = cm.getLine(pos.line).length; + if (!len || pos.ch == len) return Pos(pos.line, pos.ch - 1); + return pos; + } + cm.on("beforeSelectionChange", function(cm, obj) { + obj.update([{anchor: notAtEnd(cm, obj.ranges[0].anchor), + head: notAtEnd(cm, obj.ranges[0].head)}]); + }); + + addDoc(cm, 10, 10); + cm.execCommand("goLineEnd"); + eqCursorPos(cm.getCursor(), Pos(0, 9)); + cm.execCommand("selectAll"); + eqCursorPos(cm.getCursor("start"), Pos(0, 0)); + eqCursorPos(cm.getCursor("end"), Pos(9, 9)); +}); + +testCM("change_removedText", function(cm) { + cm.setValue("abc\ndef"); + + var removedText = []; + cm.on("change", function(cm, change) { + removedText.push(change.removed); + }); + + cm.operation(function() { + cm.replaceRange("xyz", Pos(0, 0), Pos(1,1)); + cm.replaceRange("123", Pos(0,0)); + }); + + eq(removedText.length, 2); + eq(removedText[0].join("\n"), "abc\nd"); + eq(removedText[1].join("\n"), ""); + + var removedText = []; + cm.undo(); + eq(removedText.length, 2); + eq(removedText[0].join("\n"), "123"); + eq(removedText[1].join("\n"), "xyz"); + + var removedText = []; + cm.redo(); + eq(removedText.length, 2); + eq(removedText[0].join("\n"), "abc\nd"); + eq(removedText[1].join("\n"), ""); +}); + +testCM("lineStyleFromMode", function(cm) { + CodeMirror.defineMode("test_mode", function() { + return {token: function(stream) { + if (stream.match(/^\[[^\]]*\]/)) return " line-brackets "; + if (stream.match(/^\([^\)]*\)/)) return " line-background-parens "; + if (stream.match(/^<[^>]*>/)) return " span line-line line-background-bg "; + stream.match(/^\s+|^\S+/); + }}; + }); + cm.setOption("mode", "test_mode"); + var bracketElts = byClassName(cm.getWrapperElement(), "brackets"); + eq(bracketElts.length, 1, "brackets count"); + eq(bracketElts[0].nodeName, "PRE"); + is(!/brackets.*brackets/.test(bracketElts[0].className)); + var parenElts = byClassName(cm.getWrapperElement(), "parens"); + eq(parenElts.length, 1, "parens count"); + eq(parenElts[0].nodeName, "DIV"); + is(!/parens.*parens/.test(parenElts[0].className)); + eq(parenElts[0].parentElement.nodeName, "DIV"); + + is(byClassName(cm.getWrapperElement(), "bg").length > 0); + is(byClassName(cm.getWrapperElement(), "line").length > 0); + var spanElts = byClassName(cm.getWrapperElement(), "cm-span"); + eq(spanElts.length, 2); + is(/^\s*cm-span\s*$/.test(spanElts[0].className)); +}, {value: "line1: [br] [br]\nline2: (par) (par)\nline3: <tag> <tag>"}); + +testCM("lineStyleFromBlankLine", function(cm) { + CodeMirror.defineMode("lineStyleFromBlankLine_mode", function() { + return {token: function(stream) { stream.skipToEnd(); return "comment"; }, + blankLine: function() { return "line-blank"; }}; + }); + cm.setOption("mode", "lineStyleFromBlankLine_mode"); + var blankElts = byClassName(cm.getWrapperElement(), "blank"); + eq(blankElts.length, 1); + eq(blankElts[0].nodeName, "PRE"); + cm.replaceRange("x", Pos(1, 0)); + blankElts = byClassName(cm.getWrapperElement(), "blank"); + eq(blankElts.length, 0); +}, {value: "foo\n\nbar"}); + +CodeMirror.registerHelper("xxx", "a", "A"); +CodeMirror.registerHelper("xxx", "b", "B"); +CodeMirror.defineMode("yyy", function() { + return { + token: function(stream) { stream.skipToEnd(); }, + xxx: ["a", "b", "q"] + }; +}); +CodeMirror.registerGlobalHelper("xxx", "c", function(m) { return m.enableC; }, "C"); + +testCM("helpers", function(cm) { + cm.setOption("mode", "yyy"); + eq(cm.getHelpers(Pos(0, 0), "xxx").join("/"), "A/B"); + cm.setOption("mode", {name: "yyy", modeProps: {xxx: "b", enableC: true}}); + eq(cm.getHelpers(Pos(0, 0), "xxx").join("/"), "B/C"); + cm.setOption("mode", "javascript"); + eq(cm.getHelpers(Pos(0, 0), "xxx").join("/"), ""); +}); + +testCM("selectionHistory", function(cm) { + for (var i = 0; i < 3; i++) { + cm.setExtending(true); + cm.execCommand("goCharRight"); + cm.setExtending(false); + cm.execCommand("goCharRight"); + cm.execCommand("goCharRight"); + } + cm.execCommand("undoSelection"); + eq(cm.getSelection(), "c"); + cm.execCommand("undoSelection"); + eq(cm.getSelection(), ""); + eqCursorPos(cm.getCursor(), Pos(0, 4, "before")); + cm.execCommand("undoSelection"); + eq(cm.getSelection(), "b"); + cm.execCommand("redoSelection"); + eq(cm.getSelection(), ""); + eqCursorPos(cm.getCursor(), Pos(0, 4, "before")); + cm.execCommand("redoSelection"); + eq(cm.getSelection(), "c"); + cm.execCommand("redoSelection"); + eq(cm.getSelection(), ""); + eqCursorPos(cm.getCursor(), Pos(0, 6, "before")); +}, {value: "a b c d"}); + +testCM("selectionChangeReducesRedo", function(cm) { + cm.replaceSelection("X"); + cm.execCommand("goCharRight"); + cm.undoSelection(); + cm.execCommand("selectAll"); + cm.undoSelection(); + eq(cm.getValue(), "Xabc"); + eqCursorPos(cm.getCursor(), Pos(0, 1)); + cm.undoSelection(); + eq(cm.getValue(), "abc"); +}, {value: "abc"}); + +testCM("selectionHistoryNonOverlapping", function(cm) { + cm.setSelection(Pos(0, 0), Pos(0, 1)); + cm.setSelection(Pos(0, 2), Pos(0, 3)); + cm.execCommand("undoSelection"); + eqCursorPos(cm.getCursor("anchor"), Pos(0, 0)); + eqCursorPos(cm.getCursor("head"), Pos(0, 1)); +}, {value: "1234"}); + +testCM("cursorMotionSplitsHistory", function(cm) { + cm.replaceSelection("a"); + cm.execCommand("goCharRight"); + cm.replaceSelection("b"); + cm.replaceSelection("c"); + cm.undo(); + eq(cm.getValue(), "a1234"); + eqCursorPos(cm.getCursor(), Pos(0, 2, "before")); + cm.undo(); + eq(cm.getValue(), "1234"); + eqCursorPos(cm.getCursor(), Pos(0, 0)); +}, {value: "1234"}); + +testCM("selChangeInOperationDoesNotSplit", function(cm) { + for (var i = 0; i < 4; i++) { + cm.operation(function() { + cm.replaceSelection("x"); + cm.setCursor(Pos(0, cm.getCursor().ch - 1)); + }); + } + eqCursorPos(cm.getCursor(), Pos(0, 0)); + eq(cm.getValue(), "xxxxa"); + cm.undo(); + eq(cm.getValue(), "a"); +}, {value: "a"}); + +testCM("alwaysMergeSelEventWithChangeOrigin", function(cm) { + cm.replaceSelection("U", null, "foo"); + cm.setSelection(Pos(0, 0), Pos(0, 1), {origin: "foo"}); + cm.undoSelection(); + eq(cm.getValue(), "a"); + cm.replaceSelection("V", null, "foo"); + cm.setSelection(Pos(0, 0), Pos(0, 1), {origin: "bar"}); + cm.undoSelection(); + eq(cm.getValue(), "Va"); +}, {value: "a"}); + +testCM("getTokenAt", function(cm) { + var tokPlus = cm.getTokenAt(Pos(0, 2)); + eq(tokPlus.type, "operator"); + eq(tokPlus.string, "+"); + var toks = cm.getLineTokens(0); + eq(toks.length, 3); + forEach([["number", "1"], ["operator", "+"], ["number", "2"]], function(expect, i) { + eq(toks[i].type, expect[0]); + eq(toks[i].string, expect[1]); + }); +}, {value: "1+2", mode: "javascript"}); + +testCM("getTokenTypeAt", function(cm) { + eq(cm.getTokenTypeAt(Pos(0, 0)), "number"); + eq(cm.getTokenTypeAt(Pos(0, 6)), "string"); + cm.addOverlay({ + token: function(stream) { + if (stream.match("foo")) return "foo"; + else stream.next(); + } + }); + eq(byClassName(cm.getWrapperElement(), "cm-foo").length, 1); + eq(cm.getTokenTypeAt(Pos(0, 6)), "string"); +}, {value: "1 + 'foo'", mode: "javascript"}); + +testCM("addOverlay", function(cm) { + cm.addOverlay({ + token: function(stream) { + var base = stream.baseToken() + if (!/comment/.test(base.type) && stream.match(/\d+/)) return "x" + stream.next() + } + }) + var x = byClassName(cm.getWrapperElement(), "cm-x") + is(x.length, 1) + is(x[0].textContent, "233") + cm.replaceRange("", Pos(0, 4), Pos(0, 6)) + is(byClassName(cm.getWrapperElement(), "cm-x").length, 2) +}, {value: "foo /* 100 */\nbar + 233;\nbaz", mode: "javascript"}) + +testCM("resizeLineWidget", function(cm) { + addDoc(cm, 200, 3); + var widget = document.createElement("pre"); + widget.innerHTML = "imwidget"; + widget.style.background = "yellow"; + cm.addLineWidget(1, widget, {noHScroll: true}); + cm.setSize(40); + is(widget.parentNode.offsetWidth < 42); +}); + +testCM("combinedOperations", function(cm) { + var place = document.getElementById("testground"); + var other = CodeMirror(place, {value: "123"}); + try { + cm.operation(function() { + cm.addLineClass(0, "wrap", "foo"); + other.addLineClass(0, "wrap", "foo"); + }); + eq(byClassName(cm.getWrapperElement(), "foo").length, 1); + eq(byClassName(other.getWrapperElement(), "foo").length, 1); + cm.operation(function() { + cm.removeLineClass(0, "wrap", "foo"); + other.removeLineClass(0, "wrap", "foo"); + }); + eq(byClassName(cm.getWrapperElement(), "foo").length, 0); + eq(byClassName(other.getWrapperElement(), "foo").length, 0); + } finally { + place.removeChild(other.getWrapperElement()); + } +}, {value: "abc"}); + +testCM("eventOrder", function(cm) { + var seen = []; + cm.on("change", function() { + if (!seen.length) cm.replaceSelection("."); + seen.push("change"); + }); + cm.on("cursorActivity", function() { + cm.replaceSelection("!"); + seen.push("activity"); + }); + cm.replaceSelection("/"); + eq(seen.join(","), "change,change,activity,change"); +}); + +testCM("splitSpaces_nonspecial", function(cm) { + eq(byClassName(cm.getWrapperElement(), "cm-invalidchar").length, 0); +}, { + specialChars: /[\u00a0]/, + value: "spaces -> <- between" +}); + +test("core_rmClass", function() { + var node = document.createElement("div"); + node.className = "foo-bar baz-quux yadda"; + CodeMirror.rmClass(node, "quux"); + eq(node.className, "foo-bar baz-quux yadda"); + CodeMirror.rmClass(node, "baz-quux"); + eq(node.className, "foo-bar yadda"); + CodeMirror.rmClass(node, "yadda"); + eq(node.className, "foo-bar"); + CodeMirror.rmClass(node, "foo-bar"); + eq(node.className, ""); + node.className = " foo "; + CodeMirror.rmClass(node, "foo"); + eq(node.className, ""); +}); + +test("core_addClass", function() { + var node = document.createElement("div"); + CodeMirror.addClass(node, "a"); + eq(node.className, "a"); + CodeMirror.addClass(node, "a"); + eq(node.className, "a"); + CodeMirror.addClass(node, "b"); + eq(node.className, "a b"); + CodeMirror.addClass(node, "a"); + CodeMirror.addClass(node, "b"); + eq(node.className, "a b"); +}); + +testCM("lineSeparator", function(cm) { + eq(cm.lineCount(), 3); + eq(cm.getLine(1), "bar\r"); + eq(cm.getLine(2), "baz\rquux"); + cm.setOption("lineSeparator", "\r"); + eq(cm.lineCount(), 5); + eq(cm.getLine(4), "quux"); + eq(cm.getValue(), "foo\rbar\r\rbaz\rquux"); + eq(cm.getValue("\n"), "foo\nbar\n\nbaz\nquux"); + cm.setOption("lineSeparator", null); + cm.setValue("foo\nbar\r\nbaz\rquux"); + eq(cm.lineCount(), 4); +}, {value: "foo\nbar\r\nbaz\rquux", + lineSeparator: "\n"}); + +var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/ +var getChar = function (noExtending) { var res; do {res = String.fromCharCode(Math.floor(Math.random()*0x8ac)); } while ([0x90].indexOf(res.charCodeAt(0)) != -1 || (noExtending && extendingChars.test(res))); return res } +var getString = function (n) { var res = getChar(true); while (--n > 0) res += getChar(); return res } + +function makeItWrapAfter(cm, pos) { + var firstLineTop = cm.cursorCoords(Pos(0, 0)).top; + for(var w = 0, posTop; posTop != firstLineTop; ++w) { + cm.setSize(w); + posTop = cm.charCoords(pos).top; + } +} + +function countIf(arr, f) { + var result = 0 + for (var i = 0; i < arr.length; i++) if (f[arr[i]]) result++ + return result +} + +function testMoveBidi(str) { + testCM("move_bidi_" + str, function(cm) { + if (cm.getOption("inputStyle") != "textarea" || !cm.getOption("rtlMoveVisually")) return; + cm.getScrollerElement().style.fontFamily = "monospace"; + makeItWrapAfter(cm, Pos(0, 5)); + + var steps = str.length - countIf(str.split(""), function(ch) { return extendingChars.test(ch) }); + var lineBreaks = {} + lineBreaks[6 - countIf(str.substr(0, 5).split(""), function(ch) { return extendingChars.test(ch) })] = 'w'; + if (str.indexOf("\n") != -1) { + lineBreaks[steps - 2] = 'n'; + } + + // Make sure we are at the visual beginning of the first line + cm.execCommand("goLineStart"); + + var prevCoords = cm.cursorCoords(), coords; + for(var i = 0; i < steps; ++i) { + cm.execCommand("goCharRight"); + coords = cm.cursorCoords(); + if ((i >= 10 && i <= 12) && !lineBreaks[i] && coords.left < prevCoords.left && coords.top > prevCoords.top) { + // The first line wraps twice + lineBreaks[i] = 'w'; + } + if (!lineBreaks[i]) { + is(coords.left > prevCoords.left, "In step " + i + ", cursor didn't move right"); + eq(coords.top, prevCoords.top, "In step " + i + ", cursor moved out of line"); + } else { + is(coords.left < prevCoords.left, i); + is(coords.top > prevCoords.top, i); + } + prevCoords = coords; + } + + cm.execCommand("goCharRight"); + coords = cm.cursorCoords(); + eq(coords.left, prevCoords.left, "Moving " + steps + " steps right didn't reach the end"); + eq(coords.top, prevCoords.top, "Moving " + steps + " steps right didn't reach the end"); + + for(i = steps - 1; i >= 0; --i) { + cm.execCommand("goCharLeft"); + coords = cm.cursorCoords(); + if (!(lineBreaks[i] == 'n' || lineBreaks[i + 1] == 'w')) { + is(coords.left < prevCoords.left, "In step " + i + ", cursor didn't move left"); + eq(coords.top, prevCoords.top, "In step " + i + ", cursor is not at the same line anymore"); + } else { + is(coords.left > prevCoords.left, i); + is(coords.top < prevCoords.top, i); + } + prevCoords = coords; + } + + cm.execCommand("goCharLeft"); + coords = cm.cursorCoords(); + eq(coords.left, prevCoords.left, "Moving " + steps + " steps left didn't reach the beginning"); + eq(coords.top, prevCoords.top, "Moving " + steps + " steps left didn't reach the beginning"); + }, {value: str, lineWrapping: true}) +}; + +function testMoveEndBidi(str) { + testCM("move_end_bidi_" + str, function(cm) { + cm.getScrollerElement().style.fontFamily = "monospace"; + makeItWrapAfter(cm, Pos(0, 5)); + + cm.execCommand("goLineStart"); + var pos = cm.doc.getCursor(); + cm.execCommand("goCharLeft"); + eqCursorPos(pos, cm.doc.getCursor()); + + cm.execCommand("goLineEnd"); + pos = cm.doc.getCursor(); + cm.execCommand("goColumnRight"); + eqCursorPos(pos, cm.doc.getCursor()); + }, {value: str, lineWrapping: true}) +}; + +var bidiTests = []; + +// We don't correctly implement L1 UBA +// See https://bugzilla.mozilla.org/show_bug.cgi?id=1331501 +// and https://bugs.chromium.org/p/chromium/issues/detail?id=673405 +/* +bidiTests.push("Say ا ب جabj\nS"); +bidiTests.push("Sayyy ا ا ب ج"); +*/ + +if (!phantom) { + bidiTests.push("Όȝǝڪȉۥ״ۺ׆ɀҩۏ\nҳ"); + bidiTests.push("ŌӰтقȤ؁ƥ؅٣ĎȺ١\nϚ"); + bidiTests.push("ٻоҤѕѽΩ־؉ïίքdz\nٵ"); + bidiTests.push("؅؁ĆՕƿɁǞϮؠȩóć\nď"); + bidiTests.push("RŨďңŪzϢŎƏԖڇڦ\nӈ"); + bidiTests.push("ό׊۷٢ԜһОצЉيčǟ\nѩ"); + bidiTests.push("ۑÚҳҕڬġڹհяųKV\nr"); + bidiTests.push("źڻғúہ4ם1Ƞc1a\nԁ"); + bidiTests.push("ҒȨҟփƞ٦ԓȦڰғâƥ\nڤ"); + bidiTests.push("ϖسՉȏŧΔԛdžĎӟیڡ\nέ"); + bidiTests.push("۹ؼL۵ĺȧКԙػא7״\nم"); + bidiTests.push("ن (ي)\u2009أقواس"); // thin space to throw off Firefox 51's broken white-space compressing behavior +} + +bidiTests.push("քմѧǮßپüŢҍҞўڳ\nӧ"); + +//bidiTests.push("Count ١ ٢ ٣ ٤"); +//bidiTests.push("ӣאƦϰ؊ȓېÛوը٬ز\nϪ"); +//bidiTests.push("ҾճٳџIՖӻ٥׭֐؜ڏ\nێ"); +//bidiTests.push("ҬÓФ؜ڂį٦Ͽɓڐͳٵ\nՈ"); +//bidiTests.push("aѴNijȻهˇ҃ڱӧǻֵ\na"); +//bidiTests.push(" a٧ا٢ ب جa\nS"); + +for (var i = 0; i < bidiTests.length; ++i) { + testMoveBidi(bidiTests[i]); + testMoveEndBidi(bidiTests[i]); +} + +/* +for (var i = 0; i < 5; ++i) { + testMoveBidi(getString(12) + "\n" + getString(1)); +} +*/ + +function testCoordsWrappedBidi(str) { + testCM("coords_wrapped_bidi_" + str, function(cm) { + cm.getScrollerElement().style.fontFamily = "monospace"; + makeItWrapAfter(cm, Pos(0, 5)); + + // Make sure we are at the visual beginning of the first line + var pos = Pos(0, 0), lastPos; + cm.doc.setCursor(pos); + do { + lastPos = pos; + cm.execCommand("goCharLeft"); + pos = cm.doc.getCursor(); + } while (pos != lastPos) + + var top = cm.charCoords(Pos(0, 0)).top, lastTop; + for (var i = 1; i < str.length; ++i) { + lastTop = top; + top = cm.charCoords(Pos(0, i)).top; + is(top >= lastTop); + } + }, {value: str, lineWrapping: true}) +}; + +testCoordsWrappedBidi("Count ١ ٢ ٣ ٤"); +/* +for (var i = 0; i < 5; ++i) { + testCoordsWrappedBidi(getString(50)); +} +*/ + +testCM("rtl_wrapped_selection", function(cm) { + cm.setSelection(Pos(0, 10), Pos(0, 190)) + is(byClassName(cm.getWrapperElement(), "CodeMirror-selected").length >= 3) +}, {value: new Array(10).join(" فتي تم تضمينها فتي تم"), lineWrapping: true}) + +testCM("bidi_wrapped_selection", function(cm) { + if (phantom) return + cm.setSize(cm.charCoords(Pos(0, 10), "editor").left) + cm.setSelection(Pos(0, 37), Pos(0, 80)) + var blocks = byClassName(cm.getWrapperElement(), "CodeMirror-selected") + is(blocks.length >= 2) + is(blocks.length <= 3) + var boxTop = blocks[0].getBoundingClientRect(), boxBot = blocks[blocks.length - 1].getBoundingClientRect() + is(boxTop.left > cm.charCoords(Pos(0, 1)).right) + is(boxBot.right < cm.charCoords(Pos(0, cm.getLine(0).length - 2)).left) +}, {value: "<p>مفتي11 تم تضمينهفتي تم تضمينها فتي تفتي تم تضمينها فتي تفتي تم تضمينها فتي تفتي تم تضمينها فتي تا فت10ي ت</p>", lineWrapping: true}) + +testCM("delete_wrapped", function(cm) { + makeItWrapAfter(cm, Pos(0, 2)); + cm.doc.setCursor(Pos(0, 3, "after")); + cm.deleteH(-1, "char"); + eq(cm.getLine(0), "1245"); +}, {value: "12345", lineWrapping: true}) + +testCM("issue_4878", function(cm) { + if (phantom) return + cm.setCursor(Pos(1, 12, "after")); + cm.moveH(-1, "char"); + eqCursorPos(cm.getCursor(), Pos(0, 113, "before")); +}, {value: " في تطبيق السمات مرة واحدة https://github.com/codemirror/CodeMirror/issues/4878#issuecomment-330550964على سبيل المثال <code>\"foo bar\"</code>\n" + +" سيتم تعيين", direction: "rtl", lineWrapping: true}); + +CodeMirror.defineMode("lookahead_mode", function() { + // Colors text as atom if the line two lines down has an x in it + return { + token: function(stream) { + stream.skipToEnd() + return /x/.test(stream.lookAhead(2)) ? "atom" : null + } + } +}) + +testCM("mode_lookahead", function(cm) { + eq(cm.getTokenAt(Pos(0, 1)).type, "atom") + eq(cm.getTokenAt(Pos(1, 1)).type, "atom") + eq(cm.getTokenAt(Pos(2, 1)).type, null) + cm.replaceRange("\n", Pos(2, 0)) + eq(cm.getTokenAt(Pos(0, 1)).type, null) + eq(cm.getTokenAt(Pos(1, 1)).type, "atom") +}, {value: "foo\na\nx\nx\n", mode: "lookahead_mode"}) diff --git a/modules/editor/codemirror/test/vim_test.js b/modules/editor/codemirror/test/vim_test.js @@ -0,0 +1,4238 @@ +var Pos = CodeMirror.Pos; +CodeMirror.Vim.suppressErrorLogging = true; + +var code = '' + +' wOrd1 (#%\n' + +' word3] \n' + +'aopop pop 0 1 2 3 4\n' + +' (a) [b] {c} \n' + +'int getchar(void) {\n' + +' static char buf[BUFSIZ];\n' + +' static char *bufp = buf;\n' + +' if (n == 0) { /* buffer is empty */\n' + +' n = read(0, buf, sizeof buf);\n' + +' bufp = buf;\n' + +' }\n' + +'\n' + +' return (--n >= 0) ? (unsigned char) *bufp++ : EOF;\n' + +' \n' + +'}\n'; + +var lines = (function() { + lineText = code.split('\n'); + var ret = []; + for (var i = 0; i < lineText.length; i++) { + ret[i] = { + line: i, + length: lineText[i].length, + lineText: lineText[i], + textStart: /^\s*/.exec(lineText[i])[0].length + }; + } + return ret; +})(); +var endOfDocument = makeCursor(lines.length - 1, + lines[lines.length - 1].length); +var wordLine = lines[0]; +var bigWordLine = lines[1]; +var charLine = lines[2]; +var bracesLine = lines[3]; +var seekBraceLine = lines[4]; + +var word1 = { + start: new Pos(wordLine.line, 1), + end: new Pos(wordLine.line, 5) +}; +var word2 = { + start: new Pos(wordLine.line, word1.end.ch + 2), + end: new Pos(wordLine.line, word1.end.ch + 4) +}; +var word3 = { + start: new Pos(bigWordLine.line, 1), + end: new Pos(bigWordLine.line, 5) +}; +var bigWord1 = word1; +var bigWord2 = word2; +var bigWord3 = { + start: new Pos(bigWordLine.line, 1), + end: new Pos(bigWordLine.line, 7) +}; +var bigWord4 = { + start: new Pos(bigWordLine.line, bigWord1.end.ch + 3), + end: new Pos(bigWordLine.line, bigWord1.end.ch + 7) +}; + +var oChars = [ new Pos(charLine.line, 1), + new Pos(charLine.line, 3), + new Pos(charLine.line, 7) ]; +var pChars = [ new Pos(charLine.line, 2), + new Pos(charLine.line, 4), + new Pos(charLine.line, 6), + new Pos(charLine.line, 8) ]; +var numChars = [ new Pos(charLine.line, 10), + new Pos(charLine.line, 12), + new Pos(charLine.line, 14), + new Pos(charLine.line, 16), + new Pos(charLine.line, 18)]; +var parens1 = { + start: new Pos(bracesLine.line, 1), + end: new Pos(bracesLine.line, 3) +}; +var squares1 = { + start: new Pos(bracesLine.line, 5), + end: new Pos(bracesLine.line, 7) +}; +var curlys1 = { + start: new Pos(bracesLine.line, 9), + end: new Pos(bracesLine.line, 11) +}; +var seekOutside = { + start: new Pos(seekBraceLine.line, 1), + end: new Pos(seekBraceLine.line, 16) +}; +var seekInside = { + start: new Pos(seekBraceLine.line, 14), + end: new Pos(seekBraceLine.line, 11) +}; + +function copyCursor(cur) { + return new Pos(cur.line, cur.ch); +} + +function forEach(arr, func) { + for (var i = 0; i < arr.length; i++) { + func(arr[i], i, arr); + } +} + +function testVim(name, run, opts, expectedFail) { + var vimOpts = { + lineNumbers: true, + vimMode: true, + showCursorWhenSelecting: true, + value: code + }; + for (var prop in opts) { + if (opts.hasOwnProperty(prop)) { + vimOpts[prop] = opts[prop]; + } + } + return test('vim_' + name, function() { + var place = document.getElementById("testground"); + var cm = CodeMirror(place, vimOpts); + var vim = CodeMirror.Vim.maybeInitVimState_(cm); + + function doKeysFn(cm) { + return function(args) { + if (args instanceof Array) { + arguments = args; + } + for (var i = 0; i < arguments.length; i++) { + var result = CodeMirror.Vim.handleKey(cm, arguments[i]); + if (!result && cm.state.vim.insertMode) { + cm.replaceSelections(fillArray(arguments[i], cm.listSelections().length)); + } + } + } + } + function doInsertModeKeysFn(cm) { + return function(args) { + if (args instanceof Array) { arguments = args; } + function executeHandler(handler) { + if (typeof handler == 'string') { + CodeMirror.commands[handler](cm); + } else { + handler(cm); + } + return true; + } + for (var i = 0; i < arguments.length; i++) { + var key = arguments[i]; + // Find key in keymap and handle. + var handled = CodeMirror.lookupKey(key, cm.getOption('keyMap'), executeHandler, cm); + // Record for insert mode. + if (handled == "handled" && cm.state.vim.insertMode && arguments[i] != 'Esc') { + var lastChange = CodeMirror.Vim.getVimGlobalState_().macroModeState.lastInsertModeChanges; + if (lastChange && (key.indexOf('Delete') != -1 || key.indexOf('Backspace') != -1)) { + lastChange.changes.push(new CodeMirror.Vim.InsertModeKey(key)); + } + } + } + } + } + function doExFn(cm) { + return function(command) { + cm.openDialog = helpers.fakeOpenDialog(command); + helpers.doKeys(':'); + } + } + function assertCursorAtFn(cm) { + return function(line, ch) { + var pos; + if (ch == null && typeof line.line == 'number') { + pos = line; + } else { + pos = makeCursor(line, ch); + } + eqCursorPos(cm.getCursor(), pos); + } + } + function fakeOpenDialog(result) { + return function(text, callback) { + return callback(result); + } + } + function fakeOpenNotification(matcher) { + return function(text) { + matcher(text); + } + } + var helpers = { + doKeys: doKeysFn(cm), + // Warning: Only emulates keymap events, not character insertions. Use + // replaceRange to simulate character insertions. + // Keys are in CodeMirror format, NOT vim format. + doInsertModeKeys: doInsertModeKeysFn(cm), + doEx: doExFn(cm), + assertCursorAt: assertCursorAtFn(cm), + fakeOpenDialog: fakeOpenDialog, + fakeOpenNotification: fakeOpenNotification, + getRegisterController: function() { + return CodeMirror.Vim.getRegisterController(); + } + } + CodeMirror.Vim.resetVimGlobalState_(); + var successful = false; + var savedOpenNotification = cm.openNotification; + var savedOpenDialog = cm.openDialog; + try { + run(cm, vim, helpers); + successful = true; + } finally { + cm.openNotification = savedOpenNotification; + cm.openDialog = savedOpenDialog; + if (!successful || verbose) { + place.style.visibility = "visible"; + } else { + place.removeChild(cm.getWrapperElement()); + } + } + }, expectedFail); +}; +testVim('qq@q', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('q', 'q', 'l', 'l', 'q'); + helpers.assertCursorAt(0,2); + helpers.doKeys('@', 'q'); + helpers.assertCursorAt(0,4); +}, { value: ' '}); +testVim('@@', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('q', 'q', 'l', 'l', 'q'); + helpers.assertCursorAt(0,2); + helpers.doKeys('@', 'q'); + helpers.assertCursorAt(0,4); + helpers.doKeys('@', '@'); + helpers.assertCursorAt(0,6); +}, { value: ' '}); +var jumplistScene = ''+ + 'word\n'+ + '(word)\n'+ + '{word\n'+ + 'word.\n'+ + '\n'+ + 'word search\n'+ + '}word\n'+ + 'word\n'+ + 'word\n'; +function testJumplist(name, keys, endPos, startPos, dialog) { + endPos = makeCursor(endPos[0], endPos[1]); + startPos = makeCursor(startPos[0], startPos[1]); + testVim(name, function(cm, vim, helpers) { + CodeMirror.Vim.resetVimGlobalState_(); + if(dialog)cm.openDialog = helpers.fakeOpenDialog('word'); + cm.setCursor(startPos); + helpers.doKeys.apply(null, keys); + helpers.assertCursorAt(endPos); + }, {value: jumplistScene}); +}; +testJumplist('jumplist_H', ['H', '<C-o>'], [5,2], [5,2]); +testJumplist('jumplist_M', ['M', '<C-o>'], [2,2], [2,2]); +testJumplist('jumplist_L', ['L', '<C-o>'], [2,2], [2,2]); +testJumplist('jumplist_[[', ['[', '[', '<C-o>'], [5,2], [5,2]); +testJumplist('jumplist_]]', [']', ']', '<C-o>'], [2,2], [2,2]); +testJumplist('jumplist_G', ['G', '<C-o>'], [5,2], [5,2]); +testJumplist('jumplist_gg', ['g', 'g', '<C-o>'], [5,2], [5,2]); +testJumplist('jumplist_%', ['%', '<C-o>'], [1,5], [1,5]); +testJumplist('jumplist_{', ['{', '<C-o>'], [1,5], [1,5]); +testJumplist('jumplist_}', ['}', '<C-o>'], [1,5], [1,5]); +testJumplist('jumplist_\'', ['m', 'a', 'h', '\'', 'a', 'h', '<C-i>'], [1,0], [1,5]); +testJumplist('jumplist_`', ['m', 'a', 'h', '`', 'a', 'h', '<C-i>'], [1,5], [1,5]); +testJumplist('jumplist_*_cachedCursor', ['*', '<C-o>'], [1,3], [1,3]); +testJumplist('jumplist_#_cachedCursor', ['#', '<C-o>'], [1,3], [1,3]); +testJumplist('jumplist_n', ['#', 'n', '<C-o>'], [1,1], [2,3]); +testJumplist('jumplist_N', ['#', 'N', '<C-o>'], [1,1], [2,3]); +testJumplist('jumplist_repeat_<c-o>', ['*', '*', '*', '3', '<C-o>'], [2,3], [2,3]); +testJumplist('jumplist_repeat_<c-i>', ['*', '*', '*', '3', '<C-o>', '2', '<C-i>'], [5,0], [2,3]); +testJumplist('jumplist_repeated_motion', ['3', '*', '<C-o>'], [2,3], [2,3]); +testJumplist('jumplist_/', ['/', '<C-o>'], [2,3], [2,3], 'dialog'); +testJumplist('jumplist_?', ['?', '<C-o>'], [2,3], [2,3], 'dialog'); +testJumplist('jumplist_skip_deleted_mark<c-o>', + ['*', 'n', 'n', 'k', 'd', 'k', '<C-o>', '<C-o>', '<C-o>'], + [0,2], [0,2]); +testJumplist('jumplist_skip_deleted_mark<c-i>', + ['*', 'n', 'n', 'k', 'd', 'k', '<C-o>', '<C-i>', '<C-i>'], + [1,0], [0,2]); + +/** + * @param name Name of the test + * @param keys An array of keys or a string with a single key to simulate. + * @param endPos The expected end position of the cursor. + * @param startPos The position the cursor should start at, defaults to 0, 0. + */ +function testMotion(name, keys, endPos, startPos) { + testVim(name, function(cm, vim, helpers) { + if (!startPos) { + startPos = new Pos(0, 0); + } + cm.setCursor(startPos); + helpers.doKeys(keys); + helpers.assertCursorAt(endPos); + }); +}; + +function makeCursor(line, ch) { + return new Pos(line, ch); +}; + +function offsetCursor(cur, offsetLine, offsetCh) { + return new Pos(cur.line + offsetLine, cur.ch + offsetCh); +}; + +// Motion tests +testMotion('|', '|', makeCursor(0, 0), makeCursor(0,4)); +testMotion('|_repeat', ['3', '|'], makeCursor(0, 2), makeCursor(0,4)); +testMotion('h', 'h', makeCursor(0, 0), word1.start); +testMotion('h_repeat', ['3', 'h'], offsetCursor(word1.end, 0, -3), word1.end); +testMotion('l', 'l', makeCursor(0, 1)); +testMotion('l_repeat', ['2', 'l'], makeCursor(0, 2)); +testMotion('j', 'j', offsetCursor(word1.end, 1, 0), word1.end); +testMotion('j_repeat', ['2', 'j'], offsetCursor(word1.end, 2, 0), word1.end); +testMotion('j_repeat_clip', ['1000', 'j'], endOfDocument); +testMotion('k', 'k', offsetCursor(word3.end, -1, 0), word3.end); +testMotion('k_repeat', ['2', 'k'], makeCursor(0, 4), makeCursor(2, 4)); +testMotion('k_repeat_clip', ['1000', 'k'], makeCursor(0, 4), makeCursor(2, 4)); +testMotion('w', 'w', word1.start); +testMotion('w_multiple_newlines_no_space', 'w', makeCursor(12, 2), makeCursor(11, 2)); +testMotion('w_multiple_newlines_with_space', 'w', makeCursor(14, 0), makeCursor(12, 51)); +testMotion('w_repeat', ['2', 'w'], word2.start); +testMotion('w_wrap', ['w'], word3.start, word2.start); +testMotion('w_endOfDocument', 'w', endOfDocument, endOfDocument); +testMotion('w_start_to_end', ['1000', 'w'], endOfDocument, makeCursor(0, 0)); +testMotion('W', 'W', bigWord1.start); +testMotion('W_repeat', ['2', 'W'], bigWord3.start, bigWord1.start); +testMotion('e', 'e', word1.end); +testMotion('e_repeat', ['2', 'e'], word2.end); +testMotion('e_wrap', 'e', word3.end, word2.end); +testMotion('e_endOfDocument', 'e', endOfDocument, endOfDocument); +testMotion('e_start_to_end', ['1000', 'e'], endOfDocument, makeCursor(0, 0)); +testMotion('b', 'b', word3.start, word3.end); +testMotion('b_repeat', ['2', 'b'], word2.start, word3.end); +testMotion('b_wrap', 'b', word2.start, word3.start); +testMotion('b_startOfDocument', 'b', makeCursor(0, 0), makeCursor(0, 0)); +testMotion('b_end_to_start', ['1000', 'b'], makeCursor(0, 0), endOfDocument); +testMotion('ge', ['g', 'e'], word2.end, word3.end); +testMotion('ge_repeat', ['2', 'g', 'e'], word1.end, word3.start); +testMotion('ge_wrap', ['g', 'e'], word2.end, word3.start); +testMotion('ge_startOfDocument', ['g', 'e'], makeCursor(0, 0), + makeCursor(0, 0)); +testMotion('ge_end_to_start', ['1000', 'g', 'e'], makeCursor(0, 0), endOfDocument); +testMotion('gg', ['g', 'g'], makeCursor(lines[0].line, lines[0].textStart), + makeCursor(3, 1)); +testMotion('gg_repeat', ['3', 'g', 'g'], + makeCursor(lines[2].line, lines[2].textStart)); +testMotion('G', 'G', + makeCursor(lines[lines.length - 1].line, lines[lines.length - 1].textStart), + makeCursor(3, 1)); +testMotion('G_repeat', ['3', 'G'], makeCursor(lines[2].line, + lines[2].textStart)); +// TODO: Make the test code long enough to test Ctrl-F and Ctrl-B. +testMotion('0', '0', makeCursor(0, 0), makeCursor(0, 8)); +testMotion('^', '^', makeCursor(0, lines[0].textStart), makeCursor(0, 8)); +testMotion('+', '+', makeCursor(1, lines[1].textStart), makeCursor(0, 8)); +testMotion('-', '-', makeCursor(0, lines[0].textStart), makeCursor(1, 4)); +testMotion('_', ['6','_'], makeCursor(5, lines[5].textStart), makeCursor(0, 8)); +testMotion('$', '$', makeCursor(0, lines[0].length - 1), makeCursor(0, 1)); +testMotion('$_repeat', ['2', '$'], makeCursor(1, lines[1].length - 1), + makeCursor(0, 3)); +testMotion('f', ['f', 'p'], pChars[0], makeCursor(charLine.line, 0)); +testMotion('f_repeat', ['2', 'f', 'p'], pChars[2], pChars[0]); +testMotion('f_num', ['f', '2'], numChars[2], makeCursor(charLine.line, 0)); +testMotion('t', ['t','p'], offsetCursor(pChars[0], 0, -1), + makeCursor(charLine.line, 0)); +testMotion('t_repeat', ['2', 't', 'p'], offsetCursor(pChars[2], 0, -1), + pChars[0]); +testMotion('F', ['F', 'p'], pChars[0], pChars[1]); +testMotion('F_repeat', ['2', 'F', 'p'], pChars[0], pChars[2]); +testMotion('T', ['T', 'p'], offsetCursor(pChars[0], 0, 1), pChars[1]); +testMotion('T_repeat', ['2', 'T', 'p'], offsetCursor(pChars[0], 0, 1), pChars[2]); +testMotion('%_parens', ['%'], parens1.end, parens1.start); +testMotion('%_squares', ['%'], squares1.end, squares1.start); +testMotion('%_braces', ['%'], curlys1.end, curlys1.start); +testMotion('%_seek_outside', ['%'], seekOutside.end, seekOutside.start); +testMotion('%_seek_inside', ['%'], seekInside.end, seekInside.start); +testVim('%_seek_skip', function(cm, vim, helpers) { + cm.setCursor(0,0); + helpers.doKeys(['%']); + helpers.assertCursorAt(0,9); +}, {value:'01234"("()'}); +testVim('%_skip_string', function(cm, vim, helpers) { + cm.setCursor(0,0); + helpers.doKeys(['%']); + helpers.assertCursorAt(0,4); + cm.setCursor(0,2); + helpers.doKeys(['%']); + helpers.assertCursorAt(0,0); +}, {value:'(")")'}); +testVim('%_skip_comment', function(cm, vim, helpers) { + cm.setCursor(0,0); + helpers.doKeys(['%']); + helpers.assertCursorAt(0,6); + cm.setCursor(0,3); + helpers.doKeys(['%']); + helpers.assertCursorAt(0,0); +}, {value:'(/*)*/)'}); +// Make sure that moving down after going to the end of a line always leaves you +// at the end of a line, but preserves the offset in other cases +testVim('Changing lines after Eol operation', function(cm, vim, helpers) { + cm.setCursor(0,0); + helpers.doKeys(['$']); + helpers.doKeys(['j']); + // After moving to Eol and then down, we should be at Eol of line 2 + helpers.assertCursorAt(new Pos(1, lines[1].length - 1)); + helpers.doKeys(['j']); + // After moving down, we should be at Eol of line 3 + helpers.assertCursorAt(new Pos(2, lines[2].length - 1)); + helpers.doKeys(['h']); + helpers.doKeys(['j']); + // After moving back one space and then down, since line 4 is shorter than line 2, we should + // be at Eol of line 2 - 1 + helpers.assertCursorAt(new Pos(3, lines[3].length - 1)); + helpers.doKeys(['j']); + helpers.doKeys(['j']); + // After moving down again, since line 3 has enough characters, we should be back to the + // same place we were at on line 1 + helpers.assertCursorAt(new Pos(5, lines[2].length - 2)); +}); +//making sure gj and gk recover from clipping +testVim('gj_gk_clipping', function(cm,vim,helpers){ + cm.setCursor(0, 1); + helpers.doKeys('g','j','g','j'); + helpers.assertCursorAt(2, 1); + helpers.doKeys('g','k','g','k'); + helpers.assertCursorAt(0, 1); +},{value: 'line 1\n\nline 2'}); +//testing a mix of j/k and gj/gk +testVim('j_k_and_gj_gk', function(cm,vim,helpers){ + cm.setSize(120); + cm.setCursor(0, 0); + //go to the last character on the first line + helpers.doKeys('$'); + //move up/down on the column within the wrapped line + //side-effect: cursor is not locked to eol anymore + helpers.doKeys('g','k'); + var cur=cm.getCursor(); + eq(cur.line,0); + is((cur.ch<176),'gk didn\'t move cursor back (1)'); + helpers.doKeys('g','j'); + helpers.assertCursorAt(0, 176); + //should move to character 177 on line 2 (j/k preserve character index within line) + helpers.doKeys('j'); + //due to different line wrapping, the cursor can be on a different screen-x now + //gj and gk preserve screen-x on movement, much like moveV + helpers.doKeys('3','g','k'); + cur=cm.getCursor(); + eq(cur.line,1); + is((cur.ch<176),'gk didn\'t move cursor back (2)'); + helpers.doKeys('g','j','2','g','j'); + //should return to the same character-index + helpers.doKeys('k'); + helpers.assertCursorAt(0, 176); +},{ lineWrapping:true, value: 'This line is intentially long to test movement of gj and gk over wrapped lines. I will start on the end of this line, then make a step up and back to set the origin for j and k.\nThis line is supposed to be even longer than the previous. I will jump here and make another wiggle with gj and gk, before I jump back to the line above. Both wiggles should not change my cursor\'s target character but both j/k and gj/gk change each other\'s reference position.'}); +testVim('gj_gk', function(cm, vim, helpers) { + if (phantom) return; + cm.setSize(120); + // Test top of document edge case. + cm.setCursor(0, 4); + helpers.doKeys('g', 'j'); + helpers.doKeys('10', 'g', 'k'); + helpers.assertCursorAt(0, 4); + + // Test moving down preserves column position. + helpers.doKeys('g', 'j'); + var pos1 = cm.getCursor(); + var expectedPos2 = new Pos(0, (pos1.ch - 4) * 2 + 4); + helpers.doKeys('g', 'j'); + helpers.assertCursorAt(expectedPos2); + + // Move to the last character + cm.setCursor(0, 0); + // Move left to reset HSPos + helpers.doKeys('h'); + // Test bottom of document edge case. + helpers.doKeys('100', 'g', 'j'); + var endingPos = cm.getCursor(); + is(endingPos != 0, 'gj should not be on wrapped line 0'); + var topLeftCharCoords = cm.charCoords(makeCursor(0, 0)); + var endingCharCoords = cm.charCoords(endingPos); + is(topLeftCharCoords.left == endingCharCoords.left, 'gj should end up on column 0'); +},{ lineNumbers: false, lineWrapping:true, value: 'Thislineisintentionallylongtotestmovementofgjandgkoverwrappedlines.' }); +testVim('}', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('}'); + helpers.assertCursorAt(1, 0); + cm.setCursor(0, 0); + helpers.doKeys('2', '}'); + helpers.assertCursorAt(4, 0); + cm.setCursor(0, 0); + helpers.doKeys('6', '}'); + helpers.assertCursorAt(5, 0); +}, { value: 'a\n\nb\nc\n\nd' }); +testVim('{', function(cm, vim, helpers) { + cm.setCursor(5, 0); + helpers.doKeys('{'); + helpers.assertCursorAt(4, 0); + cm.setCursor(5, 0); + helpers.doKeys('2', '{'); + helpers.assertCursorAt(1, 0); + cm.setCursor(5, 0); + helpers.doKeys('6', '{'); + helpers.assertCursorAt(0, 0); +}, { value: 'a\n\nb\nc\n\nd' }); +testVim('paragraph_motions', function(cm, vim, helpers) { + cm.setCursor(10, 0); + helpers.doKeys('{'); + helpers.assertCursorAt(4, 0); + helpers.doKeys('{'); + helpers.assertCursorAt(0, 0); + helpers.doKeys('2', '}'); + helpers.assertCursorAt(7, 0); + helpers.doKeys('2', '}'); + helpers.assertCursorAt(16, 0); + + cm.setCursor(9, 0); + helpers.doKeys('}'); + helpers.assertCursorAt(14, 0); + + cm.setCursor(6, 0); + helpers.doKeys('}'); + helpers.assertCursorAt(7, 0); + + // ip inside empty space + cm.setCursor(10, 0); + helpers.doKeys('v', 'i', 'p'); + eqCursorPos(Pos(7, 0), cm.getCursor('anchor')); + eqCursorPos(Pos(12, 0), cm.getCursor('head')); + helpers.doKeys('i', 'p'); + eqCursorPos(Pos(7, 0), cm.getCursor('anchor')); + eqCursorPos(Pos(13, 1), cm.getCursor('head')); + helpers.doKeys('2', 'i', 'p'); + eqCursorPos(Pos(7, 0), cm.getCursor('anchor')); + eqCursorPos(Pos(16, 1), cm.getCursor('head')); + + // should switch to visualLine mode + cm.setCursor(14, 0); + helpers.doKeys('<Esc>', 'v', 'i', 'p'); + helpers.assertCursorAt(14, 0); + + cm.setCursor(14, 0); + helpers.doKeys('<Esc>', 'V', 'i', 'p'); + eqCursorPos(Pos(16, 1), cm.getCursor('head')); + + // ap inside empty space + cm.setCursor(10, 0); + helpers.doKeys('<Esc>', 'v', 'a', 'p'); + eqCursorPos(Pos(7, 0), cm.getCursor('anchor')); + eqCursorPos(Pos(13, 1), cm.getCursor('head')); + helpers.doKeys('a', 'p'); + eqCursorPos(Pos(7, 0), cm.getCursor('anchor')); + eqCursorPos(Pos(16, 1), cm.getCursor('head')); + + cm.setCursor(13, 0); + helpers.doKeys('v', 'a', 'p'); + eqCursorPos(Pos(13, 0), cm.getCursor('anchor')); + eqCursorPos(Pos(14, 0), cm.getCursor('head')); + + cm.setCursor(16, 0); + helpers.doKeys('v', 'a', 'p'); + eqCursorPos(Pos(14, 0), cm.getCursor('anchor')); + eqCursorPos(Pos(16, 1), cm.getCursor('head')); + + cm.setCursor(0, 0); + helpers.doKeys('v', 'a', 'p'); + eqCursorPos(Pos(0, 0), cm.getCursor('anchor')); + eqCursorPos(Pos(4, 0), cm.getCursor('head')); + + cm.setCursor(0, 0); + helpers.doKeys('d', 'i', 'p'); + var register = helpers.getRegisterController().getRegister(); + eq('a\na\n', register.toString()); + is(register.linewise); + helpers.doKeys('3', 'j', 'p'); + helpers.doKeys('y', 'i', 'p'); + is(register.linewise); + eq('b\na\na\nc\n', register.toString()); +}, { value: 'a\na\n\n\n\nb\nc\n\n\n\n\n\n\nd\n\ne\nf' }); + +// Operator tests +testVim('dl', function(cm, vim, helpers) { + var curStart = makeCursor(0, 0); + cm.setCursor(curStart); + helpers.doKeys('d', 'l'); + eq('word1 ', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq(' ', register.toString()); + is(!register.linewise); + eqCursorPos(curStart, cm.getCursor()); +}, { value: ' word1 ' }); +testVim('dl_eol', function(cm, vim, helpers) { + cm.setCursor(0, 6); + helpers.doKeys('d', 'l'); + eq(' word1', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq(' ', register.toString()); + is(!register.linewise); + helpers.assertCursorAt(0, 5); +}, { value: ' word1 ' }); +testVim('dl_repeat', function(cm, vim, helpers) { + var curStart = makeCursor(0, 0); + cm.setCursor(curStart); + helpers.doKeys('2', 'd', 'l'); + eq('ord1 ', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq(' w', register.toString()); + is(!register.linewise); + eqCursorPos(curStart, cm.getCursor()); +}, { value: ' word1 ' }); +testVim('dh', function(cm, vim, helpers) { + var curStart = makeCursor(0, 3); + cm.setCursor(curStart); + helpers.doKeys('d', 'h'); + eq(' wrd1 ', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('o', register.toString()); + is(!register.linewise); + eqCursorPos(offsetCursor(curStart, 0 , -1), cm.getCursor()); +}, { value: ' word1 ' }); +testVim('dj', function(cm, vim, helpers) { + var curStart = makeCursor(0, 3); + cm.setCursor(curStart); + helpers.doKeys('d', 'j'); + eq(' word3', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq(' word1\nword2\n', register.toString()); + is(register.linewise); + helpers.assertCursorAt(0, 1); +}, { value: ' word1\nword2\n word3' }); +testVim('dj_end_of_document', function(cm, vim, helpers) { + var curStart = makeCursor(0, 3); + cm.setCursor(curStart); + helpers.doKeys('d', 'j'); + eq('', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq(' word1 \n', register.toString()); + is(register.linewise); + helpers.assertCursorAt(0, 0); +}, { value: ' word1 ' }); +testVim('dk', function(cm, vim, helpers) { + var curStart = makeCursor(1, 3); + cm.setCursor(curStart); + helpers.doKeys('d', 'k'); + eq(' word3', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq(' word1\nword2\n', register.toString()); + is(register.linewise); + helpers.assertCursorAt(0, 1); +}, { value: ' word1\nword2\n word3' }); +testVim('dk_start_of_document', function(cm, vim, helpers) { + var curStart = makeCursor(0, 3); + cm.setCursor(curStart); + helpers.doKeys('d', 'k'); + eq('', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq(' word1 \n', register.toString()); + is(register.linewise); + helpers.assertCursorAt(0, 0); +}, { value: ' word1 ' }); +testVim('dw_space', function(cm, vim, helpers) { + var curStart = makeCursor(0, 0); + cm.setCursor(curStart); + helpers.doKeys('d', 'w'); + eq('word1 ', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq(' ', register.toString()); + is(!register.linewise); + eqCursorPos(curStart, cm.getCursor()); +}, { value: ' word1 ' }); +testVim('dw_word', function(cm, vim, helpers) { + var curStart = makeCursor(0, 1); + cm.setCursor(curStart); + helpers.doKeys('d', 'w'); + eq(' word2', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('word1 ', register.toString()); + is(!register.linewise); + eqCursorPos(curStart, cm.getCursor()); +}, { value: ' word1 word2' }); +testVim('dw_unicode_word', function(cm, vim, helpers) { + helpers.doKeys('d', 'w'); + eq(cm.getValue().length, 10); + helpers.doKeys('d', 'w'); + eq(cm.getValue().length, 6); + helpers.doKeys('d', 'w'); + eq(cm.getValue().length, 5); + helpers.doKeys('d', 'e'); + eq(cm.getValue().length, 2); +}, { value: ' \u0562\u0561\u0580\u0587\xbbe\xb5g ' }); +testVim('dw_only_word', function(cm, vim, helpers) { + // Test that if there is only 1 word left, dw deletes till the end of the + // line. + cm.setCursor(0, 1); + helpers.doKeys('d', 'w'); + eq(' ', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('word1 ', register.toString()); + is(!register.linewise); + helpers.assertCursorAt(0, 0); +}, { value: ' word1 ' }); +testVim('dw_eol', function(cm, vim, helpers) { + // Assert that dw does not delete the newline if last word to delete is at end + // of line. + cm.setCursor(0, 1); + helpers.doKeys('d', 'w'); + eq(' \nword2', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('word1', register.toString()); + is(!register.linewise); + helpers.assertCursorAt(0, 0); +}, { value: ' word1\nword2' }); +testVim('dw_eol_with_multiple_newlines', function(cm, vim, helpers) { + // Assert that dw does not delete the newline if last word to delete is at end + // of line and it is followed by multiple newlines. + cm.setCursor(0, 1); + helpers.doKeys('d', 'w'); + eq(' \n\nword2', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('word1', register.toString()); + is(!register.linewise); + helpers.assertCursorAt(0, 0); +}, { value: ' word1\n\nword2' }); +testVim('dw_empty_line_followed_by_whitespace', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('d', 'w'); + eq(' \nword', cm.getValue()); +}, { value: '\n \nword' }); +testVim('dw_empty_line_followed_by_word', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('d', 'w'); + eq('word', cm.getValue()); +}, { value: '\nword' }); +testVim('dw_empty_line_followed_by_empty_line', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('d', 'w'); + eq('\n', cm.getValue()); +}, { value: '\n\n' }); +testVim('dw_whitespace_followed_by_whitespace', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('d', 'w'); + eq('\n \n', cm.getValue()); +}, { value: ' \n \n' }); +testVim('dw_whitespace_followed_by_empty_line', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('d', 'w'); + eq('\n\n', cm.getValue()); +}, { value: ' \n\n' }); +testVim('dw_word_whitespace_word', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('d', 'w'); + eq('\n \nword2', cm.getValue()); +}, { value: 'word1\n \nword2'}) +testVim('dw_end_of_document', function(cm, vim, helpers) { + cm.setCursor(1, 2); + helpers.doKeys('d', 'w'); + eq('\nab', cm.getValue()); +}, { value: '\nabc' }); +testVim('dw_repeat', function(cm, vim, helpers) { + // Assert that dw does delete newline if it should go to the next line, and + // that repeat works properly. + cm.setCursor(0, 1); + helpers.doKeys('d', '2', 'w'); + eq(' ', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('word1\nword2', register.toString()); + is(!register.linewise); + helpers.assertCursorAt(0, 0); +}, { value: ' word1\nword2' }); +testVim('de_word_start_and_empty_lines', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('d', 'e'); + eq('\n\n', cm.getValue()); +}, { value: 'word\n\n' }); +testVim('de_word_end_and_empty_lines', function(cm, vim, helpers) { + cm.setCursor(0, 3); + helpers.doKeys('d', 'e'); + eq('wor', cm.getValue()); +}, { value: 'word\n\n\n' }); +testVim('de_whitespace_and_empty_lines', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('d', 'e'); + eq('', cm.getValue()); +}, { value: ' \n\n\n' }); +testVim('de_end_of_document', function(cm, vim, helpers) { + cm.setCursor(1, 2); + helpers.doKeys('d', 'e'); + eq('\nab', cm.getValue()); +}, { value: '\nabc' }); +testVim('db_empty_lines', function(cm, vim, helpers) { + cm.setCursor(2, 0); + helpers.doKeys('d', 'b'); + eq('\n\n', cm.getValue()); +}, { value: '\n\n\n' }); +testVim('db_word_start_and_empty_lines', function(cm, vim, helpers) { + cm.setCursor(2, 0); + helpers.doKeys('d', 'b'); + eq('\nword', cm.getValue()); +}, { value: '\n\nword' }); +testVim('db_word_end_and_empty_lines', function(cm, vim, helpers) { + cm.setCursor(2, 3); + helpers.doKeys('d', 'b'); + eq('\n\nd', cm.getValue()); +}, { value: '\n\nword' }); +testVim('db_whitespace_and_empty_lines', function(cm, vim, helpers) { + cm.setCursor(2, 0); + helpers.doKeys('d', 'b'); + eq('', cm.getValue()); +}, { value: '\n \n' }); +testVim('db_start_of_document', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('d', 'b'); + eq('abc\n', cm.getValue()); +}, { value: 'abc\n' }); +testVim('dge_empty_lines', function(cm, vim, helpers) { + cm.setCursor(1, 0); + helpers.doKeys('d', 'g', 'e'); + // Note: In real VIM the result should be '', but it's not quite consistent, + // since 2 newlines are deleted. But in the similar case of word\n\n, only + // 1 newline is deleted. We'll diverge from VIM's behavior since it's much + // easier this way. + eq('\n', cm.getValue()); +}, { value: '\n\n' }); +testVim('dge_word_and_empty_lines', function(cm, vim, helpers) { + cm.setCursor(1, 0); + helpers.doKeys('d', 'g', 'e'); + eq('wor\n', cm.getValue()); +}, { value: 'word\n\n'}); +testVim('dge_whitespace_and_empty_lines', function(cm, vim, helpers) { + cm.setCursor(2, 0); + helpers.doKeys('d', 'g', 'e'); + eq('', cm.getValue()); +}, { value: '\n \n' }); +testVim('dge_start_of_document', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('d', 'g', 'e'); + eq('bc\n', cm.getValue()); +}, { value: 'abc\n' }); +testVim('d_inclusive', function(cm, vim, helpers) { + // Assert that when inclusive is set, the character the cursor is on gets + // deleted too. + var curStart = makeCursor(0, 1); + cm.setCursor(curStart); + helpers.doKeys('d', 'e'); + eq(' ', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('word1', register.toString()); + is(!register.linewise); + eqCursorPos(curStart, cm.getCursor()); +}, { value: ' word1 ' }); +testVim('d_reverse', function(cm, vim, helpers) { + // Test that deleting in reverse works. + cm.setCursor(1, 0); + helpers.doKeys('d', 'b'); + eq(' word2 ', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('word1\n', register.toString()); + is(!register.linewise); + helpers.assertCursorAt(0, 1); +}, { value: ' word1\nword2 ' }); +testVim('dd', function(cm, vim, helpers) { + cm.setCursor(0, 3); + var expectedBuffer = cm.getRange(new Pos(0, 0), + new Pos(1, 0)); + var expectedLineCount = cm.lineCount() - 1; + helpers.doKeys('d', 'd'); + eq(expectedLineCount, cm.lineCount()); + var register = helpers.getRegisterController().getRegister(); + eq(expectedBuffer, register.toString()); + is(register.linewise); + helpers.assertCursorAt(0, lines[1].textStart); +}); +testVim('dd_prefix_repeat', function(cm, vim, helpers) { + cm.setCursor(0, 3); + var expectedBuffer = cm.getRange(new Pos(0, 0), + new Pos(2, 0)); + var expectedLineCount = cm.lineCount() - 2; + helpers.doKeys('2', 'd', 'd'); + eq(expectedLineCount, cm.lineCount()); + var register = helpers.getRegisterController().getRegister(); + eq(expectedBuffer, register.toString()); + is(register.linewise); + helpers.assertCursorAt(0, lines[2].textStart); +}); +testVim('dd_motion_repeat', function(cm, vim, helpers) { + cm.setCursor(0, 3); + var expectedBuffer = cm.getRange(new Pos(0, 0), + new Pos(2, 0)); + var expectedLineCount = cm.lineCount() - 2; + helpers.doKeys('d', '2', 'd'); + eq(expectedLineCount, cm.lineCount()); + var register = helpers.getRegisterController().getRegister(); + eq(expectedBuffer, register.toString()); + is(register.linewise); + helpers.assertCursorAt(0, lines[2].textStart); +}); +testVim('dd_multiply_repeat', function(cm, vim, helpers) { + cm.setCursor(0, 3); + var expectedBuffer = cm.getRange(new Pos(0, 0), + new Pos(6, 0)); + var expectedLineCount = cm.lineCount() - 6; + helpers.doKeys('2', 'd', '3', 'd'); + eq(expectedLineCount, cm.lineCount()); + var register = helpers.getRegisterController().getRegister(); + eq(expectedBuffer, register.toString()); + is(register.linewise); + helpers.assertCursorAt(0, lines[6].textStart); +}); +testVim('dd_lastline', function(cm, vim, helpers) { + cm.setCursor(cm.lineCount(), 0); + var expectedLineCount = cm.lineCount() - 1; + helpers.doKeys('d', 'd'); + eq(expectedLineCount, cm.lineCount()); + helpers.assertCursorAt(cm.lineCount() - 1, 0); +}); +testVim('dd_only_line', function(cm, vim, helpers) { + cm.setCursor(0, 0); + var expectedRegister = cm.getValue() + "\n"; + helpers.doKeys('d','d'); + eq(1, cm.lineCount()); + eq('', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq(expectedRegister, register.toString()); +}, { value: "thisistheonlyline" }); +// Yank commands should behave the exact same as d commands, expect that nothing +// gets deleted. +testVim('yw_repeat', function(cm, vim, helpers) { + // Assert that yw does yank newline if it should go to the next line, and + // that repeat works properly. + var curStart = makeCursor(0, 1); + cm.setCursor(curStart); + helpers.doKeys('y', '2', 'w'); + eq(' word1\nword2', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('word1\nword2', register.toString()); + is(!register.linewise); + eqCursorPos(curStart, cm.getCursor()); +}, { value: ' word1\nword2' }); +testVim('yy_multiply_repeat', function(cm, vim, helpers) { + var curStart = makeCursor(0, 3); + cm.setCursor(curStart); + var expectedBuffer = cm.getRange(new Pos(0, 0), + new Pos(6, 0)); + var expectedLineCount = cm.lineCount(); + helpers.doKeys('2', 'y', '3', 'y'); + eq(expectedLineCount, cm.lineCount()); + var register = helpers.getRegisterController().getRegister(); + eq(expectedBuffer, register.toString()); + is(register.linewise); + eqCursorPos(curStart, cm.getCursor()); +}); +testVim('2dd_blank_P', function(cm, vim, helpers) { + helpers.doKeys('2', 'd', 'd', 'P'); + eq('\na\n\n', cm.getValue()); +}, { value: '\na\n\n' }); +// Change commands behave like d commands except that it also enters insert +// mode. In addition, when the change is linewise, an additional newline is +// inserted so that insert mode starts on that line. +testVim('cw', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('c', '2', 'w'); + eq(' word3', cm.getValue()); + helpers.assertCursorAt(0, 0); +}, { value: 'word1 word2 word3'}); +testVim('cw_repeat', function(cm, vim, helpers) { + // Assert that cw does delete newline if it should go to the next line, and + // that repeat works properly. + var curStart = makeCursor(0, 1); + cm.setCursor(curStart); + helpers.doKeys('c', '2', 'w'); + eq(' ', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('word1\nword2', register.toString()); + is(!register.linewise); + eqCursorPos(curStart, cm.getCursor()); + eq('vim-insert', cm.getOption('keyMap')); +}, { value: ' word1\nword2' }); +testVim('cc_multiply_repeat', function(cm, vim, helpers) { + cm.setCursor(0, 3); + var expectedBuffer = cm.getRange(new Pos(0, 0), + new Pos(6, 0)); + var expectedLineCount = cm.lineCount() - 5; + helpers.doKeys('2', 'c', '3', 'c'); + eq(expectedLineCount, cm.lineCount()); + var register = helpers.getRegisterController().getRegister(); + eq(expectedBuffer, register.toString()); + is(register.linewise); + eq('vim-insert', cm.getOption('keyMap')); +}); +testVim('ct', function(cm, vim, helpers) { + cm.setCursor(0, 9); + helpers.doKeys('c', 't', 'w'); + eq(' word1 word3', cm.getValue()); + helpers.doKeys('<Esc>', 'c', '|'); + eq(' word3', cm.getValue()); + helpers.assertCursorAt(0, 0); + helpers.doKeys('<Esc>', '2', 'u', 'w', 'h'); + helpers.doKeys('c', '2', 'g', 'e'); + eq(' wordword3', cm.getValue()); +}, { value: ' word1 word2 word3'}); +testVim('cc_should_not_append_to_document', function(cm, vim, helpers) { + var expectedLineCount = cm.lineCount(); + cm.setCursor(cm.lastLine(), 0); + helpers.doKeys('c', 'c'); + eq(expectedLineCount, cm.lineCount()); +}); +function fillArray(val, times) { + var arr = []; + for (var i = 0; i < times; i++) { + arr.push(val); + } + return arr; +} +testVim('c_visual_block', function(cm, vim, helpers) { + cm.setCursor(0, 1); + helpers.doKeys('<C-v>', '2', 'j', 'l', 'l', 'l', 'c'); + var replacement = fillArray('hello', 3); + cm.replaceSelections(replacement); + eq('1hello\n5hello\nahellofg', cm.getValue()); + helpers.doKeys('<Esc>'); + cm.setCursor(2, 3); + helpers.doKeys('<C-v>', '2', 'k', 'h', 'C'); + replacement = fillArray('world', 3); + cm.replaceSelections(replacement); + eq('1hworld\n5hworld\nahworld', cm.getValue()); +}, {value: '1234\n5678\nabcdefg'}); +testVim('c_visual_block_replay', function(cm, vim, helpers) { + cm.setCursor(0, 1); + helpers.doKeys('<C-v>', '2', 'j', 'l', 'c'); + var replacement = fillArray('fo', 3); + cm.replaceSelections(replacement); + eq('1fo4\n5fo8\nafodefg', cm.getValue()); + helpers.doKeys('<Esc>'); + cm.setCursor(0, 0); + helpers.doKeys('.'); + eq('foo4\nfoo8\nfoodefg', cm.getValue()); +}, {value: '1234\n5678\nabcdefg'}); + +testVim('d_visual_block', function(cm, vim, helpers) { + cm.setCursor(0, 1); + helpers.doKeys('<C-v>', '2', 'j', 'l', 'l', 'l', 'd'); + eq('1\n5\nafg', cm.getValue()); +}, {value: '1234\n5678\nabcdefg'}); +testVim('D_visual_block', function(cm, vim, helpers) { + cm.setCursor(0, 1); + helpers.doKeys('<C-v>', '2', 'j', 'l', 'D'); + eq('1\n5\na', cm.getValue()); +}, {value: '1234\n5678\nabcdefg'}); + +testVim('s_visual_block', function(cm, vim, helpers) { + cm.setCursor(0, 1); + helpers.doKeys('<C-v>', '2', 'j', 'l', 'l', 'l', 's'); + var replacement = fillArray('hello{', 3); + cm.replaceSelections(replacement); + eq('1hello{\n5hello{\nahello{fg\n', cm.getValue()); + helpers.doKeys('<Esc>'); + cm.setCursor(2, 3); + helpers.doKeys('<C-v>', '1', 'k', 'h', 'S'); + replacement = fillArray('world', 1); + cm.replaceSelections(replacement); + eq('1hello{\n world\n', cm.getValue()); +}, {value: '1234\n5678\nabcdefg\n'}); + +// Swapcase commands edit in place and do not modify registers. +testVim('g~w_repeat', function(cm, vim, helpers) { + // Assert that dw does delete newline if it should go to the next line, and + // that repeat works properly. + var curStart = makeCursor(0, 1); + cm.setCursor(curStart); + helpers.doKeys('g', '~', '2', 'w'); + eq(' WORD1\nWORD2', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('', register.toString()); + is(!register.linewise); + eqCursorPos(curStart, cm.getCursor()); +}, { value: ' word1\nword2' }); +testVim('g~g~', function(cm, vim, helpers) { + var curStart = makeCursor(0, 3); + cm.setCursor(curStart); + var expectedLineCount = cm.lineCount(); + var expectedValue = cm.getValue().toUpperCase(); + helpers.doKeys('2', 'g', '~', '3', 'g', '~'); + eq(expectedValue, cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('', register.toString()); + is(!register.linewise); + eqCursorPos(curStart, cm.getCursor()); +}, { value: ' word1\nword2\nword3\nword4\nword5\nword6' }); +testVim('gu_and_gU', function(cm, vim, helpers) { + var curStart = makeCursor(0, 7); + var value = cm.getValue(); + cm.setCursor(curStart); + helpers.doKeys('2', 'g', 'U', 'w'); + eq(cm.getValue(), 'wa wb xX WC wd'); + eqCursorPos(curStart, cm.getCursor()); + helpers.doKeys('2', 'g', 'u', 'w'); + eq(cm.getValue(), value); + + helpers.doKeys('2', 'g', 'U', 'B'); + eq(cm.getValue(), 'wa WB Xx wc wd'); + eqCursorPos(makeCursor(0, 3), cm.getCursor()); + + cm.setCursor(makeCursor(0, 4)); + helpers.doKeys('g', 'u', 'i', 'w'); + eq(cm.getValue(), 'wa wb Xx wc wd'); + eqCursorPos(makeCursor(0, 3), cm.getCursor()); + + // TODO: support gUgU guu + // eqCursorPos(makeCursor(0, 0), cm.getCursor()); + + var register = helpers.getRegisterController().getRegister(); + eq('', register.toString()); + is(!register.linewise); +}, { value: 'wa wb xx wc wd' }); +testVim('visual_block_~', function(cm, vim, helpers) { + cm.setCursor(1, 1); + helpers.doKeys('<C-v>', 'l', 'l', 'j', '~'); + helpers.assertCursorAt(1, 1); + eq('hello\nwoRLd\naBCDe', cm.getValue()); + cm.setCursor(2, 0); + helpers.doKeys('v', 'l', 'l', '~'); + helpers.assertCursorAt(2, 0); + eq('hello\nwoRLd\nAbcDe', cm.getValue()); +},{value: 'hello\nwOrld\nabcde' }); +testVim('._swapCase_visualBlock', function(cm, vim, helpers) { + helpers.doKeys('<C-v>', 'j', 'j', 'l', '~'); + cm.setCursor(0, 3); + helpers.doKeys('.'); + eq('HelLO\nWorLd\nAbcdE', cm.getValue()); +},{value: 'hEllo\nwOrlD\naBcDe' }); +testVim('._delete_visualBlock', function(cm, vim, helpers) { + helpers.doKeys('<C-v>', 'j', 'x'); + eq('ive\ne\nsome\nsugar', cm.getValue()); + helpers.doKeys('.'); + eq('ve\n\nsome\nsugar', cm.getValue()); + helpers.doKeys('j', 'j', '.'); + eq('ve\n\nome\nugar', cm.getValue()); + helpers.doKeys('u', '<C-r>', '.'); + eq('ve\n\nme\ngar', cm.getValue()); +},{value: 'give\nme\nsome\nsugar' }); +testVim('>{motion}', function(cm, vim, helpers) { + cm.setCursor(1, 3); + var expectedLineCount = cm.lineCount(); + var expectedValue = ' word1\n word2\nword3 '; + helpers.doKeys('>', 'k'); + eq(expectedValue, cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('', register.toString()); + is(!register.linewise); + helpers.assertCursorAt(0, 3); +}, { value: ' word1\nword2\nword3 ', indentUnit: 2 }); +testVim('>>', function(cm, vim, helpers) { + cm.setCursor(0, 3); + var expectedLineCount = cm.lineCount(); + var expectedValue = ' word1\n word2\nword3 '; + helpers.doKeys('2', '>', '>'); + eq(expectedValue, cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('', register.toString()); + is(!register.linewise); + helpers.assertCursorAt(0, 3); +}, { value: ' word1\nword2\nword3 ', indentUnit: 2 }); +testVim('<{motion}', function(cm, vim, helpers) { + cm.setCursor(1, 3); + var expectedLineCount = cm.lineCount(); + var expectedValue = ' word1\nword2\nword3 '; + helpers.doKeys('<', 'k'); + eq(expectedValue, cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('', register.toString()); + is(!register.linewise); + helpers.assertCursorAt(0, 1); +}, { value: ' word1\n word2\nword3 ', indentUnit: 2 }); +testVim('<<', function(cm, vim, helpers) { + cm.setCursor(0, 3); + var expectedLineCount = cm.lineCount(); + var expectedValue = ' word1\nword2\nword3 '; + helpers.doKeys('2', '<', '<'); + eq(expectedValue, cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('', register.toString()); + is(!register.linewise); + helpers.assertCursorAt(0, 1); +}, { value: ' word1\n word2\nword3 ', indentUnit: 2 }); + +// Edit tests +function testEdit(name, before, pos, edit, after) { + return testVim(name, function(cm, vim, helpers) { + var ch = before.search(pos) + var line = before.substring(0, ch).split('\n').length - 1; + if (line) { + ch = before.substring(0, ch).split('\n').pop().length; + } + cm.setCursor(line, ch); + helpers.doKeys.apply(this, edit.split('')); + eq(after, cm.getValue()); + }, {value: before}); +} + +// These Delete tests effectively cover word-wise Change, Visual & Yank. +// Tabs are used as differentiated whitespace to catch edge cases. +// Normal word: +testEdit('diw_mid_spc', 'foo \tbAr\t baz', /A/, 'diw', 'foo \t\t baz'); +testEdit('daw_mid_spc', 'foo \tbAr\t baz', /A/, 'daw', 'foo \tbaz'); +testEdit('diw_mid_punct', 'foo \tbAr.\t baz', /A/, 'diw', 'foo \t.\t baz'); +testEdit('daw_mid_punct', 'foo \tbAr.\t baz', /A/, 'daw', 'foo.\t baz'); +testEdit('diw_mid_punct2', 'foo \t,bAr.\t baz', /A/, 'diw', 'foo \t,.\t baz'); +testEdit('daw_mid_punct2', 'foo \t,bAr.\t baz', /A/, 'daw', 'foo \t,.\t baz'); +testEdit('diw_start_spc', 'bAr \tbaz', /A/, 'diw', ' \tbaz'); +testEdit('daw_start_spc', 'bAr \tbaz', /A/, 'daw', 'baz'); +testEdit('diw_start_punct', 'bAr. \tbaz', /A/, 'diw', '. \tbaz'); +testEdit('daw_start_punct', 'bAr. \tbaz', /A/, 'daw', '. \tbaz'); +testEdit('diw_end_spc', 'foo \tbAr', /A/, 'diw', 'foo \t'); +testEdit('daw_end_spc', 'foo \tbAr', /A/, 'daw', 'foo'); +testEdit('diw_end_punct', 'foo \tbAr.', /A/, 'diw', 'foo \t.'); +testEdit('daw_end_punct', 'foo \tbAr.', /A/, 'daw', 'foo.'); +// Big word: +testEdit('diW_mid_spc', 'foo \tbAr\t baz', /A/, 'diW', 'foo \t\t baz'); +testEdit('daW_mid_spc', 'foo \tbAr\t baz', /A/, 'daW', 'foo \tbaz'); +testEdit('diW_mid_punct', 'foo \tbAr.\t baz', /A/, 'diW', 'foo \t\t baz'); +testEdit('daW_mid_punct', 'foo \tbAr.\t baz', /A/, 'daW', 'foo \tbaz'); +testEdit('diW_mid_punct2', 'foo \t,bAr.\t baz', /A/, 'diW', 'foo \t\t baz'); +testEdit('daW_mid_punct2', 'foo \t,bAr.\t baz', /A/, 'daW', 'foo \tbaz'); +testEdit('diW_start_spc', 'bAr\t baz', /A/, 'diW', '\t baz'); +testEdit('daW_start_spc', 'bAr\t baz', /A/, 'daW', 'baz'); +testEdit('diW_start_punct', 'bAr.\t baz', /A/, 'diW', '\t baz'); +testEdit('daW_start_punct', 'bAr.\t baz', /A/, 'daW', 'baz'); +testEdit('diW_end_spc', 'foo \tbAr', /A/, 'diW', 'foo \t'); +testEdit('daW_end_spc', 'foo \tbAr', /A/, 'daW', 'foo'); +testEdit('diW_end_punct', 'foo \tbAr.', /A/, 'diW', 'foo \t'); +testEdit('daW_end_punct', 'foo \tbAr.', /A/, 'daW', 'foo'); +// Deleting text objects +// Open and close on same line +testEdit('di(_open_spc', 'foo (bAr) baz', /\(/, 'di(', 'foo () baz'); +testEdit('di)_open_spc', 'foo (bAr) baz', /\(/, 'di)', 'foo () baz'); +testEdit('dib_open_spc', 'foo (bAr) baz', /\(/, 'dib', 'foo () baz'); +testEdit('da(_open_spc', 'foo (bAr) baz', /\(/, 'da(', 'foo baz'); +testEdit('da)_open_spc', 'foo (bAr) baz', /\(/, 'da)', 'foo baz'); + +testEdit('di(_middle_spc', 'foo (bAr) baz', /A/, 'di(', 'foo () baz'); +testEdit('di)_middle_spc', 'foo (bAr) baz', /A/, 'di)', 'foo () baz'); +testEdit('da(_middle_spc', 'foo (bAr) baz', /A/, 'da(', 'foo baz'); +testEdit('da)_middle_spc', 'foo (bAr) baz', /A/, 'da)', 'foo baz'); + +testEdit('di(_close_spc', 'foo (bAr) baz', /\)/, 'di(', 'foo () baz'); +testEdit('di)_close_spc', 'foo (bAr) baz', /\)/, 'di)', 'foo () baz'); +testEdit('da(_close_spc', 'foo (bAr) baz', /\)/, 'da(', 'foo baz'); +testEdit('da)_close_spc', 'foo (bAr) baz', /\)/, 'da)', 'foo baz'); + +// delete around and inner b. +testEdit('dab_on_(_should_delete_around_()block', 'o( in(abc) )', /\(a/, 'dab', 'o( in )'); + +// delete around and inner B. +testEdit('daB_on_{_should_delete_around_{}block', 'o{ in{abc} }', /{a/, 'daB', 'o{ in }'); +testEdit('diB_on_{_should_delete_inner_{}block', 'o{ in{abc} }', /{a/, 'diB', 'o{ in{} }'); + +testEdit('da{_on_{_should_delete_inner_block', 'o{ in{abc} }', /{a/, 'da{', 'o{ in }'); +testEdit('di[_on_(_should_not_delete', 'foo (bAr) baz', /\(/, 'di[', 'foo (bAr) baz'); +testEdit('di[_on_)_should_not_delete', 'foo (bAr) baz', /\)/, 'di[', 'foo (bAr) baz'); +testEdit('da[_on_(_should_not_delete', 'foo (bAr) baz', /\(/, 'da[', 'foo (bAr) baz'); +testEdit('da[_on_)_should_not_delete', 'foo (bAr) baz', /\)/, 'da[', 'foo (bAr) baz'); +testMotion('di(_outside_should_stay', ['d', 'i', '('], new Pos(0, 0), new Pos(0, 0)); + +// Open and close on different lines, equally indented +testEdit('di{_middle_spc', 'a{\n\tbar\n}b', /r/, 'di{', 'a{}b'); +testEdit('di}_middle_spc', 'a{\n\tbar\n}b', /r/, 'di}', 'a{}b'); +testEdit('da{_middle_spc', 'a{\n\tbar\n}b', /r/, 'da{', 'ab'); +testEdit('da}_middle_spc', 'a{\n\tbar\n}b', /r/, 'da}', 'ab'); +testEdit('daB_middle_spc', 'a{\n\tbar\n}b', /r/, 'daB', 'ab'); + +// open and close on diff lines, open indented less than close +testEdit('di{_middle_spc', 'a{\n\tbar\n\t}b', /r/, 'di{', 'a{}b'); +testEdit('di}_middle_spc', 'a{\n\tbar\n\t}b', /r/, 'di}', 'a{}b'); +testEdit('da{_middle_spc', 'a{\n\tbar\n\t}b', /r/, 'da{', 'ab'); +testEdit('da}_middle_spc', 'a{\n\tbar\n\t}b', /r/, 'da}', 'ab'); + +// open and close on diff lines, open indented more than close +testEdit('di[_middle_spc', 'a\t[\n\tbar\n]b', /r/, 'di[', 'a\t[]b'); +testEdit('di]_middle_spc', 'a\t[\n\tbar\n]b', /r/, 'di]', 'a\t[]b'); +testEdit('da[_middle_spc', 'a\t[\n\tbar\n]b', /r/, 'da[', 'a\tb'); +testEdit('da]_middle_spc', 'a\t[\n\tbar\n]b', /r/, 'da]', 'a\tb'); + +function testSelection(name, before, pos, keys, sel) { + return testVim(name, function(cm, vim, helpers) { + var ch = before.search(pos) + var line = before.substring(0, ch).split('\n').length - 1; + if (line) { + ch = before.substring(0, ch).split('\n').pop().length; + } + cm.setCursor(line, ch); + helpers.doKeys.apply(this, keys.split('')); + eq(sel, cm.getSelection()); + }, {value: before}); +} +testSelection('viw_middle_spc', 'foo \tbAr\t baz', /A/, 'viw', 'bAr'); +testSelection('vaw_middle_spc', 'foo \tbAr\t baz', /A/, 'vaw', 'bAr\t '); +testSelection('viw_middle_punct', 'foo \tbAr,\t baz', /A/, 'viw', 'bAr'); +testSelection('vaW_middle_punct', 'foo \tbAr,\t baz', /A/, 'vaW', 'bAr,\t '); +testSelection('viw_start_spc', 'foo \tbAr\t baz', /b/, 'viw', 'bAr'); +testSelection('viw_end_spc', 'foo \tbAr\t baz', /r/, 'viw', 'bAr'); +testSelection('viw_eol', 'foo \tbAr', /r/, 'viw', 'bAr'); +testSelection('vi{_middle_spc', 'a{\n\tbar\n\t}b', /r/, 'vi{', '\n\tbar\n\t'); +testSelection('va{_middle_spc', 'a{\n\tbar\n\t}b', /r/, 'va{', '{\n\tbar\n\t}'); + +testVim('mouse_select', function(cm, vim, helpers) { + cm.setSelection(Pos(0, 2), Pos(0, 4), {origin: '*mouse'}); + is(cm.state.vim.visualMode); + is(!cm.state.vim.visualLine); + is(!cm.state.vim.visualBlock); + helpers.doKeys('<Esc>'); + is(!cm.somethingSelected()); + helpers.doKeys('g', 'v'); + eq('cd', cm.getSelection()); +}, {value: 'abcdef'}); + +// Operator-motion tests +testVim('D', function(cm, vim, helpers) { + cm.setCursor(0, 3); + helpers.doKeys('D'); + eq(' wo\nword2\n word3', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('rd1', register.toString()); + is(!register.linewise); + helpers.assertCursorAt(0, 2); +}, { value: ' word1\nword2\n word3' }); +testVim('C', function(cm, vim, helpers) { + var curStart = makeCursor(0, 3); + cm.setCursor(curStart); + helpers.doKeys('C'); + eq(' wo\nword2\n word3', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('rd1', register.toString()); + is(!register.linewise); + eqCursorPos(curStart, cm.getCursor()); + eq('vim-insert', cm.getOption('keyMap')); +}, { value: ' word1\nword2\n word3' }); +testVim('Y', function(cm, vim, helpers) { + var curStart = makeCursor(0, 3); + cm.setCursor(curStart); + helpers.doKeys('Y'); + eq(' word1\nword2\n word3', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq(' word1\n', register.toString()); + is(register.linewise); + helpers.assertCursorAt(0, 3); +}, { value: ' word1\nword2\n word3' }); +testVim('~', function(cm, vim, helpers) { + helpers.doKeys('3', '~'); + eq('ABCdefg', cm.getValue()); + helpers.assertCursorAt(0, 3); +}, { value: 'abcdefg' }); + +// Action tests +testVim('ctrl-a', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('<C-a>'); + eq('-9', cm.getValue()); + helpers.assertCursorAt(0, 1); + helpers.doKeys('2','<C-a>'); + eq('-7', cm.getValue()); +}, {value: '-10'}); +testVim('ctrl-x', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('<C-x>'); + eq('-1', cm.getValue()); + helpers.assertCursorAt(0, 1); + helpers.doKeys('2','<C-x>'); + eq('-3', cm.getValue()); +}, {value: '0'}); +testVim('<C-x>/<C-a> search forward', function(cm, vim, helpers) { + forEach(['<C-x>', '<C-a>'], function(key) { + cm.setCursor(0, 0); + helpers.doKeys(key); + helpers.assertCursorAt(0, 5); + helpers.doKeys('l'); + helpers.doKeys(key); + helpers.assertCursorAt(0, 10); + cm.setCursor(0, 11); + helpers.doKeys(key); + helpers.assertCursorAt(0, 11); + }); +}, {value: '__jmp1 jmp2 jmp'}); +testVim('insert_ctrl_w', function(cm, vim, helpers) { + var curStart = makeCursor(0, 10); + cm.setCursor(curStart); + helpers.doKeys('a'); + helpers.doKeys('<C-w>'); + eq('word1/', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('word2', register.toString()); + is(!register.linewise); + var curEnd = makeCursor(0, 6); + eqCursorPos(curEnd, cm.getCursor()); + eq('vim-insert', cm.getOption('keyMap')); +}, { value: 'word1/word2' }); +testVim('a', function(cm, vim, helpers) { + cm.setCursor(0, 1); + helpers.doKeys('a'); + helpers.assertCursorAt(0, 2); + eq('vim-insert', cm.getOption('keyMap')); +}); +testVim('a_eol', function(cm, vim, helpers) { + cm.setCursor(0, lines[0].length - 1); + helpers.doKeys('a'); + helpers.assertCursorAt(0, lines[0].length); + eq('vim-insert', cm.getOption('keyMap')); +}); +testVim('A_endOfSelectedArea', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('v', 'j', 'l'); + helpers.doKeys('A'); + helpers.assertCursorAt(1, 2); + eq('vim-insert', cm.getOption('keyMap')); +}, {value: 'foo\nbar'}); +testVim('i', function(cm, vim, helpers) { + cm.setCursor(0, 1); + helpers.doKeys('i'); + helpers.assertCursorAt(0, 1); + eq('vim-insert', cm.getOption('keyMap')); +}); +testVim('i_repeat', function(cm, vim, helpers) { + helpers.doKeys('3', 'i'); + cm.replaceRange('test', cm.getCursor()); + helpers.doKeys('<Esc>'); + eq('testtesttest', cm.getValue()); + helpers.assertCursorAt(0, 11); +}, { value: '' }); +testVim('i_repeat_delete', function(cm, vim, helpers) { + cm.setCursor(0, 4); + helpers.doKeys('2', 'i'); + cm.replaceRange('z', cm.getCursor()); + helpers.doInsertModeKeys('Backspace', 'Backspace'); + helpers.doKeys('<Esc>'); + eq('abe', cm.getValue()); + helpers.assertCursorAt(0, 1); +}, { value: 'abcde' }); +testVim('insert', function(cm, vim, helpers) { + helpers.doKeys('i'); + eq('vim-insert', cm.getOption('keyMap')); + eq(false, cm.state.overwrite); + helpers.doKeys('<Ins>'); + eq('vim-replace', cm.getOption('keyMap')); + eq(true, cm.state.overwrite); + helpers.doKeys('<Ins>'); + eq('vim-insert', cm.getOption('keyMap')); + eq(false, cm.state.overwrite); +}); +testVim('i_backspace', function(cm, vim, helpers) { + cm.setCursor(0, 10); + helpers.doKeys('i'); + helpers.doInsertModeKeys('Backspace'); + helpers.assertCursorAt(0, 9); + eq('012345678', cm.getValue()); +}, { value: '0123456789'}); +testVim('i_overwrite_backspace', function(cm, vim, helpers) { + cm.setCursor(0, 10); + helpers.doKeys('i'); + helpers.doKeys('<Ins>'); + helpers.doInsertModeKeys('Backspace'); + helpers.assertCursorAt(Pos(0, 9, "after")); + eq('0123456789', cm.getValue()); +}, { value: '0123456789'}); +testVim('A', function(cm, vim, helpers) { + helpers.doKeys('A'); + helpers.assertCursorAt(0, lines[0].length); + eq('vim-insert', cm.getOption('keyMap')); +}); +testVim('A_visual_block', function(cm, vim, helpers) { + cm.setCursor(0, 1); + helpers.doKeys('<C-v>', '2', 'j', 'l', 'l', 'A'); + var replacement = new Array(cm.listSelections().length+1).join('hello ').split(' '); + replacement.pop(); + cm.replaceSelections(replacement); + eq('testhello\nmehello\npleahellose', cm.getValue()); + helpers.doKeys('<Esc>'); + cm.setCursor(0, 0); + helpers.doKeys('.'); + // TODO this doesn't work yet + // eq('teshellothello\nme hello hello\nplehelloahellose', cm.getValue()); +}, {value: 'test\nme\nplease'}); +testVim('I', function(cm, vim, helpers) { + cm.setCursor(0, 4); + helpers.doKeys('I'); + helpers.assertCursorAt(0, lines[0].textStart); + eq('vim-insert', cm.getOption('keyMap')); +}); +testVim('I_repeat', function(cm, vim, helpers) { + cm.setCursor(0, 1); + helpers.doKeys('3', 'I'); + cm.replaceRange('test', cm.getCursor()); + helpers.doKeys('<Esc>'); + eq('testtesttestblah', cm.getValue()); + helpers.assertCursorAt(0, 11); +}, { value: 'blah' }); +testVim('I_visual_block', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('<C-v>', '2', 'j', 'l', 'l', 'I'); + var replacement = new Array(cm.listSelections().length+1).join('hello ').split(' '); + replacement.pop(); + cm.replaceSelections(replacement); + eq('hellotest\nhellome\nhelloplease', cm.getValue()); +}, {value: 'test\nme\nplease'}); +testVim('o', function(cm, vim, helpers) { + cm.setCursor(0, 4); + helpers.doKeys('o'); + eq('word1\n\nword2', cm.getValue()); + helpers.assertCursorAt(1, 0); + eq('vim-insert', cm.getOption('keyMap')); +}, { value: 'word1\nword2' }); +testVim('o_repeat', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('3', 'o'); + cm.replaceRange('test', cm.getCursor()); + helpers.doKeys('<Esc>'); + eq('\ntest\ntest\ntest', cm.getValue()); + helpers.assertCursorAt(3, 3); +}, { value: '' }); +testVim('O', function(cm, vim, helpers) { + cm.setCursor(0, 4); + helpers.doKeys('O'); + eq('\nword1\nword2', cm.getValue()); + helpers.assertCursorAt(0, 0); + eq('vim-insert', cm.getOption('keyMap')); +}, { value: 'word1\nword2' }); +testVim('J', function(cm, vim, helpers) { + cm.setCursor(0, 4); + helpers.doKeys('J'); + var expectedValue = 'word1 word2\nword3\n word4'; + eq(expectedValue, cm.getValue()); + helpers.assertCursorAt(0, expectedValue.indexOf('word2') - 1); +}, { value: 'word1 \n word2\nword3\n word4' }); +testVim('J_repeat', function(cm, vim, helpers) { + cm.setCursor(0, 4); + helpers.doKeys('3', 'J'); + var expectedValue = 'word1 word2 word3\n word4'; + eq(expectedValue, cm.getValue()); + helpers.assertCursorAt(0, expectedValue.indexOf('word3') - 1); +}, { value: 'word1 \n word2\nword3\n word4' }); +testVim('p', function(cm, vim, helpers) { + cm.setCursor(0, 1); + helpers.getRegisterController().pushText('"', 'yank', 'abc\ndef', false); + helpers.doKeys('p'); + eq('__abc\ndef_', cm.getValue()); + helpers.assertCursorAt(1, 2); +}, { value: '___' }); +testVim('p_register', function(cm, vim, helpers) { + cm.setCursor(0, 1); + helpers.getRegisterController().getRegister('a').setText('abc\ndef', false); + helpers.doKeys('"', 'a', 'p'); + eq('__abc\ndef_', cm.getValue()); + helpers.assertCursorAt(1, 2); +}, { value: '___' }); +testVim('p_wrong_register', function(cm, vim, helpers) { + cm.setCursor(0, 1); + helpers.getRegisterController().getRegister('a').setText('abc\ndef', false); + helpers.doKeys('p'); + eq('___', cm.getValue()); + helpers.assertCursorAt(0, 1); +}, { value: '___' }); +testVim('p_line', function(cm, vim, helpers) { + cm.setCursor(0, 1); + helpers.getRegisterController().pushText('"', 'yank', ' a\nd\n', true); + helpers.doKeys('2', 'p'); + eq('___\n a\nd\n a\nd', cm.getValue()); + helpers.assertCursorAt(1, 2); +}, { value: '___' }); +testVim('p_lastline', function(cm, vim, helpers) { + cm.setCursor(0, 1); + helpers.getRegisterController().pushText('"', 'yank', ' a\nd', true); + helpers.doKeys('2', 'p'); + eq('___\n a\nd\n a\nd', cm.getValue()); + helpers.assertCursorAt(1, 2); +}, { value: '___' }); +testVim(']p_first_indent_is_smaller', function(cm, vim, helpers) { + helpers.getRegisterController().pushText('"', 'yank', ' abc\n def\n', true); + helpers.doKeys(']', 'p'); + eq(' ___\n abc\n def', cm.getValue()); +}, { value: ' ___' }); +testVim(']p_first_indent_is_larger', function(cm, vim, helpers) { + helpers.getRegisterController().pushText('"', 'yank', ' abc\n def\n', true); + helpers.doKeys(']', 'p'); + eq(' ___\n abc\ndef', cm.getValue()); +}, { value: ' ___' }); +testVim(']p_with_tab_indents', function(cm, vim, helpers) { + helpers.getRegisterController().pushText('"', 'yank', '\t\tabc\n\t\t\tdef\n', true); + helpers.doKeys(']', 'p'); + eq('\t___\n\tabc\n\t\tdef', cm.getValue()); +}, { value: '\t___', indentWithTabs: true}); +testVim(']p_with_spaces_translated_to_tabs', function(cm, vim, helpers) { + helpers.getRegisterController().pushText('"', 'yank', ' abc\n def\n', true); + helpers.doKeys(']', 'p'); + eq('\t___\n\tabc\n\t\tdef', cm.getValue()); +}, { value: '\t___', indentWithTabs: true, tabSize: 2 }); +testVim('[p', function(cm, vim, helpers) { + helpers.getRegisterController().pushText('"', 'yank', ' abc\n def\n', true); + helpers.doKeys('[', 'p'); + eq(' abc\n def\n ___', cm.getValue()); +}, { value: ' ___' }); +testVim('P', function(cm, vim, helpers) { + cm.setCursor(0, 1); + helpers.getRegisterController().pushText('"', 'yank', 'abc\ndef', false); + helpers.doKeys('P'); + eq('_abc\ndef__', cm.getValue()); + helpers.assertCursorAt(1, 3); +}, { value: '___' }); +testVim('P_line', function(cm, vim, helpers) { + cm.setCursor(0, 1); + helpers.getRegisterController().pushText('"', 'yank', ' a\nd\n', true); + helpers.doKeys('2', 'P'); + eq(' a\nd\n a\nd\n___', cm.getValue()); + helpers.assertCursorAt(0, 2); +}, { value: '___' }); +testVim('r', function(cm, vim, helpers) { + cm.setCursor(0, 1); + helpers.doKeys('3', 'r', 'u'); + eq('wuuuet\nanother', cm.getValue(),'3r failed'); + helpers.assertCursorAt(0, 3); + cm.setCursor(0, 4); + helpers.doKeys('v', 'j', 'h', 'r', '<Space>'); + eq('wuuu \n her', cm.getValue(),'Replacing selection by space-characters failed'); + cm.setValue("ox"); + helpers.doKeys('r', '<C-c>'); + eq('ox', cm.getValue()); + helpers.doKeys('r', '<Del>'); + eq('ox', cm.getValue()); + helpers.doKeys('r', '<CR>'); + eq('\nx', cm.getValue()); +}, { value: 'wordet\nanother' }); +testVim('r_visual_block', function(cm, vim, helpers) { + cm.setCursor(2, 3); + helpers.doKeys('<C-v>', 'k', 'k', 'h', 'h', 'r', 'l'); + eq('1lll\n5lll\nalllefg', cm.getValue()); + helpers.doKeys('<C-v>', 'l', 'j', 'r', '<Space>'); + eq('1 l\n5 l\nalllefg', cm.getValue()); + cm.setCursor(2, 0); + helpers.doKeys('o'); + helpers.doKeys('<Esc>'); + cm.replaceRange('\t\t', cm.getCursor()); + helpers.doKeys('<C-v>', 'h', 'h', 'r', 'r'); + eq('1 l\n5 l\nalllefg\nrrrrrrrr', cm.getValue()); +}, {value: '1234\n5678\nabcdefg'}); +testVim('R', function(cm, vim, helpers) { + cm.setCursor(0, 1); + helpers.doKeys('R'); + helpers.assertCursorAt(0, 1); + eq('vim-replace', cm.getOption('keyMap')); + is(cm.state.overwrite, 'Setting overwrite state failed'); +}); +testVim('mark', function(cm, vim, helpers) { + cm.setCursor(2, 2); + helpers.doKeys('m', 't'); + cm.setCursor(0, 0); + helpers.doKeys('`', 't'); + helpers.assertCursorAt(2, 2); + cm.setCursor(2, 0); + cm.replaceRange(' h', cm.getCursor()); + cm.setCursor(0, 0); + helpers.doKeys('\'', 't'); + helpers.assertCursorAt(2, 3); +}); +testVim('mark\'', function(cm, vim, helpers) { + cm.setCursor(2, 2); + cm.setCursor(0, 0); + helpers.doKeys('`', '\''); + helpers.assertCursorAt(2, 2); + cm.setCursor(2, 0); + cm.replaceRange(' h', cm.getCursor()); + cm.setCursor(0, 0); + helpers.doKeys('\'', '\''); + helpers.assertCursorAt(2, 3); +}); +testVim('mark.', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('O', 'testing', '<Esc>'); + cm.setCursor(3, 3); + helpers.doKeys('\'', '.'); + helpers.assertCursorAt(0, 0); + cm.setCursor(4, 4); + helpers.doKeys('`', '.'); + helpers.assertCursorAt(0, 6); +}); +testVim('jumpToMark_next', function(cm, vim, helpers) { + cm.setCursor(2, 2); + helpers.doKeys('m', 't'); + cm.setCursor(0, 0); + helpers.doKeys(']', '`'); + helpers.assertCursorAt(2, 2); + cm.setCursor(0, 0); + helpers.doKeys(']', '\''); + helpers.assertCursorAt(2, 0); +}); +testVim('jumpToMark_next_repeat', function(cm, vim, helpers) { + cm.setCursor(2, 2); + helpers.doKeys('m', 'a'); + cm.setCursor(3, 2); + helpers.doKeys('m', 'b'); + cm.setCursor(4, 2); + helpers.doKeys('m', 'c'); + cm.setCursor(0, 0); + helpers.doKeys('2', ']', '`'); + helpers.assertCursorAt(3, 2); + cm.setCursor(0, 0); + helpers.doKeys('2', ']', '\''); + helpers.assertCursorAt(3, 1); +}); +testVim('jumpToMark_next_sameline', function(cm, vim, helpers) { + cm.setCursor(2, 0); + helpers.doKeys('m', 'a'); + cm.setCursor(2, 4); + helpers.doKeys('m', 'b'); + cm.setCursor(2, 2); + helpers.doKeys(']', '`'); + helpers.assertCursorAt(2, 4); +}); +testVim('jumpToMark_next_onlyprev', function(cm, vim, helpers) { + cm.setCursor(2, 0); + helpers.doKeys('m', 'a'); + cm.setCursor(4, 0); + helpers.doKeys(']', '`'); + helpers.assertCursorAt(4, 0); +}); +testVim('jumpToMark_next_nomark', function(cm, vim, helpers) { + cm.setCursor(2, 2); + helpers.doKeys(']', '`'); + helpers.assertCursorAt(2, 2); + helpers.doKeys(']', '\''); + helpers.assertCursorAt(2, 0); +}); +testVim('jumpToMark_next_linewise_over', function(cm, vim, helpers) { + cm.setCursor(2, 2); + helpers.doKeys('m', 'a'); + cm.setCursor(3, 4); + helpers.doKeys('m', 'b'); + cm.setCursor(2, 1); + helpers.doKeys(']', '\''); + helpers.assertCursorAt(3, 1); +}); +testVim('jumpToMark_next_action', function(cm, vim, helpers) { + cm.setCursor(2, 2); + helpers.doKeys('m', 't'); + cm.setCursor(0, 0); + helpers.doKeys('d', ']', '`'); + helpers.assertCursorAt(0, 0); + var actual = cm.getLine(0); + var expected = 'pop pop 0 1 2 3 4'; + eq(actual, expected, "Deleting while jumping to the next mark failed."); +}); +testVim('jumpToMark_next_line_action', function(cm, vim, helpers) { + cm.setCursor(2, 2); + helpers.doKeys('m', 't'); + cm.setCursor(0, 0); + helpers.doKeys('d', ']', '\''); + helpers.assertCursorAt(0, 1); + var actual = cm.getLine(0); + var expected = ' (a) [b] {c} ' + eq(actual, expected, "Deleting while jumping to the next mark line failed."); +}); +testVim('jumpToMark_prev', function(cm, vim, helpers) { + cm.setCursor(2, 2); + helpers.doKeys('m', 't'); + cm.setCursor(4, 0); + helpers.doKeys('[', '`'); + helpers.assertCursorAt(2, 2); + cm.setCursor(4, 0); + helpers.doKeys('[', '\''); + helpers.assertCursorAt(2, 0); +}); +testVim('jumpToMark_prev_repeat', function(cm, vim, helpers) { + cm.setCursor(2, 2); + helpers.doKeys('m', 'a'); + cm.setCursor(3, 2); + helpers.doKeys('m', 'b'); + cm.setCursor(4, 2); + helpers.doKeys('m', 'c'); + cm.setCursor(5, 0); + helpers.doKeys('2', '[', '`'); + helpers.assertCursorAt(3, 2); + cm.setCursor(5, 0); + helpers.doKeys('2', '[', '\''); + helpers.assertCursorAt(3, 1); +}); +testVim('jumpToMark_prev_sameline', function(cm, vim, helpers) { + cm.setCursor(2, 0); + helpers.doKeys('m', 'a'); + cm.setCursor(2, 4); + helpers.doKeys('m', 'b'); + cm.setCursor(2, 2); + helpers.doKeys('[', '`'); + helpers.assertCursorAt(2, 0); +}); +testVim('jumpToMark_prev_onlynext', function(cm, vim, helpers) { + cm.setCursor(4, 4); + helpers.doKeys('m', 'a'); + cm.setCursor(2, 0); + helpers.doKeys('[', '`'); + helpers.assertCursorAt(2, 0); +}); +testVim('jumpToMark_prev_nomark', function(cm, vim, helpers) { + cm.setCursor(2, 2); + helpers.doKeys('[', '`'); + helpers.assertCursorAt(2, 2); + helpers.doKeys('[', '\''); + helpers.assertCursorAt(2, 0); +}); +testVim('jumpToMark_prev_linewise_over', function(cm, vim, helpers) { + cm.setCursor(2, 2); + helpers.doKeys('m', 'a'); + cm.setCursor(3, 4); + helpers.doKeys('m', 'b'); + cm.setCursor(3, 6); + helpers.doKeys('[', '\''); + helpers.assertCursorAt(2, 0); +}); +testVim('delmark_single', function(cm, vim, helpers) { + cm.setCursor(1, 2); + helpers.doKeys('m', 't'); + helpers.doEx('delmarks t'); + cm.setCursor(0, 0); + helpers.doKeys('`', 't'); + helpers.assertCursorAt(0, 0); +}); +testVim('delmark_range', function(cm, vim, helpers) { + cm.setCursor(1, 2); + helpers.doKeys('m', 'a'); + cm.setCursor(2, 2); + helpers.doKeys('m', 'b'); + cm.setCursor(3, 2); + helpers.doKeys('m', 'c'); + cm.setCursor(4, 2); + helpers.doKeys('m', 'd'); + cm.setCursor(5, 2); + helpers.doKeys('m', 'e'); + helpers.doEx('delmarks b-d'); + cm.setCursor(0, 0); + helpers.doKeys('`', 'a'); + helpers.assertCursorAt(1, 2); + helpers.doKeys('`', 'b'); + helpers.assertCursorAt(1, 2); + helpers.doKeys('`', 'c'); + helpers.assertCursorAt(1, 2); + helpers.doKeys('`', 'd'); + helpers.assertCursorAt(1, 2); + helpers.doKeys('`', 'e'); + helpers.assertCursorAt(5, 2); +}); +testVim('delmark_multi', function(cm, vim, helpers) { + cm.setCursor(1, 2); + helpers.doKeys('m', 'a'); + cm.setCursor(2, 2); + helpers.doKeys('m', 'b'); + cm.setCursor(3, 2); + helpers.doKeys('m', 'c'); + cm.setCursor(4, 2); + helpers.doKeys('m', 'd'); + cm.setCursor(5, 2); + helpers.doKeys('m', 'e'); + helpers.doEx('delmarks bcd'); + cm.setCursor(0, 0); + helpers.doKeys('`', 'a'); + helpers.assertCursorAt(1, 2); + helpers.doKeys('`', 'b'); + helpers.assertCursorAt(1, 2); + helpers.doKeys('`', 'c'); + helpers.assertCursorAt(1, 2); + helpers.doKeys('`', 'd'); + helpers.assertCursorAt(1, 2); + helpers.doKeys('`', 'e'); + helpers.assertCursorAt(5, 2); +}); +testVim('delmark_multi_space', function(cm, vim, helpers) { + cm.setCursor(1, 2); + helpers.doKeys('m', 'a'); + cm.setCursor(2, 2); + helpers.doKeys('m', 'b'); + cm.setCursor(3, 2); + helpers.doKeys('m', 'c'); + cm.setCursor(4, 2); + helpers.doKeys('m', 'd'); + cm.setCursor(5, 2); + helpers.doKeys('m', 'e'); + helpers.doEx('delmarks b c d'); + cm.setCursor(0, 0); + helpers.doKeys('`', 'a'); + helpers.assertCursorAt(1, 2); + helpers.doKeys('`', 'b'); + helpers.assertCursorAt(1, 2); + helpers.doKeys('`', 'c'); + helpers.assertCursorAt(1, 2); + helpers.doKeys('`', 'd'); + helpers.assertCursorAt(1, 2); + helpers.doKeys('`', 'e'); + helpers.assertCursorAt(5, 2); +}); +testVim('delmark_all', function(cm, vim, helpers) { + cm.setCursor(1, 2); + helpers.doKeys('m', 'a'); + cm.setCursor(2, 2); + helpers.doKeys('m', 'b'); + cm.setCursor(3, 2); + helpers.doKeys('m', 'c'); + cm.setCursor(4, 2); + helpers.doKeys('m', 'd'); + cm.setCursor(5, 2); + helpers.doKeys('m', 'e'); + helpers.doEx('delmarks a b-de'); + cm.setCursor(0, 0); + helpers.doKeys('`', 'a'); + helpers.assertCursorAt(0, 0); + helpers.doKeys('`', 'b'); + helpers.assertCursorAt(0, 0); + helpers.doKeys('`', 'c'); + helpers.assertCursorAt(0, 0); + helpers.doKeys('`', 'd'); + helpers.assertCursorAt(0, 0); + helpers.doKeys('`', 'e'); + helpers.assertCursorAt(0, 0); +}); +testVim('visual', function(cm, vim, helpers) { + helpers.doKeys('l', 'v', 'l', 'l'); + helpers.assertCursorAt(0, 4); + eqCursorPos(makeCursor(0, 1), cm.getCursor('anchor')); + helpers.doKeys('d'); + eq('15', cm.getValue()); +}, { value: '12345' }); +testVim('visual_yank', function(cm, vim, helpers) { + helpers.doKeys('v', '3', 'l', 'y'); + helpers.assertCursorAt(0, 0); + helpers.doKeys('p'); + eq('aa te test for yank', cm.getValue()); +}, { value: 'a test for yank' }) +testVim('visual_w', function(cm, vim, helpers) { + helpers.doKeys('v', 'w'); + eq(cm.getSelection(), 'motion t'); +}, { value: 'motion test'}); +testVim('visual_initial_selection', function(cm, vim, helpers) { + cm.setCursor(0, 1); + helpers.doKeys('v'); + cm.getSelection('n'); +}, { value: 'init'}); +testVim('visual_crossover_left', function(cm, vim, helpers) { + cm.setCursor(0, 2); + helpers.doKeys('v', 'l', 'h', 'h'); + cm.getSelection('ro'); +}, { value: 'cross'}); +testVim('visual_crossover_left', function(cm, vim, helpers) { + cm.setCursor(0, 2); + helpers.doKeys('v', 'h', 'l', 'l'); + cm.getSelection('os'); +}, { value: 'cross'}); +testVim('visual_crossover_up', function(cm, vim, helpers) { + cm.setCursor(3, 2); + helpers.doKeys('v', 'j', 'k', 'k'); + eqCursorPos(Pos(2, 2), cm.getCursor('head')); + eqCursorPos(Pos(3, 3), cm.getCursor('anchor')); + helpers.doKeys('k'); + eqCursorPos(Pos(1, 2), cm.getCursor('head')); + eqCursorPos(Pos(3, 3), cm.getCursor('anchor')); +}, { value: 'cross\ncross\ncross\ncross\ncross\n'}); +testVim('visual_crossover_down', function(cm, vim, helpers) { + cm.setCursor(1, 2); + helpers.doKeys('v', 'k', 'j', 'j'); + eqCursorPos(Pos(2, 3), cm.getCursor('head')); + eqCursorPos(Pos(1, 2), cm.getCursor('anchor')); + helpers.doKeys('j'); + eqCursorPos(Pos(3, 3), cm.getCursor('head')); + eqCursorPos(Pos(1, 2), cm.getCursor('anchor')); +}, { value: 'cross\ncross\ncross\ncross\ncross\n'}); +testVim('visual_exit', function(cm, vim, helpers) { + helpers.doKeys('<C-v>', 'l', 'j', 'j', '<Esc>'); + eqCursorPos(cm.getCursor('anchor'), cm.getCursor('head')); + eq(vim.visualMode, false); +}, { value: 'hello\nworld\nfoo' }); +testVim('visual_line', function(cm, vim, helpers) { + helpers.doKeys('l', 'V', 'l', 'j', 'j', 'd'); + eq(' 4\n 5', cm.getValue()); +}, { value: ' 1\n 2\n 3\n 4\n 5' }); +testVim('visual_block_move_to_eol', function(cm, vim, helpers) { + // moveToEol should move all block cursors to end of line + cm.setCursor(0, 0); + helpers.doKeys('<C-v>', 'G', '$'); + var selections = cm.getSelections().join(); + eq('123,45,6', selections); + // Checks that with cursor at Infinity, finding words backwards still works. + helpers.doKeys('2', 'k', 'b'); + selections = cm.getSelections().join(); + eq('1', selections); +}, {value: '123\n45\n6'}); +testVim('visual_block_different_line_lengths', function(cm, vim, helpers) { + // test the block selection with lines of different length + // i.e. extending the selection + // till the end of the longest line. + helpers.doKeys('<C-v>', 'l', 'j', 'j', '6', 'l', 'd'); + helpers.doKeys('d', 'd', 'd', 'd'); + eq('', cm.getValue()); +}, {value: '1234\n5678\nabcdefg'}); +testVim('visual_block_truncate_on_short_line', function(cm, vim, helpers) { + // check for left side selection in case + // of moving up to a shorter line. + cm.replaceRange('', cm.getCursor()); + cm.setCursor(3, 4); + helpers.doKeys('<C-v>', 'l', 'k', 'k', 'd'); + eq('hello world\n{\ntis\nsa!', cm.getValue()); +}, {value: 'hello world\n{\nthis is\nsparta!'}); +testVim('visual_block_corners', function(cm, vim, helpers) { + cm.setCursor(1, 2); + helpers.doKeys('<C-v>', '2', 'l', 'k'); + // circle around the anchor + // and check the selections + var selections = cm.getSelections(); + eq('345891', selections.join('')); + helpers.doKeys('4', 'h'); + selections = cm.getSelections(); + eq('123678', selections.join('')); + helpers.doKeys('j', 'j'); + selections = cm.getSelections(); + eq('678abc', selections.join('')); + helpers.doKeys('4', 'l'); + selections = cm.getSelections(); + eq('891cde', selections.join('')); +}, {value: '12345\n67891\nabcde'}); +testVim('visual_block_mode_switch', function(cm, vim, helpers) { + // switch between visual modes + cm.setCursor(1, 1); + // blockwise to characterwise visual + helpers.doKeys('<C-v>', 'j', 'l', 'v'); + var selections = cm.getSelections(); + eq('7891\nabc', selections.join('')); + // characterwise to blockwise + helpers.doKeys('<C-v>'); + selections = cm.getSelections(); + eq('78bc', selections.join('')); + // blockwise to linewise visual + helpers.doKeys('V'); + selections = cm.getSelections(); + eq('67891\nabcde', selections.join('')); +}, {value: '12345\n67891\nabcde'}); +testVim('visual_block_crossing_short_line', function(cm, vim, helpers) { + // visual block with long and short lines + cm.setCursor(0, 3); + helpers.doKeys('<C-v>', 'j', 'j', 'j'); + var selections = cm.getSelections().join(); + eq('4,,d,b', selections); + helpers.doKeys('3', 'k'); + selections = cm.getSelections().join(); + eq('4', selections); + helpers.doKeys('5', 'j', 'k'); + selections = cm.getSelections().join(""); + eq(10, selections.length); +}, {value: '123456\n78\nabcdefg\nfoobar\n}\n'}); +testVim('visual_block_curPos_on_exit', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('<C-v>', '3' , 'l', '<Esc>'); + eqCursorPos(makeCursor(0, 3), cm.getCursor()); + helpers.doKeys('h', '<C-v>', '2' , 'j' ,'3' , 'l'); + eq(cm.getSelections().join(), "3456,,cdef"); + helpers.doKeys('4' , 'h'); + eq(cm.getSelections().join(), "23,8,bc"); + helpers.doKeys('2' , 'l'); + eq(cm.getSelections().join(), "34,,cd"); +}, {value: '123456\n78\nabcdefg\nfoobar'}); + +testVim('visual_marks', function(cm, vim, helpers) { + helpers.doKeys('l', 'v', 'l', 'l', 'j', 'j', 'v'); + // Test visual mode marks + cm.setCursor(2, 1); + helpers.doKeys('\'', '<'); + helpers.assertCursorAt(0, 1); + helpers.doKeys('\'', '>'); + helpers.assertCursorAt(2, 0); +}); +testVim('visual_join', function(cm, vim, helpers) { + helpers.doKeys('l', 'V', 'l', 'j', 'j', 'J'); + eq(' 1 2 3\n 4\n 5', cm.getValue()); + is(!vim.visualMode); +}, { value: ' 1\n 2\n 3\n 4\n 5' }); +testVim('visual_join_2', function(cm, vim, helpers) { + helpers.doKeys('G', 'V', 'g', 'g', 'J'); + eq('1 2 3 4 5 6 ', cm.getValue()); + is(!vim.visualMode); +}, { value: '1\n2\n3\n4\n5\n6\n'}); +testVim('visual_blank', function(cm, vim, helpers) { + helpers.doKeys('v', 'k'); + eq(vim.visualMode, true); +}, { value: '\n' }); +testVim('reselect_visual', function(cm, vim, helpers) { + helpers.doKeys('l', 'v', 'l', 'l', 'l', 'y', 'g', 'v'); + helpers.assertCursorAt(0, 5); + eqCursorPos(makeCursor(0, 1), cm.getCursor('anchor')); + helpers.doKeys('v'); + cm.setCursor(1, 0); + helpers.doKeys('v', 'l', 'l', 'p'); + eq('123456\n2345\nbar', cm.getValue()); + cm.setCursor(0, 0); + helpers.doKeys('g', 'v'); + // here the fake cursor is at (1, 3) + helpers.assertCursorAt(1, 4); + eqCursorPos(makeCursor(1, 0), cm.getCursor('anchor')); + helpers.doKeys('v'); + cm.setCursor(2, 0); + helpers.doKeys('v', 'l', 'l', 'g', 'v'); + helpers.assertCursorAt(1, 4); + eqCursorPos(makeCursor(1, 0), cm.getCursor('anchor')); + helpers.doKeys('g', 'v'); + helpers.assertCursorAt(2, 3); + eqCursorPos(makeCursor(2, 0), cm.getCursor('anchor')); + eq('123456\n2345\nbar', cm.getValue()); +}, { value: '123456\nfoo\nbar' }); +testVim('reselect_visual_line', function(cm, vim, helpers) { + helpers.doKeys('l', 'V', 'j', 'j', 'V', 'g', 'v', 'd'); + eq('foo\nand\nbar', cm.getValue()); + cm.setCursor(1, 0); + helpers.doKeys('V', 'y', 'j'); + helpers.doKeys('V', 'p' , 'g', 'v', 'd'); + eq('foo\nand', cm.getValue()); +}, { value: 'hello\nthis\nis\nfoo\nand\nbar' }); +testVim('reselect_visual_block', function(cm, vim, helpers) { + cm.setCursor(1, 2); + helpers.doKeys('<C-v>', 'k', 'h', '<C-v>'); + cm.setCursor(2, 1); + helpers.doKeys('v', 'l', 'g', 'v'); + eqCursorPos(Pos(1, 2), vim.sel.anchor); + eqCursorPos(Pos(0, 1), vim.sel.head); + // Ensure selection is done with visual block mode rather than one + // continuous range. + eq(cm.getSelections().join(''), '23oo') + helpers.doKeys('g', 'v'); + eqCursorPos(Pos(2, 1), vim.sel.anchor); + eqCursorPos(Pos(2, 2), vim.sel.head); + helpers.doKeys('<Esc>'); + // Ensure selection of deleted range + cm.setCursor(1, 1); + helpers.doKeys('v', '<C-v>', 'j', 'd', 'g', 'v'); + eq(cm.getSelections().join(''), 'or'); +}, { value: '123456\nfoo\nbar' }); +testVim('s_normal', function(cm, vim, helpers) { + cm.setCursor(0, 1); + helpers.doKeys('s'); + helpers.doKeys('<Esc>'); + eq('ac', cm.getValue()); +}, { value: 'abc'}); +testVim('s_visual', function(cm, vim, helpers) { + cm.setCursor(0, 1); + helpers.doKeys('v', 's'); + helpers.doKeys('<Esc>'); + helpers.assertCursorAt(0, 0); + eq('ac', cm.getValue()); +}, { value: 'abc'}); +testVim('o_visual', function(cm, vim, helpers) { + cm.setCursor(0,0); + helpers.doKeys('v','l','l','l','o'); + helpers.assertCursorAt(0,0); + helpers.doKeys('v','v','j','j','j','o'); + helpers.assertCursorAt(0,0); + helpers.doKeys('O'); + helpers.doKeys('l','l') + helpers.assertCursorAt(3, 3); + helpers.doKeys('d'); + eq('p',cm.getValue()); +}, { value: 'abcd\nefgh\nijkl\nmnop'}); +testVim('o_visual_block', function(cm, vim, helpers) { + cm.setCursor(0, 1); + helpers.doKeys('<C-v>','3','j','l','l', 'o'); + eqCursorPos(Pos(3, 3), vim.sel.anchor); + eqCursorPos(Pos(0, 1), vim.sel.head); + helpers.doKeys('O'); + eqCursorPos(Pos(3, 1), vim.sel.anchor); + eqCursorPos(Pos(0, 3), vim.sel.head); + helpers.doKeys('o'); + eqCursorPos(Pos(0, 3), vim.sel.anchor); + eqCursorPos(Pos(3, 1), vim.sel.head); +}, { value: 'abcd\nefgh\nijkl\nmnop'}); +testVim('changeCase_visual', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('v', 'l', 'l'); + helpers.doKeys('U'); + helpers.assertCursorAt(0, 0); + helpers.doKeys('v', 'l', 'l'); + helpers.doKeys('u'); + helpers.assertCursorAt(0, 0); + helpers.doKeys('l', 'l', 'l', '.'); + helpers.assertCursorAt(0, 3); + cm.setCursor(0, 0); + helpers.doKeys('q', 'a', 'v', 'j', 'U', 'q'); + helpers.assertCursorAt(0, 0); + helpers.doKeys('j', '@', 'a'); + helpers.assertCursorAt(1, 0); + cm.setCursor(3, 0); + helpers.doKeys('V', 'U', 'j', '.'); + eq('ABCDEF\nGHIJKL\nMnopq\nSHORT LINE\nLONG LINE OF TEXT', cm.getValue()); +}, { value: 'abcdef\nghijkl\nmnopq\nshort line\nlong line of text'}); +testVim('changeCase_visual_block', function(cm, vim, helpers) { + cm.setCursor(2, 1); + helpers.doKeys('<C-v>', 'k', 'k', 'h', 'U'); + eq('ABcdef\nGHijkl\nMNopq\nfoo', cm.getValue()); + cm.setCursor(0, 2); + helpers.doKeys('.'); + eq('ABCDef\nGHIJkl\nMNOPq\nfoo', cm.getValue()); + // check when last line is shorter. + cm.setCursor(2, 2); + helpers.doKeys('.'); + eq('ABCDef\nGHIJkl\nMNOPq\nfoO', cm.getValue()); +}, { value: 'abcdef\nghijkl\nmnopq\nfoo'}); +testVim('visual_paste', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('v', 'l', 'l', 'y'); + helpers.assertCursorAt(0, 0); + helpers.doKeys('3', 'l', 'j', 'v', 'l', 'p'); + helpers.assertCursorAt(1, 5); + eq('this is a\nunithitest for visual paste', cm.getValue()); + cm.setCursor(0, 0); + // in case of pasting whole line + helpers.doKeys('y', 'y'); + cm.setCursor(1, 6); + helpers.doKeys('v', 'l', 'l', 'l', 'p'); + helpers.assertCursorAt(2, 0); + eq('this is a\nunithi\nthis is a\n for visual paste', cm.getValue()); +}, { value: 'this is a\nunit test for visual paste'}); + +// This checks the contents of the register used to paste the text +testVim('v_paste_from_register', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('"', 'a', 'y', 'w'); + cm.setCursor(1, 0); + helpers.doKeys('v', 'p'); + cm.openDialog = helpers.fakeOpenDialog('registers'); + cm.openNotification = helpers.fakeOpenNotification(function(text) { + is(/a\s+register/.test(text)); + }); +}, { value: 'register contents\nare not erased'}); +testVim('S_normal', function(cm, vim, helpers) { + cm.setCursor(0, 1); + helpers.doKeys('j', 'S'); + helpers.doKeys('<Esc>'); + helpers.assertCursorAt(1, 1); + eq('aa{\n \ncc', cm.getValue()); + helpers.doKeys('j', 'S'); + eq('aa{\n \n ', cm.getValue()); + helpers.assertCursorAt(2, 2); + helpers.doKeys('<Esc>'); + helpers.doKeys('d', 'd', 'd', 'd'); + helpers.assertCursorAt(0, 0); + helpers.doKeys('S'); + is(vim.insertMode); + eq('', cm.getValue()); +}, { value: 'aa{\nbb\ncc'}); +testVim('blockwise_paste', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('<C-v>', '3', 'j', 'l', 'y'); + cm.setCursor(0, 2); + // paste one char after the current cursor position + helpers.doKeys('p'); + eq('helhelo\nworwold\nfoofo\nbarba', cm.getValue()); + cm.setCursor(0, 0); + helpers.doKeys('v', '4', 'l', 'y'); + cm.setCursor(0, 0); + helpers.doKeys('<C-v>', '3', 'j', 'p'); + eq('helheelhelo\norwold\noofo\narba', cm.getValue()); +}, { value: 'hello\nworld\nfoo\nbar'}); +testVim('blockwise_paste_long/short_line', function(cm, vim, helpers) { + // extend short lines in case of different line lengths. + cm.setCursor(0, 0); + helpers.doKeys('<C-v>', 'j', 'j', 'y'); + cm.setCursor(0, 3); + helpers.doKeys('p'); + eq('hellho\nfoo f\nbar b', cm.getValue()); +}, { value: 'hello\nfoo\nbar'}); +testVim('blockwise_paste_cut_paste', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('<C-v>', '2', 'j', 'x'); + cm.setCursor(0, 0); + helpers.doKeys('P'); + eq('cut\nand\npaste\nme', cm.getValue()); +}, { value: 'cut\nand\npaste\nme'}); +testVim('blockwise_paste_from_register', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('<C-v>', '2', 'j', '"', 'a', 'y'); + cm.setCursor(0, 3); + helpers.doKeys('"', 'a', 'p'); + eq('foobfar\nhellho\nworlwd', cm.getValue()); +}, { value: 'foobar\nhello\nworld'}); +testVim('blockwise_paste_last_line', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('<C-v>', '2', 'j', 'l', 'y'); + cm.setCursor(3, 0); + helpers.doKeys('p'); + eq('cut\nand\npaste\nmcue\n an\n pa', cm.getValue()); +}, { value: 'cut\nand\npaste\nme'}); + +testVim('S_visual', function(cm, vim, helpers) { + cm.setCursor(0, 1); + helpers.doKeys('v', 'j', 'S'); + helpers.doKeys('<Esc>'); + helpers.assertCursorAt(0, 0); + eq('\ncc', cm.getValue()); +}, { value: 'aa\nbb\ncc'}); + +testVim('d_/', function(cm, vim, helpers) { + cm.openDialog = helpers.fakeOpenDialog('match'); + helpers.doKeys('2', 'd', '/'); + helpers.assertCursorAt(0, 0); + eq('match \n next', cm.getValue()); + cm.openDialog = helpers.fakeOpenDialog('2'); + helpers.doKeys('d', ':'); + // TODO eq(' next', cm.getValue()); +}, { value: 'text match match \n next' }); +testVim('/ and n/N', function(cm, vim, helpers) { + cm.openDialog = helpers.fakeOpenDialog('match'); + helpers.doKeys('/'); + helpers.assertCursorAt(0, 11); + helpers.doKeys('n'); + helpers.assertCursorAt(1, 6); + helpers.doKeys('N'); + helpers.assertCursorAt(0, 11); + + cm.setCursor(0, 0); + helpers.doKeys('2', '/'); + helpers.assertCursorAt(1, 6); +}, { value: 'match nope match \n nope Match' }); +testVim('/_case', function(cm, vim, helpers) { + cm.openDialog = helpers.fakeOpenDialog('Match'); + helpers.doKeys('/'); + helpers.assertCursorAt(1, 6); +}, { value: 'match nope match \n nope Match' }); +testVim('/_2_pcre', function(cm, vim, helpers) { + CodeMirror.Vim.setOption('pcre', true); + cm.openDialog = helpers.fakeOpenDialog('(word){2}'); + helpers.doKeys('/'); + helpers.assertCursorAt(1, 9); + helpers.doKeys('n'); + helpers.assertCursorAt(2, 1); +}, { value: 'word\n another wordword\n wordwordword\n' }); +testVim('/_2_nopcre', function(cm, vim, helpers) { + CodeMirror.Vim.setOption('pcre', false); + cm.openDialog = helpers.fakeOpenDialog('\\(word\\)\\{2}'); + helpers.doKeys('/'); + helpers.assertCursorAt(1, 9); + helpers.doKeys('n'); + helpers.assertCursorAt(2, 1); +}, { value: 'word\n another wordword\n wordwordword\n' }); +testVim('/_nongreedy', function(cm, vim, helpers) { + cm.openDialog = helpers.fakeOpenDialog('aa'); + helpers.doKeys('/'); + helpers.assertCursorAt(0, 4); + helpers.doKeys('n'); + helpers.assertCursorAt(1, 3); + helpers.doKeys('n'); + helpers.assertCursorAt(0, 0); +}, { value: 'aaa aa \n a aa'}); +testVim('?_nongreedy', function(cm, vim, helpers) { + cm.openDialog = helpers.fakeOpenDialog('aa'); + helpers.doKeys('?'); + helpers.assertCursorAt(1, 3); + helpers.doKeys('n'); + helpers.assertCursorAt(0, 4); + helpers.doKeys('n'); + helpers.assertCursorAt(0, 0); +}, { value: 'aaa aa \n a aa'}); +testVim('/_greedy', function(cm, vim, helpers) { + cm.openDialog = helpers.fakeOpenDialog('a+'); + helpers.doKeys('/'); + helpers.assertCursorAt(0, 4); + helpers.doKeys('n'); + helpers.assertCursorAt(1, 1); + helpers.doKeys('n'); + helpers.assertCursorAt(1, 3); + helpers.doKeys('n'); + helpers.assertCursorAt(0, 0); +}, { value: 'aaa aa \n a aa'}); +testVim('?_greedy', function(cm, vim, helpers) { + cm.openDialog = helpers.fakeOpenDialog('a+'); + helpers.doKeys('?'); + helpers.assertCursorAt(1, 3); + helpers.doKeys('n'); + helpers.assertCursorAt(1, 1); + helpers.doKeys('n'); + helpers.assertCursorAt(0, 4); + helpers.doKeys('n'); + helpers.assertCursorAt(0, 0); +}, { value: 'aaa aa \n a aa'}); +testVim('/_greedy_0_or_more', function(cm, vim, helpers) { + cm.openDialog = helpers.fakeOpenDialog('a*'); + helpers.doKeys('/'); + helpers.assertCursorAt(0, 3); + helpers.doKeys('n'); + helpers.assertCursorAt(0, 4); + helpers.doKeys('n'); + helpers.assertCursorAt(0, 5); + helpers.doKeys('n'); + helpers.assertCursorAt(1, 0); + helpers.doKeys('n'); + helpers.assertCursorAt(1, 1); + helpers.doKeys('n'); + helpers.assertCursorAt(0, 0); +}, { value: 'aaa aa\n aa'}); +testVim('?_greedy_0_or_more', function(cm, vim, helpers) { + cm.openDialog = helpers.fakeOpenDialog('a*'); + helpers.doKeys('?'); + helpers.assertCursorAt(1, 1); + helpers.doKeys('n'); + helpers.assertCursorAt(0, 5); + helpers.doKeys('n'); + helpers.assertCursorAt(0, 3); + helpers.doKeys('n'); + helpers.assertCursorAt(0, 0); +}, { value: 'aaa aa\n aa'}); +testVim('? and n/N', function(cm, vim, helpers) { + cm.openDialog = helpers.fakeOpenDialog('match'); + helpers.doKeys('?'); + helpers.assertCursorAt(1, 6); + helpers.doKeys('n'); + helpers.assertCursorAt(0, 11); + helpers.doKeys('N'); + helpers.assertCursorAt(1, 6); + + cm.setCursor(0, 0); + helpers.doKeys('2', '?'); + helpers.assertCursorAt(0, 11); +}, { value: 'match nope match \n nope Match' }); +testVim('*', function(cm, vim, helpers) { + cm.setCursor(0, 9); + helpers.doKeys('*'); + helpers.assertCursorAt(0, 22); + + cm.setCursor(0, 9); + helpers.doKeys('2', '*'); + helpers.assertCursorAt(1, 8); +}, { value: 'nomatch match nomatch match \nnomatch Match' }); +testVim('*_no_word', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('*'); + helpers.assertCursorAt(0, 0); +}, { value: ' \n match \n' }); +testVim('*_symbol', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('*'); + helpers.assertCursorAt(1, 0); +}, { value: ' /}\n/} match \n' }); +testVim('#', function(cm, vim, helpers) { + cm.setCursor(0, 9); + helpers.doKeys('#'); + helpers.assertCursorAt(1, 8); + + cm.setCursor(0, 9); + helpers.doKeys('2', '#'); + helpers.assertCursorAt(0, 22); +}, { value: 'nomatch match nomatch match \nnomatch Match' }); +testVim('*_seek', function(cm, vim, helpers) { + // Should skip over space and symbols. + cm.setCursor(0, 3); + helpers.doKeys('*'); + helpers.assertCursorAt(0, 22); +}, { value: ' := match nomatch match \nnomatch Match' }); +testVim('#', function(cm, vim, helpers) { + // Should skip over space and symbols. + cm.setCursor(0, 3); + helpers.doKeys('#'); + helpers.assertCursorAt(1, 8); +}, { value: ' := match nomatch match \nnomatch Match' }); +testVim('g*', function(cm, vim, helpers) { + cm.setCursor(0, 8); + helpers.doKeys('g', '*'); + helpers.assertCursorAt(0, 18); + cm.setCursor(0, 8); + helpers.doKeys('3', 'g', '*'); + helpers.assertCursorAt(1, 8); +}, { value: 'matches match alsoMatch\nmatchme matching' }); +testVim('g#', function(cm, vim, helpers) { + cm.setCursor(0, 8); + helpers.doKeys('g', '#'); + helpers.assertCursorAt(0, 0); + cm.setCursor(0, 8); + helpers.doKeys('3', 'g', '#'); + helpers.assertCursorAt(1, 0); +}, { value: 'matches match alsoMatch\nmatchme matching' }); +testVim('macro_insert', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('q', 'a', '0', 'i'); + cm.replaceRange('foo', cm.getCursor()); + helpers.doKeys('<Esc>'); + helpers.doKeys('q', '@', 'a'); + eq('foofoo', cm.getValue()); +}, { value: ''}); +testVim('macro_insert_repeat', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('q', 'a', '$', 'a'); + cm.replaceRange('larry.', cm.getCursor()); + helpers.doKeys('<Esc>'); + helpers.doKeys('a'); + cm.replaceRange('curly.', cm.getCursor()); + helpers.doKeys('<Esc>'); + helpers.doKeys('q'); + helpers.doKeys('a'); + cm.replaceRange('moe.', cm.getCursor()); + helpers.doKeys('<Esc>'); + helpers.doKeys('@', 'a'); + // At this point, the most recent edit should be the 2nd insert change + // inside the macro, i.e. "curly.". + helpers.doKeys('.'); + eq('larry.curly.moe.larry.curly.curly.', cm.getValue()); +}, { value: ''}); +testVim('macro_space', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('<Space>', '<Space>'); + helpers.assertCursorAt(0, 2); + helpers.doKeys('q', 'a', '<Space>', '<Space>', 'q'); + helpers.assertCursorAt(0, 4); + helpers.doKeys('@', 'a'); + helpers.assertCursorAt(0, 6); + helpers.doKeys('@', 'a'); + helpers.assertCursorAt(0, 8); +}, { value: 'one line of text.'}); +testVim('macro_t_search', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('q', 'a', 't', 'e', 'q'); + helpers.assertCursorAt(0, 1); + helpers.doKeys('l', '@', 'a'); + helpers.assertCursorAt(0, 6); + helpers.doKeys('l', ';'); + helpers.assertCursorAt(0, 12); +}, { value: 'one line of text.'}); +testVim('macro_f_search', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('q', 'b', 'f', 'e', 'q'); + helpers.assertCursorAt(0, 2); + helpers.doKeys('@', 'b'); + helpers.assertCursorAt(0, 7); + helpers.doKeys(';'); + helpers.assertCursorAt(0, 13); +}, { value: 'one line of text.'}); +testVim('macro_slash_search', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('q', 'c'); + cm.openDialog = helpers.fakeOpenDialog('e'); + helpers.doKeys('/', 'q'); + helpers.assertCursorAt(0, 2); + helpers.doKeys('@', 'c'); + helpers.assertCursorAt(0, 7); + helpers.doKeys('n'); + helpers.assertCursorAt(0, 13); +}, { value: 'one line of text.'}); +testVim('macro_multislash_search', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('q', 'd'); + cm.openDialog = helpers.fakeOpenDialog('e'); + helpers.doKeys('/'); + cm.openDialog = helpers.fakeOpenDialog('t'); + helpers.doKeys('/', 'q'); + helpers.assertCursorAt(0, 12); + helpers.doKeys('@', 'd'); + helpers.assertCursorAt(0, 15); +}, { value: 'one line of text to rule them all.'}); +testVim('macro_last_ex_command_register', function (cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doEx('s/a/b'); + helpers.doKeys('2', '@', ':'); + eq('bbbaa', cm.getValue()); + helpers.assertCursorAt(0, 2); +}, { value: 'aaaaa'}); +testVim('macro_parens', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('q', 'z', 'i'); + cm.replaceRange('(', cm.getCursor()); + helpers.doKeys('<Esc>'); + helpers.doKeys('e', 'a'); + cm.replaceRange(')', cm.getCursor()); + helpers.doKeys('<Esc>'); + helpers.doKeys('q'); + helpers.doKeys('w', '@', 'z'); + helpers.doKeys('w', '@', 'z'); + eq('(see) (spot) (run)', cm.getValue()); +}, { value: 'see spot run'}); +testVim('macro_overwrite', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('q', 'z', '0', 'i'); + cm.replaceRange('I ', cm.getCursor()); + helpers.doKeys('<Esc>'); + helpers.doKeys('q'); + helpers.doKeys('e'); + // Now replace the macro with something else. + helpers.doKeys('q', 'z', 'a'); + cm.replaceRange('.', cm.getCursor()); + helpers.doKeys('<Esc>'); + helpers.doKeys('q'); + helpers.doKeys('e', '@', 'z'); + helpers.doKeys('e', '@', 'z'); + eq('I see. spot. run.', cm.getValue()); +}, { value: 'see spot run'}); +testVim('macro_search_f', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('q', 'a', 'f', ' '); + helpers.assertCursorAt(0,3); + helpers.doKeys('q', '0'); + helpers.assertCursorAt(0,0); + helpers.doKeys('@', 'a'); + helpers.assertCursorAt(0,3); +}, { value: 'The quick brown fox jumped over the lazy dog.'}); +testVim('macro_search_2f', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('q', 'a', '2', 'f', ' '); + helpers.assertCursorAt(0,9); + helpers.doKeys('q', '0'); + helpers.assertCursorAt(0,0); + helpers.doKeys('@', 'a'); + helpers.assertCursorAt(0,9); +}, { value: 'The quick brown fox jumped over the lazy dog.'}); +testVim('macro_yank_tick', function(cm, vim, helpers) { + cm.setCursor(0, 0); + // Start recording a macro into the \' register. + helpers.doKeys('q', '\''); + helpers.doKeys('y', '<Right>', '<Right>', '<Right>', '<Right>', 'p'); + helpers.assertCursorAt(0,4); + eq('the tex parrot', cm.getValue()); +}, { value: 'the ex parrot'}); +testVim('yank_register', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('"', 'a', 'y', 'y'); + helpers.doKeys('j', '"', 'b', 'y', 'y'); + cm.openDialog = helpers.fakeOpenDialog('registers'); + cm.openNotification = helpers.fakeOpenNotification(function(text) { + is(/a\s+foo/.test(text)); + is(/b\s+bar/.test(text)); + }); + helpers.doKeys(':'); +}, { value: 'foo\nbar'}); +testVim('yank_visual_block', function(cm, vim, helpers) { + cm.setCursor(0, 1); + helpers.doKeys('<C-v>', 'l', 'j', '"', 'a', 'y'); + cm.openNotification = helpers.fakeOpenNotification(function(text) { + is(/a\s+oo\nar/.test(text)); + }); + helpers.doKeys(':'); +}, { value: 'foo\nbar'}); +testVim('yank_append_line_to_line_register', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('"', 'a', 'y', 'y'); + helpers.doKeys('j', '"', 'A', 'y', 'y'); + cm.openDialog = helpers.fakeOpenDialog('registers'); + cm.openNotification = helpers.fakeOpenNotification(function(text) { + is(/a\s+foo\nbar/.test(text)); + is(/"\s+foo\nbar/.test(text)); + }); + helpers.doKeys(':'); +}, { value: 'foo\nbar'}); +testVim('yank_append_word_to_word_register', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('"', 'a', 'y', 'w'); + helpers.doKeys('j', '"', 'A', 'y', 'w'); + cm.openDialog = helpers.fakeOpenDialog('registers'); + cm.openNotification = helpers.fakeOpenNotification(function(text) { + is(/a\s+foobar/.test(text)); + is(/"\s+foobar/.test(text)); + }); + helpers.doKeys(':'); +}, { value: 'foo\nbar'}); +testVim('yank_append_line_to_word_register', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('"', 'a', 'y', 'w'); + helpers.doKeys('j', '"', 'A', 'y', 'y'); + cm.openDialog = helpers.fakeOpenDialog('registers'); + cm.openNotification = helpers.fakeOpenNotification(function(text) { + is(/a\s+foo\nbar/.test(text)); + is(/"\s+foo\nbar/.test(text)); + }); + helpers.doKeys(':'); +}, { value: 'foo\nbar'}); +testVim('yank_append_word_to_line_register', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('"', 'a', 'y', 'y'); + helpers.doKeys('j', '"', 'A', 'y', 'w'); + cm.openDialog = helpers.fakeOpenDialog('registers'); + cm.openNotification = helpers.fakeOpenNotification(function(text) { + is(/a\s+foo\nbar/.test(text)); + is(/"\s+foo\nbar/.test(text)); + }); + helpers.doKeys(':'); +}, { value: 'foo\nbar'}); +testVim('macro_register', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('q', 'a', 'i'); + cm.replaceRange('gangnam', cm.getCursor()); + helpers.doKeys('<Esc>'); + helpers.doKeys('q'); + helpers.doKeys('q', 'b', 'o'); + cm.replaceRange('style', cm.getCursor()); + helpers.doKeys('<Esc>'); + helpers.doKeys('q'); + cm.openDialog = helpers.fakeOpenDialog('registers'); + cm.openNotification = helpers.fakeOpenNotification(function(text) { + is(/a\s+i/.test(text)); + is(/b\s+o/.test(text)); + }); + helpers.doKeys(':'); +}, { value: ''}); +testVim('._register', function(cm,vim,helpers) { + cm.setCursor(0,0); + helpers.doKeys('i'); + cm.replaceRange('foo',cm.getCursor()); + helpers.doKeys('<Esc>'); + cm.openDialog = helpers.fakeOpenDialog('registers'); + cm.openNotification = helpers.fakeOpenNotification(function(text) { + is(/\.\s+foo/.test(text)); + }); + helpers.doKeys(':'); +}, {value: ''}); +testVim(':_register', function(cm,vim,helpers) { + helpers.doEx('bar'); + cm.openDialog = helpers.fakeOpenDialog('registers'); + cm.openNotification = helpers.fakeOpenNotification(function(text) { + is(/:\s+bar/.test(text)); + }); + helpers.doKeys(':'); +}, {value: ''}); +testVim('search_register_escape', function(cm, vim, helpers) { + // Check that the register is restored if the user escapes rather than confirms. + cm.openDialog = helpers.fakeOpenDialog('waldo'); + helpers.doKeys('/'); + var onKeyDown; + var onKeyUp; + var KEYCODES = { + f: 70, + o: 79, + Esc: 27 + }; + cm.openDialog = function(template, callback, options) { + onKeyDown = options.onKeyDown; + onKeyUp = options.onKeyUp; + }; + var close = function() {}; + helpers.doKeys('/'); + // Fake some keyboard events coming in. + onKeyDown({keyCode: KEYCODES.f}, '', close); + onKeyUp({keyCode: KEYCODES.f}, '', close); + onKeyDown({keyCode: KEYCODES.o}, 'f', close); + onKeyUp({keyCode: KEYCODES.o}, 'f', close); + onKeyDown({keyCode: KEYCODES.o}, 'fo', close); + onKeyUp({keyCode: KEYCODES.o}, 'fo', close); + onKeyDown({keyCode: KEYCODES.Esc}, 'foo', close); + cm.openDialog = helpers.fakeOpenDialog('registers'); + cm.openNotification = helpers.fakeOpenNotification(function(text) { + is(/waldo/.test(text)); + is(!/foo/.test(text)); + }); + helpers.doKeys(':'); +}, {value: ''}); +testVim('search_register', function(cm, vim, helpers) { + cm.openDialog = helpers.fakeOpenDialog('foo'); + helpers.doKeys('/'); + cm.openDialog = helpers.fakeOpenDialog('registers'); + cm.openNotification = helpers.fakeOpenNotification(function(text) { + is(/\/\s+foo/.test(text)); + }); + helpers.doKeys(':'); +}, {value: ''}); +testVim('search_history', function(cm, vim, helpers) { + cm.openDialog = helpers.fakeOpenDialog('this'); + helpers.doKeys('/'); + cm.openDialog = helpers.fakeOpenDialog('checks'); + helpers.doKeys('/'); + cm.openDialog = helpers.fakeOpenDialog('search'); + helpers.doKeys('/'); + cm.openDialog = helpers.fakeOpenDialog('history'); + helpers.doKeys('/'); + cm.openDialog = helpers.fakeOpenDialog('checks'); + helpers.doKeys('/'); + var onKeyDown; + var onKeyUp; + var query = ''; + var keyCodes = { + Up: 38, + Down: 40 + }; + cm.openDialog = function(template, callback, options) { + onKeyUp = options.onKeyUp; + onKeyDown = options.onKeyDown; + }; + var close = function(newVal) { + if (typeof newVal == 'string') query = newVal; + } + helpers.doKeys('/'); + onKeyDown({keyCode: keyCodes.Up}, query, close); + onKeyUp({keyCode: keyCodes.Up}, query, close); + eq(query, 'checks'); + onKeyDown({keyCode: keyCodes.Up}, query, close); + onKeyUp({keyCode: keyCodes.Up}, query, close); + eq(query, 'history'); + onKeyDown({keyCode: keyCodes.Up}, query, close); + onKeyUp({keyCode: keyCodes.Up}, query, close); + eq(query, 'search'); + onKeyDown({keyCode: keyCodes.Up}, query, close); + onKeyUp({keyCode: keyCodes.Up}, query, close); + eq(query, 'this'); + onKeyDown({keyCode: keyCodes.Down}, query, close); + onKeyUp({keyCode: keyCodes.Down}, query, close); + eq(query, 'search'); +}, {value: ''}); +testVim('exCommand_history', function(cm, vim, helpers) { + cm.openDialog = helpers.fakeOpenDialog('registers'); + helpers.doKeys(':'); + cm.openDialog = helpers.fakeOpenDialog('sort'); + helpers.doKeys(':'); + cm.openDialog = helpers.fakeOpenDialog('map'); + helpers.doKeys(':'); + cm.openDialog = helpers.fakeOpenDialog('invalid'); + helpers.doKeys(':'); + var onKeyDown; + var onKeyUp; + var input = ''; + var keyCodes = { + Up: 38, + Down: 40, + s: 115 + }; + cm.openDialog = function(template, callback, options) { + onKeyUp = options.onKeyUp; + onKeyDown = options.onKeyDown; + }; + var close = function(newVal) { + if (typeof newVal == 'string') input = newVal; + } + helpers.doKeys(':'); + onKeyDown({keyCode: keyCodes.Up}, input, close); + eq(input, 'invalid'); + onKeyDown({keyCode: keyCodes.Up}, input, close); + eq(input, 'map'); + onKeyDown({keyCode: keyCodes.Up}, input, close); + eq(input, 'sort'); + onKeyDown({keyCode: keyCodes.Up}, input, close); + eq(input, 'registers'); + onKeyDown({keyCode: keyCodes.s}, '', close); + input = 's'; + onKeyDown({keyCode: keyCodes.Up}, input, close); + eq(input, 'sort'); +}, {value: ''}); +testVim('search_clear', function(cm, vim, helpers) { + var onKeyDown; + var input = ''; + var keyCodes = { + Ctrl: 17, + u: 85 + }; + cm.openDialog = function(template, callback, options) { + onKeyDown = options.onKeyDown; + }; + var close = function(newVal) { + if (typeof newVal == 'string') input = newVal; + } + helpers.doKeys('/'); + input = 'foo'; + onKeyDown({keyCode: keyCodes.Ctrl}, input, close); + onKeyDown({keyCode: keyCodes.u, ctrlKey: true}, input, close); + eq(input, ''); +}); +testVim('exCommand_clear', function(cm, vim, helpers) { + var onKeyDown; + var input = ''; + var keyCodes = { + Ctrl: 17, + u: 85 + }; + cm.openDialog = function(template, callback, options) { + onKeyDown = options.onKeyDown; + }; + var close = function(newVal) { + if (typeof newVal == 'string') input = newVal; + } + helpers.doKeys(':'); + input = 'foo'; + onKeyDown({keyCode: keyCodes.Ctrl}, input, close); + onKeyDown({keyCode: keyCodes.u, ctrlKey: true}, input, close); + eq(input, ''); +}); +testVim('.', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('2', 'd', 'w'); + helpers.doKeys('.'); + eq('5 6', cm.getValue()); +}, { value: '1 2 3 4 5 6'}); +testVim('._repeat', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('2', 'd', 'w'); + helpers.doKeys('3', '.'); + eq('6', cm.getValue()); +}, { value: '1 2 3 4 5 6'}); +testVim('._insert', function(cm, vim, helpers) { + helpers.doKeys('i'); + cm.replaceRange('test', cm.getCursor()); + helpers.doKeys('<Esc>'); + helpers.doKeys('.'); + eq('testestt', cm.getValue()); + helpers.assertCursorAt(0, 6); + helpers.doKeys('O'); + cm.replaceRange('xyz', cm.getCursor()); + helpers.doInsertModeKeys('Backspace'); + helpers.doInsertModeKeys('Down'); + helpers.doKeys('<Esc>'); + helpers.doKeys('.'); + eq('xy\nxy\ntestestt', cm.getValue()); + helpers.assertCursorAt(1, 1); +}, { value: ''}); +testVim('._insert_repeat', function(cm, vim, helpers) { + helpers.doKeys('i'); + cm.replaceRange('test', cm.getCursor()); + cm.setCursor(0, 4); + helpers.doKeys('<Esc>'); + helpers.doKeys('2', '.'); + eq('testesttestt', cm.getValue()); + helpers.assertCursorAt(0, 10); +}, { value: ''}); +testVim('._repeat_insert', function(cm, vim, helpers) { + helpers.doKeys('3', 'i'); + cm.replaceRange('te', cm.getCursor()); + cm.setCursor(0, 2); + helpers.doKeys('<Esc>'); + helpers.doKeys('.'); + eq('tetettetetee', cm.getValue()); + helpers.assertCursorAt(0, 10); +}, { value: ''}); +testVim('._insert_o', function(cm, vim, helpers) { + helpers.doKeys('o'); + cm.replaceRange('z', cm.getCursor()); + cm.setCursor(1, 1); + helpers.doKeys('<Esc>'); + helpers.doKeys('.'); + eq('\nz\nz', cm.getValue()); + helpers.assertCursorAt(2, 0); +}, { value: ''}); +testVim('._insert_o_repeat', function(cm, vim, helpers) { + helpers.doKeys('o'); + cm.replaceRange('z', cm.getCursor()); + helpers.doKeys('<Esc>'); + cm.setCursor(1, 0); + helpers.doKeys('2', '.'); + eq('\nz\nz\nz', cm.getValue()); + helpers.assertCursorAt(3, 0); +}, { value: ''}); +testVim('._insert_o_indent', function(cm, vim, helpers) { + helpers.doKeys('o'); + cm.replaceRange('z', cm.getCursor()); + helpers.doKeys('<Esc>'); + cm.setCursor(1, 2); + helpers.doKeys('.'); + eq('{\n z\n z', cm.getValue()); + helpers.assertCursorAt(2, 2); +}, { value: '{'}); +testVim('._insert_cw', function(cm, vim, helpers) { + helpers.doKeys('c', 'w'); + cm.replaceRange('test', cm.getCursor()); + helpers.doKeys('<Esc>'); + cm.setCursor(0, 3); + helpers.doKeys('2', 'l'); + helpers.doKeys('.'); + eq('test test word3', cm.getValue()); + helpers.assertCursorAt(0, 8); +}, { value: 'word1 word2 word3' }); +testVim('._insert_cw_repeat', function(cm, vim, helpers) { + // For some reason, repeat cw in desktop VIM will does not repeat insert mode + // changes. Will conform to that behavior. + helpers.doKeys('c', 'w'); + cm.replaceRange('test', cm.getCursor()); + helpers.doKeys('<Esc>'); + cm.setCursor(0, 4); + helpers.doKeys('l'); + helpers.doKeys('2', '.'); + eq('test test', cm.getValue()); + helpers.assertCursorAt(0, 8); +}, { value: 'word1 word2 word3' }); +testVim('._delete', function(cm, vim, helpers) { + cm.setCursor(0, 5); + helpers.doKeys('i'); + helpers.doInsertModeKeys('Backspace'); + helpers.doKeys('<Esc>'); + helpers.doKeys('.'); + eq('zace', cm.getValue()); + helpers.assertCursorAt(0, 1); +}, { value: 'zabcde'}); +testVim('._delete_repeat', function(cm, vim, helpers) { + cm.setCursor(0, 6); + helpers.doKeys('i'); + helpers.doInsertModeKeys('Backspace'); + helpers.doKeys('<Esc>'); + helpers.doKeys('2', '.'); + eq('zzce', cm.getValue()); + helpers.assertCursorAt(0, 1); +}, { value: 'zzabcde'}); +testVim('._visual_>', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('V', 'j', '>'); + cm.setCursor(2, 0) + helpers.doKeys('.'); + eq(' 1\n 2\n 3\n 4', cm.getValue()); + helpers.assertCursorAt(2, 2); +}, { value: '1\n2\n3\n4'}); +testVim('._replace_repeat', function(cm, vim, helpers) { + helpers.doKeys('R'); + cm.replaceRange('123', cm.getCursor(), offsetCursor(cm.getCursor(), 0, 3)); + cm.setCursor(0, 3); + helpers.doKeys('<Esc>'); + helpers.doKeys('2', '.'); + eq('12123123\nabcdefg', cm.getValue()); + helpers.assertCursorAt(0, 7); + cm.setCursor(1, 0); + helpers.doKeys('.'); + eq('12123123\n123123g', cm.getValue()); + helpers.doKeys('l', '"', '.', 'p'); + eq('12123123\n123123g123', cm.getValue()); +}, { value: 'abcdef\nabcdefg'}); +testVim('f;', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('f', 'x'); + helpers.doKeys(';'); + helpers.doKeys('2', ';'); + eq(9, cm.getCursor().ch); +}, { value: '01x3xx678x'}); +testVim('F;', function(cm, vim, helpers) { + cm.setCursor(0, 8); + helpers.doKeys('F', 'x'); + helpers.doKeys(';'); + helpers.doKeys('2', ';'); + eq(2, cm.getCursor().ch); +}, { value: '01x3xx6x8x'}); +testVim('t;', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('t', 'x'); + helpers.doKeys(';'); + helpers.doKeys('2', ';'); + eq(8, cm.getCursor().ch); +}, { value: '01x3xx678x'}); +testVim('T;', function(cm, vim, helpers) { + cm.setCursor(0, 9); + helpers.doKeys('T', 'x'); + helpers.doKeys(';'); + helpers.doKeys('2', ';'); + eq(2, cm.getCursor().ch); +}, { value: '0xx3xx678x'}); +testVim('f,', function(cm, vim, helpers) { + cm.setCursor(0, 6); + helpers.doKeys('f', 'x'); + helpers.doKeys(','); + helpers.doKeys('2', ','); + eq(2, cm.getCursor().ch); +}, { value: '01x3xx678x'}); +testVim('F,', function(cm, vim, helpers) { + cm.setCursor(0, 3); + helpers.doKeys('F', 'x'); + helpers.doKeys(','); + helpers.doKeys('2', ','); + eq(9, cm.getCursor().ch); +}, { value: '01x3xx678x'}); +testVim('t,', function(cm, vim, helpers) { + cm.setCursor(0, 6); + helpers.doKeys('t', 'x'); + helpers.doKeys(','); + helpers.doKeys('2', ','); + eq(3, cm.getCursor().ch); +}, { value: '01x3xx678x'}); +testVim('T,', function(cm, vim, helpers) { + cm.setCursor(0, 4); + helpers.doKeys('T', 'x'); + helpers.doKeys(','); + helpers.doKeys('2', ','); + eq(8, cm.getCursor().ch); +}, { value: '01x3xx67xx'}); +testVim('fd,;', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('f', '4'); + cm.setCursor(0, 0); + helpers.doKeys('d', ';'); + eq('56789', cm.getValue()); + helpers.doKeys('u'); + cm.setCursor(0, 9); + helpers.doKeys('d', ','); + eq('01239', cm.getValue()); +}, { value: '0123456789'}); +testVim('Fd,;', function(cm, vim, helpers) { + cm.setCursor(0, 9); + helpers.doKeys('F', '4'); + cm.setCursor(0, 9); + helpers.doKeys('d', ';'); + eq('01239', cm.getValue()); + helpers.doKeys('u'); + cm.setCursor(0, 0); + helpers.doKeys('d', ','); + eq('56789', cm.getValue()); +}, { value: '0123456789'}); +testVim('td,;', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('t', '4'); + cm.setCursor(0, 0); + helpers.doKeys('d', ';'); + eq('456789', cm.getValue()); + helpers.doKeys('u'); + cm.setCursor(0, 9); + helpers.doKeys('d', ','); + eq('012349', cm.getValue()); +}, { value: '0123456789'}); +testVim('Td,;', function(cm, vim, helpers) { + cm.setCursor(0, 9); + helpers.doKeys('T', '4'); + cm.setCursor(0, 9); + helpers.doKeys('d', ';'); + eq('012349', cm.getValue()); + helpers.doKeys('u'); + cm.setCursor(0, 0); + helpers.doKeys('d', ','); + eq('456789', cm.getValue()); +}, { value: '0123456789'}); +testVim('fc,;', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('f', '4'); + cm.setCursor(0, 0); + helpers.doKeys('c', ';', '<Esc>'); + eq('56789', cm.getValue()); + helpers.doKeys('u'); + cm.setCursor(0, 9); + helpers.doKeys('c', ','); + eq('01239', cm.getValue()); +}, { value: '0123456789'}); +testVim('Fc,;', function(cm, vim, helpers) { + cm.setCursor(0, 9); + helpers.doKeys('F', '4'); + cm.setCursor(0, 9); + helpers.doKeys('c', ';', '<Esc>'); + eq('01239', cm.getValue()); + helpers.doKeys('u'); + cm.setCursor(0, 0); + helpers.doKeys('c', ','); + eq('56789', cm.getValue()); +}, { value: '0123456789'}); +testVim('tc,;', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('t', '4'); + cm.setCursor(0, 0); + helpers.doKeys('c', ';', '<Esc>'); + eq('456789', cm.getValue()); + helpers.doKeys('u'); + cm.setCursor(0, 9); + helpers.doKeys('c', ','); + eq('012349', cm.getValue()); +}, { value: '0123456789'}); +testVim('Tc,;', function(cm, vim, helpers) { + cm.setCursor(0, 9); + helpers.doKeys('T', '4'); + cm.setCursor(0, 9); + helpers.doKeys('c', ';', '<Esc>'); + eq('012349', cm.getValue()); + helpers.doKeys('u'); + cm.setCursor(0, 0); + helpers.doKeys('c', ','); + eq('456789', cm.getValue()); +}, { value: '0123456789'}); +testVim('fy,;', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('f', '4'); + cm.setCursor(0, 0); + helpers.doKeys('y', ';', 'P'); + eq('012340123456789', cm.getValue()); + helpers.doKeys('u'); + cm.setCursor(0, 9); + helpers.doKeys('y', ',', 'P'); + eq('012345678456789', cm.getValue()); +}, { value: '0123456789'}); +testVim('Fy,;', function(cm, vim, helpers) { + cm.setCursor(0, 9); + helpers.doKeys('F', '4'); + cm.setCursor(0, 9); + helpers.doKeys('y', ';', 'p'); + eq('012345678945678', cm.getValue()); + helpers.doKeys('u'); + cm.setCursor(0, 0); + helpers.doKeys('y', ',', 'P'); + eq('012340123456789', cm.getValue()); +}, { value: '0123456789'}); +testVim('ty,;', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('t', '4'); + cm.setCursor(0, 0); + helpers.doKeys('y', ';', 'P'); + eq('01230123456789', cm.getValue()); + helpers.doKeys('u'); + cm.setCursor(0, 9); + helpers.doKeys('y', ',', 'p'); + eq('01234567895678', cm.getValue()); +}, { value: '0123456789'}); +testVim('Ty,;', function(cm, vim, helpers) { + cm.setCursor(0, 9); + helpers.doKeys('T', '4'); + cm.setCursor(0, 9); + helpers.doKeys('y', ';', 'p'); + eq('01234567895678', cm.getValue()); + helpers.doKeys('u'); + cm.setCursor(0, 0); + helpers.doKeys('y', ',', 'P'); + eq('01230123456789', cm.getValue()); +}, { value: '0123456789'}); +testVim('HML', function(cm, vim, helpers) { + var lines = 35; + var textHeight = cm.defaultTextHeight(); + cm.setSize(600, lines*textHeight); + cm.setCursor(120, 0); + helpers.doKeys('H'); + helpers.assertCursorAt(86, 2); + helpers.doKeys('L'); + helpers.assertCursorAt(120, 4); + helpers.doKeys('M'); + helpers.assertCursorAt(103,4); +}, { value: (function(){ + var lines = new Array(100); + var upper = ' xx\n'; + var lower = ' xx\n'; + upper = lines.join(upper); + lower = lines.join(lower); + return upper + lower; +})()}); + +var zVals = []; +forEach(['zb','zz','zt','z-','z.','z<CR>'], function(e, idx){ + var lineNum = 250; + var lines = 35; + testVim(e, function(cm, vim, helpers) { + var k1 = e[0]; + var k2 = e.substring(1); + var textHeight = cm.defaultTextHeight(); + cm.setSize(600, lines*textHeight); + cm.setCursor(lineNum, 0); + helpers.doKeys(k1, k2); + zVals[idx] = cm.getScrollInfo().top; + }, { value: (function(){ + return new Array(500).join('\n'); + })()}); +}); +testVim('zb_to_bottom', function(cm, vim, helpers){ + var lineNum = 250; + cm.setSize(600, 35*cm.defaultTextHeight()); + cm.setCursor(lineNum, 0); + helpers.doKeys('z', 'b'); + var scrollInfo = cm.getScrollInfo(); + eq(scrollInfo.top + scrollInfo.clientHeight, cm.charCoords(Pos(lineNum, 0), 'local').bottom); +}, { value: (function(){ + return new Array(500).join('\n'); +})()}); +testVim('zt_to_top', function(cm, vim, helpers){ + var lineNum = 250; + cm.setSize(600, 35*cm.defaultTextHeight()); + cm.setCursor(lineNum, 0); + helpers.doKeys('z', 't'); + eq(cm.getScrollInfo().top, cm.charCoords(Pos(lineNum, 0), 'local').top); +}, { value: (function(){ + return new Array(500).join('\n'); +})()}); +testVim('zb<zz', function(cm, vim, helpers){ + eq(zVals[0]<zVals[1], true); +}); +testVim('zz<zt', function(cm, vim, helpers){ + eq(zVals[1]<zVals[2], true); +}); +testVim('zb==z-', function(cm, vim, helpers){ + eq(zVals[0], zVals[3]); +}); +testVim('zz==z.', function(cm, vim, helpers){ + eq(zVals[1], zVals[4]); +}); +testVim('zt==z<CR>', function(cm, vim, helpers){ + eq(zVals[2], zVals[5]); +}); + +var moveTillCharacterSandbox = + 'The quick brown fox \n'; +testVim('moveTillCharacter', function(cm, vim, helpers){ + cm.setCursor(0, 0); + // Search for the 'q'. + cm.openDialog = helpers.fakeOpenDialog('q'); + helpers.doKeys('/'); + eq(4, cm.getCursor().ch); + // Jump to just before the first o in the list. + helpers.doKeys('t'); + helpers.doKeys('o'); + eq('The quick brown fox \n', cm.getValue()); + // Delete that one character. + helpers.doKeys('d'); + helpers.doKeys('t'); + helpers.doKeys('o'); + eq('The quick bown fox \n', cm.getValue()); + // Delete everything until the next 'o'. + helpers.doKeys('.'); + eq('The quick box \n', cm.getValue()); + // An unmatched character should have no effect. + helpers.doKeys('d'); + helpers.doKeys('t'); + helpers.doKeys('q'); + eq('The quick box \n', cm.getValue()); + // Matches should only be possible on single lines. + helpers.doKeys('d'); + helpers.doKeys('t'); + helpers.doKeys('z'); + eq('The quick box \n', cm.getValue()); + // After all that, the search for 'q' should still be active, so the 'N' command + // can run it again in reverse. Use that to delete everything back to the 'q'. + helpers.doKeys('d'); + helpers.doKeys('N'); + eq('The ox \n', cm.getValue()); + eq(4, cm.getCursor().ch); +}, { value: moveTillCharacterSandbox}); +testVim('searchForPipe', function(cm, vim, helpers){ + CodeMirror.Vim.setOption('pcre', false); + cm.setCursor(0, 0); + // Search for the '|'. + cm.openDialog = helpers.fakeOpenDialog('|'); + helpers.doKeys('/'); + eq(4, cm.getCursor().ch); +}, { value: 'this|that'}); + + +var scrollMotionSandbox = + '\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n'; +testVim('scrollMotion', function(cm, vim, helpers){ + var prevCursor, prevScrollInfo; + cm.setCursor(0, 0); + // ctrl-y at the top of the file should have no effect. + helpers.doKeys('<C-y>'); + eq(0, cm.getCursor().line); + prevScrollInfo = cm.getScrollInfo(); + helpers.doKeys('<C-e>'); + eq(1, cm.getCursor().line); + is(prevScrollInfo.top < cm.getScrollInfo().top); + // Jump to the end of the sandbox. + cm.setCursor(1000, 0); + prevCursor = cm.getCursor(); + // ctrl-e at the bottom of the file should have no effect. + helpers.doKeys('<C-e>'); + eq(prevCursor.line, cm.getCursor().line); + prevScrollInfo = cm.getScrollInfo(); + helpers.doKeys('<C-y>'); + eq(prevCursor.line - 1, cm.getCursor().line, "Y"); + is(prevScrollInfo.top > cm.getScrollInfo().top); +}, { value: scrollMotionSandbox}); + +var squareBracketMotionSandbox = ''+ + '({\n'+//0 + ' ({\n'+//11 + ' /*comment {\n'+//2 + ' */(\n'+//3 + '#else \n'+//4 + ' /* )\n'+//5 + '#if }\n'+//6 + ' )}*/\n'+//7 + ')}\n'+//8 + '{}\n'+//9 + '#else {{\n'+//10 + '{}\n'+//11 + '}\n'+//12 + '{\n'+//13 + '#endif\n'+//14 + '}\n'+//15 + '}\n'+//16 + '#else';//17 +testVim('[[, ]]', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys(']', ']'); + helpers.assertCursorAt(9,0); + helpers.doKeys('2', ']', ']'); + helpers.assertCursorAt(13,0); + helpers.doKeys(']', ']'); + helpers.assertCursorAt(17,0); + helpers.doKeys('[', '['); + helpers.assertCursorAt(13,0); + helpers.doKeys('2', '[', '['); + helpers.assertCursorAt(9,0); + helpers.doKeys('[', '['); + helpers.assertCursorAt(0,0); +}, { value: squareBracketMotionSandbox}); +testVim('[], ][', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys(']', '['); + helpers.assertCursorAt(12,0); + helpers.doKeys('2', ']', '['); + helpers.assertCursorAt(16,0); + helpers.doKeys(']', '['); + helpers.assertCursorAt(17,0); + helpers.doKeys('[', ']'); + helpers.assertCursorAt(16,0); + helpers.doKeys('2', '[', ']'); + helpers.assertCursorAt(12,0); + helpers.doKeys('[', ']'); + helpers.assertCursorAt(0,0); +}, { value: squareBracketMotionSandbox}); +testVim('[{, ]}', function(cm, vim, helpers) { + cm.setCursor(4, 10); + helpers.doKeys('[', '{'); + helpers.assertCursorAt(2,12); + helpers.doKeys('2', '[', '{'); + helpers.assertCursorAt(0,1); + cm.setCursor(4, 10); + helpers.doKeys(']', '}'); + helpers.assertCursorAt(6,11); + helpers.doKeys('2', ']', '}'); + helpers.assertCursorAt(8,1); + cm.setCursor(0,1); + helpers.doKeys(']', '}'); + helpers.assertCursorAt(8,1); + helpers.doKeys('[', '{'); + helpers.assertCursorAt(0,1); +}, { value: squareBracketMotionSandbox}); +testVim('[(, ])', function(cm, vim, helpers) { + cm.setCursor(4, 10); + helpers.doKeys('[', '('); + helpers.assertCursorAt(3,14); + helpers.doKeys('2', '[', '('); + helpers.assertCursorAt(0,0); + cm.setCursor(4, 10); + helpers.doKeys(']', ')'); + helpers.assertCursorAt(5,11); + helpers.doKeys('2', ']', ')'); + helpers.assertCursorAt(8,0); + helpers.doKeys('[', '('); + helpers.assertCursorAt(0,0); + helpers.doKeys(']', ')'); + helpers.assertCursorAt(8,0); +}, { value: squareBracketMotionSandbox}); +testVim('[*, ]*, [/, ]/', function(cm, vim, helpers) { + forEach(['*', '/'], function(key){ + cm.setCursor(7, 0); + helpers.doKeys('2', '[', key); + helpers.assertCursorAt(2,2); + helpers.doKeys('2', ']', key); + helpers.assertCursorAt(7,5); + }); +}, { value: squareBracketMotionSandbox}); +testVim('[#, ]#', function(cm, vim, helpers) { + cm.setCursor(10, 3); + helpers.doKeys('2', '[', '#'); + helpers.assertCursorAt(4,0); + helpers.doKeys('5', ']', '#'); + helpers.assertCursorAt(17,0); + cm.setCursor(10, 3); + helpers.doKeys(']', '#'); + helpers.assertCursorAt(14,0); +}, { value: squareBracketMotionSandbox}); +testVim('[m, ]m, [M, ]M', function(cm, vim, helpers) { + cm.setCursor(11, 0); + helpers.doKeys('[', 'm'); + helpers.assertCursorAt(10,7); + helpers.doKeys('4', '[', 'm'); + helpers.assertCursorAt(1,3); + helpers.doKeys('5', ']', 'm'); + helpers.assertCursorAt(11,0); + helpers.doKeys('[', 'M'); + helpers.assertCursorAt(9,1); + helpers.doKeys('3', ']', 'M'); + helpers.assertCursorAt(15,0); + helpers.doKeys('5', '[', 'M'); + helpers.assertCursorAt(7,3); +}, { value: squareBracketMotionSandbox}); + +testVim('i_indent_right', function(cm, vim, helpers) { + cm.setCursor(0, 3); + var expectedValue = ' word1\nword2\nword3 '; + helpers.doKeys('i', '<C-t>'); + eq(expectedValue, cm.getValue()); + helpers.assertCursorAt(0, 5); +}, { value: ' word1\nword2\nword3 ', indentUnit: 2 }); +testVim('i_indent_left', function(cm, vim, helpers) { + cm.setCursor(0, 3); + var expectedValue = ' word1\nword2\nword3 '; + helpers.doKeys('i', '<C-d>'); + eq(expectedValue, cm.getValue()); + helpers.assertCursorAt(0, 1); +}, { value: ' word1\nword2\nword3 ', indentUnit: 2 }); + +// Ex mode tests +testVim('ex_go_to_line', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doEx('4'); + helpers.assertCursorAt(3, 0); +}, { value: 'a\nb\nc\nd\ne\n'}); +testVim('ex_go_to_mark', function(cm, vim, helpers) { + cm.setCursor(3, 0); + helpers.doKeys('m', 'a'); + cm.setCursor(0, 0); + helpers.doEx('\'a'); + helpers.assertCursorAt(3, 0); +}, { value: 'a\nb\nc\nd\ne\n'}); +testVim('ex_go_to_line_offset', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doEx('+3'); + helpers.assertCursorAt(3, 0); + helpers.doEx('-1'); + helpers.assertCursorAt(2, 0); + helpers.doEx('.2'); + helpers.assertCursorAt(4, 0); + helpers.doEx('.-3'); + helpers.assertCursorAt(1, 0); +}, { value: 'a\nb\nc\nd\ne\n'}); +testVim('ex_go_to_mark_offset', function(cm, vim, helpers) { + cm.setCursor(2, 0); + helpers.doKeys('m', 'a'); + cm.setCursor(0, 0); + helpers.doEx('\'a1'); + helpers.assertCursorAt(3, 0); + helpers.doEx('\'a-1'); + helpers.assertCursorAt(1, 0); + helpers.doEx('\'a+2'); + helpers.assertCursorAt(4, 0); +}, { value: 'a\nb\nc\nd\ne\n'}); +testVim('ex_write', function(cm, vim, helpers) { + var tmp = CodeMirror.commands.save; + var written; + var actualCm; + CodeMirror.commands.save = function(cm) { + written = true; + actualCm = cm; + }; + // Test that w, wr, wri ... write all trigger :write. + var command = 'write'; + for (var i = 1; i < command.length; i++) { + written = false; + actualCm = null; + helpers.doEx(command.substring(0, i)); + eq(written, true); + eq(actualCm, cm); + } + CodeMirror.commands.save = tmp; +}); +testVim('ex_sort', function(cm, vim, helpers) { + helpers.doEx('sort'); + eq('Z\na\nb\nc\nd', cm.getValue()); +}, { value: 'b\nZ\nd\nc\na'}); +testVim('ex_sort_reverse', function(cm, vim, helpers) { + helpers.doEx('sort!'); + eq('d\nc\nb\na', cm.getValue()); +}, { value: 'b\nd\nc\na'}); +testVim('ex_sort_range', function(cm, vim, helpers) { + helpers.doEx('2,3sort'); + eq('b\nc\nd\na', cm.getValue()); +}, { value: 'b\nd\nc\na'}); +testVim('ex_sort_oneline', function(cm, vim, helpers) { + helpers.doEx('2sort'); + // Expect no change. + eq('b\nd\nc\na', cm.getValue()); +}, { value: 'b\nd\nc\na'}); +testVim('ex_sort_ignoreCase', function(cm, vim, helpers) { + helpers.doEx('sort i'); + eq('a\nb\nc\nd\nZ', cm.getValue()); +}, { value: 'b\nZ\nd\nc\na'}); +testVim('ex_sort_unique', function(cm, vim, helpers) { + helpers.doEx('sort u'); + eq('Z\na\nb\nc\nd', cm.getValue()); +}, { value: 'b\nZ\na\na\nd\na\nc\na'}); +testVim('ex_sort_decimal', function(cm, vim, helpers) { + helpers.doEx('sort d'); + eq('d3\n s5\n6\n.9', cm.getValue()); +}, { value: '6\nd3\n s5\n.9'}); +testVim('ex_sort_decimal_negative', function(cm, vim, helpers) { + helpers.doEx('sort d'); + eq('z-9\nd3\n s5\n6\n.9', cm.getValue()); +}, { value: '6\nd3\n s5\n.9\nz-9'}); +testVim('ex_sort_decimal_reverse', function(cm, vim, helpers) { + helpers.doEx('sort! d'); + eq('.9\n6\n s5\nd3', cm.getValue()); +}, { value: '6\nd3\n s5\n.9'}); +testVim('ex_sort_hex', function(cm, vim, helpers) { + helpers.doEx('sort x'); + eq(' s5\n6\n.9\n&0xB\nd3', cm.getValue()); +}, { value: '6\nd3\n s5\n&0xB\n.9'}); +testVim('ex_sort_octal', function(cm, vim, helpers) { + helpers.doEx('sort o'); + eq('.9\n.8\nd3\n s5\n6', cm.getValue()); +}, { value: '6\nd3\n s5\n.9\n.8'}); +testVim('ex_sort_decimal_mixed', function(cm, vim, helpers) { + helpers.doEx('sort d'); + eq('z\ny\nc1\nb2\na3', cm.getValue()); +}, { value: 'a3\nz\nc1\ny\nb2'}); +testVim('ex_sort_decimal_mixed_reverse', function(cm, vim, helpers) { + helpers.doEx('sort! d'); + eq('a3\nb2\nc1\nz\ny', cm.getValue()); +}, { value: 'a3\nz\nc1\ny\nb2'}); +testVim('ex_sort_pattern_alpha', function(cm, vim, helpers) { + helpers.doEx('sort /[a-z]/'); + eq('a3\nb2\nc1\ny\nz', cm.getValue()); +}, { value: 'z\ny\nc1\nb2\na3'}); +testVim('ex_sort_pattern_alpha_reverse', function(cm, vim, helpers) { + helpers.doEx('sort! /[a-z]/'); + eq('z\ny\nc1\nb2\na3', cm.getValue()); +}, { value: 'z\ny\nc1\nb2\na3'}); +testVim('ex_sort_pattern_alpha_ignoreCase', function(cm, vim, helpers) { + helpers.doEx('sort i/[a-z]/'); + eq('a3\nb2\nC1\nY\nz', cm.getValue()); +}, { value: 'z\nY\nC1\nb2\na3'}); +testVim('ex_sort_pattern_alpha_longer', function(cm, vim, helpers) { + helpers.doEx('sort /[a-z]+/'); + eq('a\naa\nab\nade\nadele\nadelle\nadriana\nalex\nalexandra\nb\nc\ny\nz', cm.getValue()); +}, { value: 'z\nab\naa\nade\nadelle\nalexandra\nalex\nadriana\nadele\ny\nc\nb\na'}); +testVim('ex_sort_pattern_alpha_only', function(cm, vim, helpers) { + helpers.doEx('sort /^[a-z]$/'); + eq('z1\ny2\na3\nb\nc', cm.getValue()); +}, { value: 'z1\ny2\na3\nc\nb'}); +testVim('ex_sort_pattern_alpha_only_reverse', function(cm, vim, helpers) { + helpers.doEx('sort! /^[a-z]$/'); + eq('c\nb\nz1\ny2\na3', cm.getValue()); +}, { value: 'z1\ny2\na3\nc\nb'}); +testVim('ex_sort_pattern_alpha_num', function(cm, vim, helpers) { + helpers.doEx('sort /[a-z][0-9]/'); + eq('c\nb\na3\ny2\nz1', cm.getValue()); +}, { value: 'z1\ny2\na3\nc\nb'}); +// test for :global command +testVim('ex_global', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doEx('g/one/s//two'); + eq('two two\n two two\n two two', cm.getValue()); + helpers.doEx('1,2g/two/s//one'); + eq('one one\n one one\n two two', cm.getValue()); +}, {value: 'one one\n one one\n one one'}); +testVim('ex_global_confirm', function(cm, vim, helpers) { + cm.setCursor(0, 0); + var onKeyDown; + var openDialogSave = cm.openDialog; + var KEYCODES = { + a: 65, + n: 78, + q: 81, + y: 89 + }; + // Intercept the ex command, 'global' + cm.openDialog = function(template, callback, options) { + // Intercept the prompt for the embedded ex command, 'substitute' + cm.openDialog = function(template, callback, options) { + onKeyDown = options.onKeyDown; + }; + callback('g/one/s//two/gc'); + }; + helpers.doKeys(':'); + var close = function() {}; + onKeyDown({keyCode: KEYCODES.n}, '', close); + onKeyDown({keyCode: KEYCODES.y}, '', close); + onKeyDown({keyCode: KEYCODES.a}, '', close); + onKeyDown({keyCode: KEYCODES.q}, '', close); + onKeyDown({keyCode: KEYCODES.y}, '', close); + eq('one two\n two two\n one one\n two one\n one one', cm.getValue()); +}, {value: 'one one\n one one\n one one\n one one\n one one'}); +// Basic substitute tests. +testVim('ex_substitute_same_line', function(cm, vim, helpers) { + cm.setCursor(1, 0); + helpers.doEx('s/one/two/g'); + eq('one one\n two two', cm.getValue()); +}, { value: 'one one\n one one'}); +testVim('ex_substitute_full_file', function(cm, vim, helpers) { + cm.setCursor(1, 0); + helpers.doEx('%s/one/two/g'); + eq('two two\n two two', cm.getValue()); +}, { value: 'one one\n one one'}); +testVim('ex_substitute_input_range', function(cm, vim, helpers) { + cm.setCursor(1, 0); + helpers.doEx('1,3s/\\d/0/g'); + eq('0\n0\n0\n4', cm.getValue()); +}, { value: '1\n2\n3\n4' }); +testVim('ex_substitute_range_current_to_input', function(cm, vim, helpers) { + cm.setCursor(1, 0); + helpers.doEx('.,3s/\\d/0/g'); + eq('1\n0\n0\n4', cm.getValue()); +}, { value: '1\n2\n3\n4' }); +testVim('ex_substitute_range_input_to_current', function(cm, vim, helpers) { + cm.setCursor(3, 0); + helpers.doEx('2,.s/\\d/0/g'); + eq('1\n0\n0\n0\n5', cm.getValue()); +}, { value: '1\n2\n3\n4\n5' }); +testVim('ex_substitute_range_offset', function(cm, vim, helpers) { + cm.setCursor(2, 0); + helpers.doEx('-1,+1s/\\d/0/g'); + eq('1\n0\n0\n0\n5', cm.getValue()); +}, { value: '1\n2\n3\n4\n5' }); +testVim('ex_substitute_range_implicit_offset', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doEx('.1,.3s/\\d/0/g'); + eq('1\n0\n0\n0\n5', cm.getValue()); +}, { value: '1\n2\n3\n4\n5' }); +testVim('ex_substitute_to_eof', function(cm, vim, helpers) { + cm.setCursor(2, 0); + helpers.doEx('.,$s/\\d/0/g'); + eq('1\n2\n0\n0\n0', cm.getValue()); +}, { value: '1\n2\n3\n4\n5' }); +testVim('ex_substitute_to_relative_eof', function(cm, vim, helpers) { + cm.setCursor(4, 0); + helpers.doEx('2,$-2s/\\d/0/g'); + eq('1\n0\n0\n4\n5', cm.getValue()); +}, { value: '1\n2\n3\n4\n5' }); +testVim('ex_substitute_range_mark', function(cm, vim, helpers) { + cm.setCursor(2, 0); + helpers.doKeys('ma'); + cm.setCursor(0, 0); + helpers.doEx('.,\'as/\\d/0/g'); + eq('0\n0\n0\n4\n5', cm.getValue()); +}, { value: '1\n2\n3\n4\n5' }); +testVim('ex_substitute_range_mark_offset', function(cm, vim, helpers) { + cm.setCursor(2, 0); + helpers.doKeys('ma'); + cm.setCursor(0, 0); + helpers.doEx('\'a-1,\'a+1s/\\d/0/g'); + eq('1\n0\n0\n0\n5', cm.getValue()); +}, { value: '1\n2\n3\n4\n5' }); +testVim('ex_substitute_visual_range', function(cm, vim, helpers) { + cm.setCursor(1, 0); + // Set last visual mode selection marks '< and '> at lines 2 and 4 + helpers.doKeys('V', '2', 'j', 'v'); + helpers.doEx('\'<,\'>s/\\d/0/g'); + eq('1\n0\n0\n0\n5', cm.getValue()); +}, { value: '1\n2\n3\n4\n5' }); +testVim('ex_substitute_empty_query', function(cm, vim, helpers) { + // If the query is empty, use last query. + cm.setCursor(1, 0); + cm.openDialog = helpers.fakeOpenDialog('1'); + helpers.doKeys('/'); + helpers.doEx('s//b/g'); + eq('abb ab2 ab3', cm.getValue()); +}, { value: 'a11 a12 a13' }); +testVim('ex_substitute_javascript', function(cm, vim, helpers) { + CodeMirror.Vim.setOption('pcre', false); + cm.setCursor(1, 0); + // Throw all the things that javascript likes to treat as special values + // into the replace part. All should be literal (this is VIM). + helpers.doEx('s/\\(\\d+\\)/$$ $\' $` $& \\1/g') + eq('a $$ $\' $` $& 0 b', cm.getValue()); +}, { value: 'a 0 b' }); +testVim('ex_substitute_empty_arguments', function(cm,vim,helpers) { + cm.setCursor(0, 0); + helpers.doEx('s/a/b/g'); + cm.setCursor(1, 0); + helpers.doEx('s'); + eq('b b\nb a', cm.getValue()); +}, {value: 'a a\na a'}); + +// More complex substitute tests that test both pcre and nopcre options. +function testSubstitute(name, options) { + testVim(name + '_pcre', function(cm, vim, helpers) { + cm.setCursor(1, 0); + CodeMirror.Vim.setOption('pcre', true); + helpers.doEx(options.expr); + eq(options.expectedValue, cm.getValue()); + }, options); + // If no noPcreExpr is defined, assume that it's the same as the expr. + var noPcreExpr = options.noPcreExpr ? options.noPcreExpr : options.expr; + testVim(name + '_nopcre', function(cm, vim, helpers) { + cm.setCursor(1, 0); + CodeMirror.Vim.setOption('pcre', false); + helpers.doEx(noPcreExpr); + eq(options.expectedValue, cm.getValue()); + }, options); +} +testSubstitute('ex_substitute_capture', { + value: 'a11 a12 a13', + expectedValue: 'a1111 a1212 a1313', + // $n is a backreference + expr: 's/(\\d+)/$1$1/g', + // \n is a backreference. + noPcreExpr: 's/\\(\\d+\\)/\\1\\1/g'}); +testSubstitute('ex_substitute_capture2', { + value: 'a 0 b', + expectedValue: 'a $00 b', + expr: 's/(\\d+)/$$$1$1/g', + noPcreExpr: 's/\\(\\d+\\)/$\\1\\1/g'}); +testSubstitute('ex_substitute_nocapture', { + value: 'a11 a12 a13', + expectedValue: 'a$1$1 a$1$1 a$1$1', + expr: 's/(\\d+)/$$1$$1/g', + noPcreExpr: 's/\\(\\d+\\)/$1$1/g'}); +testSubstitute('ex_substitute_nocapture2', { + value: 'a 0 b', + expectedValue: 'a $10 b', + expr: 's/(\\d+)/$$1$1/g', + noPcreExpr: 's/\\(\\d+\\)/\\$1\\1/g'}); +testSubstitute('ex_substitute_nocapture', { + value: 'a b c', + expectedValue: 'a $ c', + expr: 's/b/$$/', + noPcreExpr: 's/b/$/'}); +testSubstitute('ex_substitute_slash_regex', { + value: 'one/two \n three/four', + expectedValue: 'one|two \n three|four', + expr: '%s/\\//|'}); +testSubstitute('ex_substitute_pipe_regex', { + value: 'one|two \n three|four', + expectedValue: 'one,two \n three,four', + expr: '%s/\\|/,/', + noPcreExpr: '%s/|/,/'}); +testSubstitute('ex_substitute_or_regex', { + value: 'one|two \n three|four', + expectedValue: 'ana|twa \n thraa|faar', + expr: '%s/o|e|u/a/g', + noPcreExpr: '%s/o\\|e\\|u/a/g'}); +testSubstitute('ex_substitute_or_word_regex', { + value: 'one|two \n three|four', + expectedValue: 'five|five \n three|four', + expr: '%s/(one|two)/five/g', + noPcreExpr: '%s/\\(one\\|two\\)/five/g'}); +testSubstitute('ex_substitute_backslashslash_regex', { + value: 'one\\two \n three\\four', + expectedValue: 'one,two \n three,four', + expr: '%s/\\\\/,'}); +testSubstitute('ex_substitute_slash_replacement', { + value: 'one,two \n three,four', + expectedValue: 'one/two \n three/four', + expr: '%s/,/\\/'}); +testSubstitute('ex_substitute_backslash_replacement', { + value: 'one,two \n three,four', + expectedValue: 'one\\two \n three\\four', + expr: '%s/,/\\\\/g'}); +testSubstitute('ex_substitute_multibackslash_replacement', { + value: 'one,two \n three,four', + expectedValue: 'one\\\\\\\\two \n three\\\\\\\\four', // 2*8 backslashes. + expr: '%s/,/\\\\\\\\\\\\\\\\/g'}); // 16 backslashes. +testSubstitute('ex_substitute_dollar_match', { + value: 'one,two \n three,four', + expectedValue: 'one,two ,\n three,four', + expr: '%s/$/,/g'}); +testSubstitute('ex_substitute_newline_match', { + value: 'one,two \n three,four', + expectedValue: 'one,two , three,four', + expr: '%s/\\n/,/g'}); +testSubstitute('ex_substitute_newline_replacement', { + value: 'one,two \n three,four', + expectedValue: 'one\ntwo \n three\nfour', + expr: '%s/,/\\n/g'}); +testSubstitute('ex_substitute_braces_word', { + value: 'ababab abb ab{2}', + expectedValue: 'ab abb ab{2}', + expr: '%s/(ab){2}//g', + noPcreExpr: '%s/\\(ab\\)\\{2\\}//g'}); +testSubstitute('ex_substitute_braces_range', { + value: 'a aa aaa aaaa', + expectedValue: 'a a', + expr: '%s/a{2,3}//g', + noPcreExpr: '%s/a\\{2,3\\}//g'}); +testSubstitute('ex_substitute_braces_literal', { + value: 'ababab abb ab{2}', + expectedValue: 'ababab abb ', + expr: '%s/ab\\{2\\}//g', + noPcreExpr: '%s/ab{2}//g'}); +testSubstitute('ex_substitute_braces_char', { + value: 'ababab abb ab{2}', + expectedValue: 'ababab ab{2}', + expr: '%s/ab{2}//g', + noPcreExpr: '%s/ab\\{2\\}//g'}); +testSubstitute('ex_substitute_braces_no_escape', { + value: 'ababab abb ab{2}', + expectedValue: 'ababab ab{2}', + expr: '%s/ab{2}//g', + noPcreExpr: '%s/ab\\{2}//g'}); +testSubstitute('ex_substitute_count', { + value: '1\n2\n3\n4', + expectedValue: '1\n0\n0\n4', + expr: 's/\\d/0/i 2'}); +testSubstitute('ex_substitute_count_with_range', { + value: '1\n2\n3\n4', + expectedValue: '1\n2\n0\n0', + expr: '1,3s/\\d/0/ 3'}); +testSubstitute('ex_substitute_not_global', { + value: 'aaa\nbaa\ncaa', + expectedValue: 'xaa\nbxa\ncxa', + expr: '%s/a/x/'}); +function testSubstituteConfirm(name, command, initialValue, expectedValue, keys, finalPos) { + testVim(name, function(cm, vim, helpers) { + var savedOpenDialog = cm.openDialog; + var savedKeyName = CodeMirror.keyName; + var onKeyDown; + var recordedCallback; + var closed = true; // Start out closed, set false on second openDialog. + function close() { + closed = true; + } + // First openDialog should save callback. + cm.openDialog = function(template, callback, options) { + recordedCallback = callback; + } + // Do first openDialog. + helpers.doKeys(':'); + // Second openDialog should save keyDown handler. + cm.openDialog = function(template, callback, options) { + onKeyDown = options.onKeyDown; + closed = false; + }; + // Return the command to Vim and trigger second openDialog. + recordedCallback(command); + // The event should really use keyCode, but here just mock it out and use + // key and replace keyName to just return key. + CodeMirror.keyName = function (e) { return e.key; } + keys = keys.toUpperCase(); + for (var i = 0; i < keys.length; i++) { + is(!closed); + onKeyDown({ key: keys.charAt(i) }, '', close); + } + try { + eq(expectedValue, cm.getValue()); + helpers.assertCursorAt(finalPos); + is(closed); + } catch(e) { + throw e + } finally { + // Restore overridden functions. + CodeMirror.keyName = savedKeyName; + cm.openDialog = savedOpenDialog; + } + }, { value: initialValue }); +}; +testSubstituteConfirm('ex_substitute_confirm_emptydoc', + '%s/x/b/c', '', '', '', makeCursor(0, 0)); +testSubstituteConfirm('ex_substitute_confirm_nomatch', + '%s/x/b/c', 'ba a\nbab', 'ba a\nbab', '', makeCursor(0, 0)); +testSubstituteConfirm('ex_substitute_confirm_accept', + '%s/a/b/cg', 'ba a\nbab', 'bb b\nbbb', 'yyy', makeCursor(1, 1)); +testSubstituteConfirm('ex_substitute_confirm_random_keys', + '%s/a/b/cg', 'ba a\nbab', 'bb b\nbbb', 'ysdkywerty', makeCursor(1, 1)); +testSubstituteConfirm('ex_substitute_confirm_some', + '%s/a/b/cg', 'ba a\nbab', 'bb a\nbbb', 'yny', makeCursor(1, 1)); +testSubstituteConfirm('ex_substitute_confirm_all', + '%s/a/b/cg', 'ba a\nbab', 'bb b\nbbb', 'a', makeCursor(1, 1)); +testSubstituteConfirm('ex_substitute_confirm_accept_then_all', + '%s/a/b/cg', 'ba a\nbab', 'bb b\nbbb', 'ya', makeCursor(1, 1)); +testSubstituteConfirm('ex_substitute_confirm_quit', + '%s/a/b/cg', 'ba a\nbab', 'bb a\nbab', 'yq', makeCursor(0, 3)); +testSubstituteConfirm('ex_substitute_confirm_last', + '%s/a/b/cg', 'ba a\nbab', 'bb b\nbab', 'yl', makeCursor(0, 3)); +testSubstituteConfirm('ex_substitute_confirm_oneline', + '1s/a/b/cg', 'ba a\nbab', 'bb b\nbab', 'yl', makeCursor(0, 3)); +testSubstituteConfirm('ex_substitute_confirm_range_accept', + '1,2s/a/b/cg', 'aa\na \na\na', 'bb\nb \na\na', 'yyy', makeCursor(1, 0)); +testSubstituteConfirm('ex_substitute_confirm_range_some', + '1,3s/a/b/cg', 'aa\na \na\na', 'ba\nb \nb\na', 'ynyy', makeCursor(2, 0)); +testSubstituteConfirm('ex_substitute_confirm_range_all', + '1,3s/a/b/cg', 'aa\na \na\na', 'bb\nb \nb\na', 'a', makeCursor(2, 0)); +testSubstituteConfirm('ex_substitute_confirm_range_last', + '1,3s/a/b/cg', 'aa\na \na\na', 'bb\nb \na\na', 'yyl', makeCursor(1, 0)); +//:noh should clear highlighting of search-results but allow to resume search through n +testVim('ex_noh_clearSearchHighlight', function(cm, vim, helpers) { + cm.openDialog = helpers.fakeOpenDialog('match'); + helpers.doKeys('?'); + helpers.doEx('noh'); + eq(vim.searchState_.getOverlay(),null,'match-highlighting wasn\'t cleared'); + helpers.doKeys('n'); + helpers.assertCursorAt(0, 11,'can\'t resume search after clearing highlighting'); +}, { value: 'match nope match \n nope Match' }); +testVim('ex_yank', function (cm, vim, helpers) { + var curStart = makeCursor(3, 0); + cm.setCursor(curStart); + helpers.doEx('y'); + var register = helpers.getRegisterController().getRegister(); + var line = cm.getLine(3); + eq(line + '\n', register.toString()); +}); +testVim('set_boolean', function(cm, vim, helpers) { + CodeMirror.Vim.defineOption('testoption', true, 'boolean'); + // Test default value is set. + is(CodeMirror.Vim.getOption('testoption')); + try { + // Test fail to set to non-boolean + CodeMirror.Vim.setOption('testoption', '5'); + fail(); + } catch (expected) {} + // Test setOption + CodeMirror.Vim.setOption('testoption', false); + is(!CodeMirror.Vim.getOption('testoption')); +}); +testVim('ex_set_boolean', function(cm, vim, helpers) { + CodeMirror.Vim.defineOption('testoption', true, 'boolean'); + // Test default value is set. + is(CodeMirror.Vim.getOption('testoption')); + try { + // Test fail to set to non-boolean + helpers.doEx('set testoption=22'); + fail(); + } catch (expected) {} + // Test setOption + helpers.doEx('set notestoption'); + is(!CodeMirror.Vim.getOption('testoption')); +}); +testVim('set_string', function(cm, vim, helpers) { + CodeMirror.Vim.defineOption('testoption', 'a', 'string'); + // Test default value is set. + eq('a', CodeMirror.Vim.getOption('testoption')); + try { + // Test fail to set non-string. + CodeMirror.Vim.setOption('testoption', true); + fail(); + } catch (expected) {} + try { + // Test fail to set 'notestoption' + CodeMirror.Vim.setOption('notestoption', 'b'); + fail(); + } catch (expected) {} + // Test setOption + CodeMirror.Vim.setOption('testoption', 'c'); + eq('c', CodeMirror.Vim.getOption('testoption')); +}); +testVim('ex_set_string', function(cm, vim, helpers) { + CodeMirror.Vim.defineOption('testopt', 'a', 'string'); + // Test default value is set. + eq('a', CodeMirror.Vim.getOption('testopt')); + try { + // Test fail to set 'notestopt' + helpers.doEx('set notestopt=b'); + fail(); + } catch (expected) {} + // Test setOption + helpers.doEx('set testopt=c') + eq('c', CodeMirror.Vim.getOption('testopt')); + helpers.doEx('set testopt=c') + eq('c', CodeMirror.Vim.getOption('testopt', cm)); //local || global + eq('c', CodeMirror.Vim.getOption('testopt', cm, {scope: 'local'})); // local + eq('c', CodeMirror.Vim.getOption('testopt', cm, {scope: 'global'})); // global + eq('c', CodeMirror.Vim.getOption('testopt')); // global + // Test setOption global + helpers.doEx('setg testopt=d') + eq('c', CodeMirror.Vim.getOption('testopt', cm)); + eq('c', CodeMirror.Vim.getOption('testopt', cm, {scope: 'local'})); + eq('d', CodeMirror.Vim.getOption('testopt', cm, {scope: 'global'})); + eq('d', CodeMirror.Vim.getOption('testopt')); + // Test setOption local + helpers.doEx('setl testopt=e') + eq('e', CodeMirror.Vim.getOption('testopt', cm)); + eq('e', CodeMirror.Vim.getOption('testopt', cm, {scope: 'local'})); + eq('d', CodeMirror.Vim.getOption('testopt', cm, {scope: 'global'})); + eq('d', CodeMirror.Vim.getOption('testopt')); +}); +testVim('ex_set_callback', function(cm, vim, helpers) { + var global; + + function cb(val, cm, cfg) { + if (val === undefined) { + // Getter + if (cm) { + return cm._local; + } else { + return global; + } + } else { + // Setter + if (cm) { + cm._local = val; + } else { + global = val; + } + } + } + + CodeMirror.Vim.defineOption('testopt', 'a', 'string', cb); + // Test default value is set. + eq('a', CodeMirror.Vim.getOption('testopt')); + try { + // Test fail to set 'notestopt' + helpers.doEx('set notestopt=b'); + fail(); + } catch (expected) {} + // Test setOption (Identical to the string tests, but via callback instead) + helpers.doEx('set testopt=c') + eq('c', CodeMirror.Vim.getOption('testopt', cm)); //local || global + eq('c', CodeMirror.Vim.getOption('testopt', cm, {scope: 'local'})); // local + eq('c', CodeMirror.Vim.getOption('testopt', cm, {scope: 'global'})); // global + eq('c', CodeMirror.Vim.getOption('testopt')); // global + // Test setOption global + helpers.doEx('setg testopt=d') + eq('c', CodeMirror.Vim.getOption('testopt', cm)); + eq('c', CodeMirror.Vim.getOption('testopt', cm, {scope: 'local'})); + eq('d', CodeMirror.Vim.getOption('testopt', cm, {scope: 'global'})); + eq('d', CodeMirror.Vim.getOption('testopt')); + // Test setOption local + helpers.doEx('setl testopt=e') + eq('e', CodeMirror.Vim.getOption('testopt', cm)); + eq('e', CodeMirror.Vim.getOption('testopt', cm, {scope: 'local'})); + eq('d', CodeMirror.Vim.getOption('testopt', cm, {scope: 'global'})); + eq('d', CodeMirror.Vim.getOption('testopt')); +}) +testVim('ex_set_filetype', function(cm, vim, helpers) { + CodeMirror.defineMode('test_mode', function() { + return {token: function(stream) { + stream.match(/^\s+|^\S+/); + }}; + }); + CodeMirror.defineMode('test_mode_2', function() { + return {token: function(stream) { + stream.match(/^\s+|^\S+/); + }}; + }); + // Test mode is set. + helpers.doEx('set filetype=test_mode'); + eq('test_mode', cm.getMode().name); + // Test 'ft' alias also sets mode. + helpers.doEx('set ft=test_mode_2'); + eq('test_mode_2', cm.getMode().name); +}); +testVim('ex_set_filetype_null', function(cm, vim, helpers) { + CodeMirror.defineMode('test_mode', function() { + return {token: function(stream) { + stream.match(/^\s+|^\S+/); + }}; + }); + cm.setOption('mode', 'test_mode'); + // Test mode is set to null. + helpers.doEx('set filetype='); + eq('null', cm.getMode().name); +}); +// TODO: Reset key maps after each test. +testVim('ex_map_key2key', function(cm, vim, helpers) { + helpers.doEx('map a x'); + helpers.doKeys('a'); + helpers.assertCursorAt(0, 0); + eq('bc', cm.getValue()); +}, { value: 'abc' }); +testVim('ex_unmap_key2key', function(cm, vim, helpers) { + helpers.doEx('unmap a'); + helpers.doKeys('a'); + eq('vim-insert', cm.getOption('keyMap')); +}, { value: 'abc' }); +testVim('ex_unmap_key2key_does_not_remove_default', function(cm, vim, helpers) { + try { + helpers.doEx('unmap a'); + fail(); + } catch (expected) {} + helpers.doKeys('a'); + eq('vim-insert', cm.getOption('keyMap')); +}, { value: 'abc' }); +testVim('ex_map_key2key_to_colon', function(cm, vim, helpers) { + helpers.doEx('map ; :'); + var dialogOpened = false; + cm.openDialog = function() { + dialogOpened = true; + } + helpers.doKeys(';'); + eq(dialogOpened, true); +}); +testVim('ex_map_ex2key:', function(cm, vim, helpers) { + helpers.doEx('map :del x'); + helpers.doEx('del'); + helpers.assertCursorAt(0, 0); + eq('bc', cm.getValue()); +}, { value: 'abc' }); +testVim('ex_map_ex2ex', function(cm, vim, helpers) { + helpers.doEx('map :del :w'); + var tmp = CodeMirror.commands.save; + var written = false; + var actualCm; + CodeMirror.commands.save = function(cm) { + written = true; + actualCm = cm; + }; + helpers.doEx('del'); + CodeMirror.commands.save = tmp; + eq(written, true); + eq(actualCm, cm); +}); +testVim('ex_map_key2ex', function(cm, vim, helpers) { + helpers.doEx('map a :w'); + var tmp = CodeMirror.commands.save; + var written = false; + var actualCm; + CodeMirror.commands.save = function(cm) { + written = true; + actualCm = cm; + }; + helpers.doKeys('a'); + CodeMirror.commands.save = tmp; + eq(written, true); + eq(actualCm, cm); +}); +testVim('ex_map_key2key_visual_api', function(cm, vim, helpers) { + CodeMirror.Vim.map('b', ':w', 'visual'); + var tmp = CodeMirror.commands.save; + var written = false; + var actualCm; + CodeMirror.commands.save = function(cm) { + written = true; + actualCm = cm; + }; + // Mapping should not work in normal mode. + helpers.doKeys('b'); + eq(written, false); + // Mapping should work in visual mode. + helpers.doKeys('v', 'b'); + eq(written, true); + eq(actualCm, cm); + + CodeMirror.commands.save = tmp; +}); +testVim('ex_imap', function(cm, vim, helpers) { + CodeMirror.Vim.map('jk', '<Esc>', 'insert'); + helpers.doKeys('i'); + is(vim.insertMode); + helpers.doKeys('j', 'k'); + is(!vim.insertMode); + cm.setCursor(0, 1); + CodeMirror.Vim.map('jj', '<Esc>', 'insert'); + helpers.doKeys('<C-v>', '2', 'j', 'l', 'c'); + var replacement = fillArray('fo', 3); + cm.replaceSelections(replacement); + eq('1fo4\n5fo8\nafodefg', cm.getValue()); + helpers.doKeys('j', 'j'); + cm.setCursor(0, 0); + helpers.doKeys('.'); + eq('foo4\nfoo8\nfoodefg', cm.getValue()); +}, { value: '1234\n5678\nabcdefg' }); +testVim('ex_unmap_api', function(cm, vim, helpers) { + CodeMirror.Vim.map('<Alt-X>', 'gg', 'normal'); + is(CodeMirror.Vim.handleKey(cm, "<Alt-X>", "normal"), "Alt-X key is mapped"); + CodeMirror.Vim.unmap("<Alt-X>", "normal"); + is(!CodeMirror.Vim.handleKey(cm, "<Alt-X>", "normal"), "Alt-X key is unmapped"); +}); + +// Testing registration of functions as ex-commands and mapping to <Key>-keys +testVim('ex_api_test', function(cm, vim, helpers) { + var res=false; + var val='from'; + CodeMirror.Vim.defineEx('extest','ext',function(cm,params){ + if(params.args)val=params.args[0]; + else res=true; + }); + helpers.doEx(':ext to'); + eq(val,'to','Defining ex-command failed'); + CodeMirror.Vim.map('<C-CR><Space>',':ext'); + helpers.doKeys('<C-CR>','<Space>'); + is(res,'Mapping to key failed'); +}); +// For now, this test needs to be last because it messes up : for future tests. +testVim('ex_map_key2key_from_colon', function(cm, vim, helpers) { + helpers.doEx('map : x'); + helpers.doKeys(':'); + helpers.assertCursorAt(0, 0); + eq('bc', cm.getValue()); +}, { value: 'abc' }); + +// Test event handlers +testVim('beforeSelectionChange', function(cm, vim, helpers) { + cm.setCursor(0, 100); + eqCursorPos(cm.getCursor('head'), cm.getCursor('anchor')); +}, { value: 'abc' }); + + diff --git a/modules/editor/codemirror/theme/3024-day.css b/modules/editor/codemirror/theme/3024-day.css @@ -0,0 +1,41 @@ +/* + + Name: 3024 day + Author: Jan T. Sott (http://github.com/idleberg) + + CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror) + Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16) + +*/ + +.cm-s-3024-day.CodeMirror { background: #f7f7f7; color: #3a3432; } +.cm-s-3024-day div.CodeMirror-selected { background: #d6d5d4; } + +.cm-s-3024-day .CodeMirror-line::selection, .cm-s-3024-day .CodeMirror-line > span::selection, .cm-s-3024-day .CodeMirror-line > span > span::selection { background: #d6d5d4; } +.cm-s-3024-day .CodeMirror-line::-moz-selection, .cm-s-3024-day .CodeMirror-line > span::-moz-selection, .cm-s-3024-day .CodeMirror-line > span > span::selection { background: #d9d9d9; } + +.cm-s-3024-day .CodeMirror-gutters { background: #f7f7f7; border-right: 0px; } +.cm-s-3024-day .CodeMirror-guttermarker { color: #db2d20; } +.cm-s-3024-day .CodeMirror-guttermarker-subtle { color: #807d7c; } +.cm-s-3024-day .CodeMirror-linenumber { color: #807d7c; } + +.cm-s-3024-day .CodeMirror-cursor { border-left: 1px solid #5c5855; } + +.cm-s-3024-day span.cm-comment { color: #cdab53; } +.cm-s-3024-day span.cm-atom { color: #a16a94; } +.cm-s-3024-day span.cm-number { color: #a16a94; } + +.cm-s-3024-day span.cm-property, .cm-s-3024-day span.cm-attribute { color: #01a252; } +.cm-s-3024-day span.cm-keyword { color: #db2d20; } +.cm-s-3024-day span.cm-string { color: #fded02; } + +.cm-s-3024-day span.cm-variable { color: #01a252; } +.cm-s-3024-day span.cm-variable-2 { color: #01a0e4; } +.cm-s-3024-day span.cm-def { color: #e8bbd0; } +.cm-s-3024-day span.cm-bracket { color: #3a3432; } +.cm-s-3024-day span.cm-tag { color: #db2d20; } +.cm-s-3024-day span.cm-link { color: #a16a94; } +.cm-s-3024-day span.cm-error { background: #db2d20; color: #5c5855; } + +.cm-s-3024-day .CodeMirror-activeline-background { background: #e8f2ff; } +.cm-s-3024-day .CodeMirror-matchingbracket { text-decoration: underline; color: #a16a94 !important; } diff --git a/modules/editor/codemirror/theme/ambiance-mobile.css b/modules/editor/codemirror/theme/ambiance-mobile.css @@ -0,0 +1,5 @@ +.cm-s-ambiance.CodeMirror { + -webkit-box-shadow: none; + -moz-box-shadow: none; + box-shadow: none; +} diff --git a/modules/editor/codemirror/theme/cobalt.css b/modules/editor/codemirror/theme/cobalt.css @@ -0,0 +1,25 @@ +.cm-s-cobalt.CodeMirror { background: #002240; color: white; } +.cm-s-cobalt div.CodeMirror-selected { background: #b36539; } +.cm-s-cobalt .CodeMirror-line::selection, .cm-s-cobalt .CodeMirror-line > span::selection, .cm-s-cobalt .CodeMirror-line > span > span::selection { background: rgba(179, 101, 57, .99); } +.cm-s-cobalt .CodeMirror-line::-moz-selection, .cm-s-cobalt .CodeMirror-line > span::-moz-selection, .cm-s-cobalt .CodeMirror-line > span > span::-moz-selection { background: rgba(179, 101, 57, .99); } +.cm-s-cobalt .CodeMirror-gutters { background: #002240; border-right: 1px solid #aaa; } +.cm-s-cobalt .CodeMirror-guttermarker { color: #ffee80; } +.cm-s-cobalt .CodeMirror-guttermarker-subtle { color: #d0d0d0; } +.cm-s-cobalt .CodeMirror-linenumber { color: #d0d0d0; } +.cm-s-cobalt .CodeMirror-cursor { border-left: 1px solid white; } + +.cm-s-cobalt span.cm-comment { color: #08f; } +.cm-s-cobalt span.cm-atom { color: #845dc4; } +.cm-s-cobalt span.cm-number, .cm-s-cobalt span.cm-attribute { color: #ff80e1; } +.cm-s-cobalt span.cm-keyword { color: #ffee80; } +.cm-s-cobalt span.cm-string { color: #3ad900; } +.cm-s-cobalt span.cm-meta { color: #ff9d00; } +.cm-s-cobalt span.cm-variable-2, .cm-s-cobalt span.cm-tag { color: #9effff; } +.cm-s-cobalt span.cm-variable-3, .cm-s-cobalt span.cm-def, .cm-s-cobalt .cm-type { color: white; } +.cm-s-cobalt span.cm-bracket { color: #d8d8d8; } +.cm-s-cobalt span.cm-builtin, .cm-s-cobalt span.cm-special { color: #ff9e59; } +.cm-s-cobalt span.cm-link { color: #845dc4; } +.cm-s-cobalt span.cm-error { color: #9d1e15; } + +.cm-s-cobalt .CodeMirror-activeline-background { background: #002D57; } +.cm-s-cobalt .CodeMirror-matchingbracket { outline:1px solid grey;color:white !important; } diff --git a/modules/editor/codemirror/theme/eclipse.css b/modules/editor/codemirror/theme/eclipse.css @@ -0,0 +1,23 @@ +.cm-s-eclipse span.cm-meta { color: #FF1717; } +.cm-s-eclipse span.cm-keyword { line-height: 1em; font-weight: bold; color: #7F0055; } +.cm-s-eclipse span.cm-atom { color: #219; } +.cm-s-eclipse span.cm-number { color: #164; } +.cm-s-eclipse span.cm-def { color: #00f; } +.cm-s-eclipse span.cm-variable { color: black; } +.cm-s-eclipse span.cm-variable-2 { color: #0000C0; } +.cm-s-eclipse span.cm-variable-3, .cm-s-eclipse span.cm-type { color: #0000C0; } +.cm-s-eclipse span.cm-property { color: black; } +.cm-s-eclipse span.cm-operator { color: black; } +.cm-s-eclipse span.cm-comment { color: #3F7F5F; } +.cm-s-eclipse span.cm-string { color: #2A00FF; } +.cm-s-eclipse span.cm-string-2 { color: #f50; } +.cm-s-eclipse span.cm-qualifier { color: #555; } +.cm-s-eclipse span.cm-builtin { color: #30a; } +.cm-s-eclipse span.cm-bracket { color: #cc7; } +.cm-s-eclipse span.cm-tag { color: #170; } +.cm-s-eclipse span.cm-attribute { color: #00c; } +.cm-s-eclipse span.cm-link { color: #219; } +.cm-s-eclipse span.cm-error { color: #f00; } + +.cm-s-eclipse .CodeMirror-activeline-background { background: #e8f2ff; } +.cm-s-eclipse .CodeMirror-matchingbracket { outline:1px solid grey; color:black !important; } diff --git a/modules/editor/codemirror/theme/elegant.css b/modules/editor/codemirror/theme/elegant.css @@ -0,0 +1,13 @@ +.cm-s-elegant span.cm-number, .cm-s-elegant span.cm-string, .cm-s-elegant span.cm-atom { color: #762; } +.cm-s-elegant span.cm-comment { color: #262; font-style: italic; line-height: 1em; } +.cm-s-elegant span.cm-meta { color: #555; font-style: italic; line-height: 1em; } +.cm-s-elegant span.cm-variable { color: black; } +.cm-s-elegant span.cm-variable-2 { color: #b11; } +.cm-s-elegant span.cm-qualifier { color: #555; } +.cm-s-elegant span.cm-keyword { color: #730; } +.cm-s-elegant span.cm-builtin { color: #30a; } +.cm-s-elegant span.cm-link { color: #762; } +.cm-s-elegant span.cm-error { background-color: #fdd; } + +.cm-s-elegant .CodeMirror-activeline-background { background: #e8f2ff; } +.cm-s-elegant .CodeMirror-matchingbracket { outline:1px solid grey; color:black !important; } diff --git a/modules/editor/codemirror/theme/erlang-dark.css b/modules/editor/codemirror/theme/erlang-dark.css @@ -0,0 +1,34 @@ +.cm-s-erlang-dark.CodeMirror { background: #002240; color: white; } +.cm-s-erlang-dark div.CodeMirror-selected { background: #b36539; } +.cm-s-erlang-dark .CodeMirror-line::selection, .cm-s-erlang-dark .CodeMirror-line > span::selection, .cm-s-erlang-dark .CodeMirror-line > span > span::selection { background: rgba(179, 101, 57, .99); } +.cm-s-erlang-dark .CodeMirror-line::-moz-selection, .cm-s-erlang-dark .CodeMirror-line > span::-moz-selection, .cm-s-erlang-dark .CodeMirror-line > span > span::-moz-selection { background: rgba(179, 101, 57, .99); } +.cm-s-erlang-dark .CodeMirror-gutters { background: #002240; border-right: 1px solid #aaa; } +.cm-s-erlang-dark .CodeMirror-guttermarker { color: white; } +.cm-s-erlang-dark .CodeMirror-guttermarker-subtle { color: #d0d0d0; } +.cm-s-erlang-dark .CodeMirror-linenumber { color: #d0d0d0; } +.cm-s-erlang-dark .CodeMirror-cursor { border-left: 1px solid white; } + +.cm-s-erlang-dark span.cm-quote { color: #ccc; } +.cm-s-erlang-dark span.cm-atom { color: #f133f1; } +.cm-s-erlang-dark span.cm-attribute { color: #ff80e1; } +.cm-s-erlang-dark span.cm-bracket { color: #ff9d00; } +.cm-s-erlang-dark span.cm-builtin { color: #eaa; } +.cm-s-erlang-dark span.cm-comment { color: #77f; } +.cm-s-erlang-dark span.cm-def { color: #e7a; } +.cm-s-erlang-dark span.cm-keyword { color: #ffee80; } +.cm-s-erlang-dark span.cm-meta { color: #50fefe; } +.cm-s-erlang-dark span.cm-number { color: #ffd0d0; } +.cm-s-erlang-dark span.cm-operator { color: #d55; } +.cm-s-erlang-dark span.cm-property { color: #ccc; } +.cm-s-erlang-dark span.cm-qualifier { color: #ccc; } +.cm-s-erlang-dark span.cm-special { color: #ffbbbb; } +.cm-s-erlang-dark span.cm-string { color: #3ad900; } +.cm-s-erlang-dark span.cm-string-2 { color: #ccc; } +.cm-s-erlang-dark span.cm-tag { color: #9effff; } +.cm-s-erlang-dark span.cm-variable { color: #50fe50; } +.cm-s-erlang-dark span.cm-variable-2 { color: #e0e; } +.cm-s-erlang-dark span.cm-variable-3, .cm-s-erlang-dark span.cm-type { color: #ccc; } +.cm-s-erlang-dark span.cm-error { color: #9d1e15; } + +.cm-s-erlang-dark .CodeMirror-activeline-background { background: #013461; } +.cm-s-erlang-dark .CodeMirror-matchingbracket { outline:1px solid grey; color:white !important; } diff --git a/modules/editor/codemirror/theme/hopscotch.css b/modules/editor/codemirror/theme/hopscotch.css @@ -0,0 +1,34 @@ +/* + + Name: Hopscotch + Author: Jan T. Sott + + CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror) + Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16) + +*/ + +.cm-s-hopscotch.CodeMirror {background: #322931; color: #d5d3d5;} +.cm-s-hopscotch div.CodeMirror-selected {background: #433b42 !important;} +.cm-s-hopscotch .CodeMirror-gutters {background: #322931; border-right: 0px;} +.cm-s-hopscotch .CodeMirror-linenumber {color: #797379;} +.cm-s-hopscotch .CodeMirror-cursor {border-left: 1px solid #989498 !important;} + +.cm-s-hopscotch span.cm-comment {color: #b33508;} +.cm-s-hopscotch span.cm-atom {color: #c85e7c;} +.cm-s-hopscotch span.cm-number {color: #c85e7c;} + +.cm-s-hopscotch span.cm-property, .cm-s-hopscotch span.cm-attribute {color: #8fc13e;} +.cm-s-hopscotch span.cm-keyword {color: #dd464c;} +.cm-s-hopscotch span.cm-string {color: #fdcc59;} + +.cm-s-hopscotch span.cm-variable {color: #8fc13e;} +.cm-s-hopscotch span.cm-variable-2 {color: #1290bf;} +.cm-s-hopscotch span.cm-def {color: #fd8b19;} +.cm-s-hopscotch span.cm-error {background: #dd464c; color: #989498;} +.cm-s-hopscotch span.cm-bracket {color: #d5d3d5;} +.cm-s-hopscotch span.cm-tag {color: #dd464c;} +.cm-s-hopscotch span.cm-link {color: #c85e7c;} + +.cm-s-hopscotch .CodeMirror-matchingbracket { text-decoration: underline; color: white !important;} +.cm-s-hopscotch .CodeMirror-activeline-background { background: #302020; } diff --git a/modules/editor/codemirror/theme/liquibyte.css b/modules/editor/codemirror/theme/liquibyte.css @@ -0,0 +1,95 @@ +.cm-s-liquibyte.CodeMirror { + background-color: #000; + color: #fff; + line-height: 1.2em; + font-size: 1em; +} +.cm-s-liquibyte .CodeMirror-focused .cm-matchhighlight { + text-decoration: underline; + text-decoration-color: #0f0; + text-decoration-style: wavy; +} +.cm-s-liquibyte .cm-trailingspace { + text-decoration: line-through; + text-decoration-color: #f00; + text-decoration-style: dotted; +} +.cm-s-liquibyte .cm-tab { + text-decoration: line-through; + text-decoration-color: #404040; + text-decoration-style: dotted; +} +.cm-s-liquibyte .CodeMirror-gutters { background-color: #262626; border-right: 1px solid #505050; padding-right: 0.8em; } +.cm-s-liquibyte .CodeMirror-gutter-elt div { font-size: 1.2em; } +.cm-s-liquibyte .CodeMirror-guttermarker { } +.cm-s-liquibyte .CodeMirror-guttermarker-subtle { } +.cm-s-liquibyte .CodeMirror-linenumber { color: #606060; padding-left: 0; } +.cm-s-liquibyte .CodeMirror-cursor { border-left: 1px solid #eee; } + +.cm-s-liquibyte span.cm-comment { color: #008000; } +.cm-s-liquibyte span.cm-def { color: #ffaf40; font-weight: bold; } +.cm-s-liquibyte span.cm-keyword { color: #c080ff; font-weight: bold; } +.cm-s-liquibyte span.cm-builtin { color: #ffaf40; font-weight: bold; } +.cm-s-liquibyte span.cm-variable { color: #5967ff; font-weight: bold; } +.cm-s-liquibyte span.cm-string { color: #ff8000; } +.cm-s-liquibyte span.cm-number { color: #0f0; font-weight: bold; } +.cm-s-liquibyte span.cm-atom { color: #bf3030; font-weight: bold; } + +.cm-s-liquibyte span.cm-variable-2 { color: #007f7f; font-weight: bold; } +.cm-s-liquibyte span.cm-variable-3, .cm-s-liquibyte span.cm-type { color: #c080ff; font-weight: bold; } +.cm-s-liquibyte span.cm-property { color: #999; font-weight: bold; } +.cm-s-liquibyte span.cm-operator { color: #fff; } + +.cm-s-liquibyte span.cm-meta { color: #0f0; } +.cm-s-liquibyte span.cm-qualifier { color: #fff700; font-weight: bold; } +.cm-s-liquibyte span.cm-bracket { color: #cc7; } +.cm-s-liquibyte span.cm-tag { color: #ff0; font-weight: bold; } +.cm-s-liquibyte span.cm-attribute { color: #c080ff; font-weight: bold; } +.cm-s-liquibyte span.cm-error { color: #f00; } + +.cm-s-liquibyte div.CodeMirror-selected { background-color: rgba(255, 0, 0, 0.25); } + +.cm-s-liquibyte span.cm-compilation { background-color: rgba(255, 255, 255, 0.12); } + +.cm-s-liquibyte .CodeMirror-activeline-background { background-color: rgba(0, 255, 0, 0.15); } + +/* Default styles for common addons */ +.cm-s-liquibyte .CodeMirror span.CodeMirror-matchingbracket { color: #0f0; font-weight: bold; } +.cm-s-liquibyte .CodeMirror span.CodeMirror-nonmatchingbracket { color: #f00; font-weight: bold; } +.CodeMirror-matchingtag { background-color: rgba(150, 255, 0, .3); } +/* Scrollbars */ +/* Simple */ +.cm-s-liquibyte div.CodeMirror-simplescroll-horizontal div:hover, .cm-s-liquibyte div.CodeMirror-simplescroll-vertical div:hover { + background-color: rgba(80, 80, 80, .7); +} +.cm-s-liquibyte div.CodeMirror-simplescroll-horizontal div, .cm-s-liquibyte div.CodeMirror-simplescroll-vertical div { + background-color: rgba(80, 80, 80, .3); + border: 1px solid #404040; + border-radius: 5px; +} +.cm-s-liquibyte div.CodeMirror-simplescroll-vertical div { + border-top: 1px solid #404040; + border-bottom: 1px solid #404040; +} +.cm-s-liquibyte div.CodeMirror-simplescroll-horizontal div { + border-left: 1px solid #404040; + border-right: 1px solid #404040; +} +.cm-s-liquibyte div.CodeMirror-simplescroll-vertical { + background-color: #262626; +} +.cm-s-liquibyte div.CodeMirror-simplescroll-horizontal { + background-color: #262626; + border-top: 1px solid #404040; +} +/* Overlay */ +.cm-s-liquibyte div.CodeMirror-overlayscroll-horizontal div, div.CodeMirror-overlayscroll-vertical div { + background-color: #404040; + border-radius: 5px; +} +.cm-s-liquibyte div.CodeMirror-overlayscroll-vertical div { + border: 1px solid #404040; +} +.cm-s-liquibyte div.CodeMirror-overlayscroll-horizontal div { + border: 1px solid #404040; +} diff --git a/modules/editor/codemirror/theme/material.css b/modules/editor/codemirror/theme/material.css @@ -0,0 +1,53 @@ +/* + + Name: material + Author: Michael Kaminsky (http://github.com/mkaminsky11) + + Original material color scheme by Mattia Astorino (https://github.com/equinusocio/material-theme) + +*/ + +.cm-s-material.CodeMirror { + background-color: #263238; + color: rgba(233, 237, 237, 1); +} +.cm-s-material .CodeMirror-gutters { + background: #263238; + color: rgb(83,127,126); + border: none; +} +.cm-s-material .CodeMirror-guttermarker, .cm-s-material .CodeMirror-guttermarker-subtle, .cm-s-material .CodeMirror-linenumber { color: rgb(83,127,126); } +.cm-s-material .CodeMirror-cursor { border-left: 1px solid #f8f8f0; } +.cm-s-material div.CodeMirror-selected { background: rgba(255, 255, 255, 0.15); } +.cm-s-material.CodeMirror-focused div.CodeMirror-selected { background: rgba(255, 255, 255, 0.10); } +.cm-s-material .CodeMirror-line::selection, .cm-s-material .CodeMirror-line > span::selection, .cm-s-material .CodeMirror-line > span > span::selection { background: rgba(255, 255, 255, 0.10); } +.cm-s-material .CodeMirror-line::-moz-selection, .cm-s-material .CodeMirror-line > span::-moz-selection, .cm-s-material .CodeMirror-line > span > span::-moz-selection { background: rgba(255, 255, 255, 0.10); } + +.cm-s-material .CodeMirror-activeline-background { background: rgba(0, 0, 0, 0); } +.cm-s-material .cm-keyword { color: rgba(199, 146, 234, 1); } +.cm-s-material .cm-operator { color: rgba(233, 237, 237, 1); } +.cm-s-material .cm-variable-2 { color: #80CBC4; } +.cm-s-material .cm-variable-3, .cm-s-material .cm-type { color: #82B1FF; } +.cm-s-material .cm-builtin { color: #DECB6B; } +.cm-s-material .cm-atom { color: #F77669; } +.cm-s-material .cm-number { color: #F77669; } +.cm-s-material .cm-def { color: rgba(233, 237, 237, 1); } +.cm-s-material .cm-string { color: #C3E88D; } +.cm-s-material .cm-string-2 { color: #80CBC4; } +.cm-s-material .cm-comment { color: #546E7A; } +.cm-s-material .cm-variable { color: #82B1FF; } +.cm-s-material .cm-tag { color: #80CBC4; } +.cm-s-material .cm-meta { color: #80CBC4; } +.cm-s-material .cm-attribute { color: #FFCB6B; } +.cm-s-material .cm-property { color: #80CBAE; } +.cm-s-material .cm-qualifier { color: #DECB6B; } +.cm-s-material .cm-variable-3, .cm-s-material .cm-type { color: #DECB6B; } +.cm-s-material .cm-tag { color: rgba(255, 83, 112, 1); } +.cm-s-material .cm-error { + color: rgba(255, 255, 255, 1.0); + background-color: #EC5F67; +} +.cm-s-material .CodeMirror-matchingbracket { + text-decoration: underline; + color: white !important; +} diff --git a/modules/editor/codemirror/theme/night.css b/modules/editor/codemirror/theme/night.css @@ -0,0 +1,27 @@ +/* Loosely based on the Midnight Textmate theme */ + +.cm-s-night.CodeMirror { background: #0a001f; color: #f8f8f8; } +.cm-s-night div.CodeMirror-selected { background: #447; } +.cm-s-night .CodeMirror-line::selection, .cm-s-night .CodeMirror-line > span::selection, .cm-s-night .CodeMirror-line > span > span::selection { background: rgba(68, 68, 119, .99); } +.cm-s-night .CodeMirror-line::-moz-selection, .cm-s-night .CodeMirror-line > span::-moz-selection, .cm-s-night .CodeMirror-line > span > span::-moz-selection { background: rgba(68, 68, 119, .99); } +.cm-s-night .CodeMirror-gutters { background: #0a001f; border-right: 1px solid #aaa; } +.cm-s-night .CodeMirror-guttermarker { color: white; } +.cm-s-night .CodeMirror-guttermarker-subtle { color: #bbb; } +.cm-s-night .CodeMirror-linenumber { color: #f8f8f8; } +.cm-s-night .CodeMirror-cursor { border-left: 1px solid white; } + +.cm-s-night span.cm-comment { color: #8900d1; } +.cm-s-night span.cm-atom { color: #845dc4; } +.cm-s-night span.cm-number, .cm-s-night span.cm-attribute { color: #ffd500; } +.cm-s-night span.cm-keyword { color: #599eff; } +.cm-s-night span.cm-string { color: #37f14a; } +.cm-s-night span.cm-meta { color: #7678e2; } +.cm-s-night span.cm-variable-2, .cm-s-night span.cm-tag { color: #99b2ff; } +.cm-s-night span.cm-variable-3, .cm-s-night span.cm-def, .cm-s-night span.cm-type { color: white; } +.cm-s-night span.cm-bracket { color: #8da6ce; } +.cm-s-night span.cm-builtin, .cm-s-night span.cm-special { color: #ff9e59; } +.cm-s-night span.cm-link { color: #845dc4; } +.cm-s-night span.cm-error { color: #9d1e15; } + +.cm-s-night .CodeMirror-activeline-background { background: #1C005A; } +.cm-s-night .CodeMirror-matchingbracket { outline:1px solid grey; color:white !important; } diff --git a/modules/editor/codemirror/theme/railscasts.css b/modules/editor/codemirror/theme/railscasts.css @@ -0,0 +1,34 @@ +/* + + Name: Railscasts + Author: Ryan Bates (http://railscasts.com) + + CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror) + Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16) + +*/ + +.cm-s-railscasts.CodeMirror {background: #2b2b2b; color: #f4f1ed;} +.cm-s-railscasts div.CodeMirror-selected {background: #272935 !important;} +.cm-s-railscasts .CodeMirror-gutters {background: #2b2b2b; border-right: 0px;} +.cm-s-railscasts .CodeMirror-linenumber {color: #5a647e;} +.cm-s-railscasts .CodeMirror-cursor {border-left: 1px solid #d4cfc9 !important;} + +.cm-s-railscasts span.cm-comment {color: #bc9458;} +.cm-s-railscasts span.cm-atom {color: #b6b3eb;} +.cm-s-railscasts span.cm-number {color: #b6b3eb;} + +.cm-s-railscasts span.cm-property, .cm-s-railscasts span.cm-attribute {color: #a5c261;} +.cm-s-railscasts span.cm-keyword {color: #da4939;} +.cm-s-railscasts span.cm-string {color: #ffc66d;} + +.cm-s-railscasts span.cm-variable {color: #a5c261;} +.cm-s-railscasts span.cm-variable-2 {color: #6d9cbe;} +.cm-s-railscasts span.cm-def {color: #cc7833;} +.cm-s-railscasts span.cm-error {background: #da4939; color: #d4cfc9;} +.cm-s-railscasts span.cm-bracket {color: #f4f1ed;} +.cm-s-railscasts span.cm-tag {color: #da4939;} +.cm-s-railscasts span.cm-link {color: #b6b3eb;} + +.cm-s-railscasts .CodeMirror-matchingbracket { text-decoration: underline; color: white !important;} +.cm-s-railscasts .CodeMirror-activeline-background { background: #303040; } diff --git a/modules/editor/codemirror/theme/ttcn.css b/modules/editor/codemirror/theme/ttcn.css @@ -0,0 +1,64 @@ +.cm-s-ttcn .cm-quote { color: #090; } +.cm-s-ttcn .cm-negative { color: #d44; } +.cm-s-ttcn .cm-positive { color: #292; } +.cm-s-ttcn .cm-header, .cm-strong { font-weight: bold; } +.cm-s-ttcn .cm-em { font-style: italic; } +.cm-s-ttcn .cm-link { text-decoration: underline; } +.cm-s-ttcn .cm-strikethrough { text-decoration: line-through; } +.cm-s-ttcn .cm-header { color: #00f; font-weight: bold; } + +.cm-s-ttcn .cm-atom { color: #219; } +.cm-s-ttcn .cm-attribute { color: #00c; } +.cm-s-ttcn .cm-bracket { color: #997; } +.cm-s-ttcn .cm-comment { color: #333333; } +.cm-s-ttcn .cm-def { color: #00f; } +.cm-s-ttcn .cm-em { font-style: italic; } +.cm-s-ttcn .cm-error { color: #f00; } +.cm-s-ttcn .cm-hr { color: #999; } +.cm-s-ttcn .cm-invalidchar { color: #f00; } +.cm-s-ttcn .cm-keyword { font-weight:bold; } +.cm-s-ttcn .cm-link { color: #00c; text-decoration: underline; } +.cm-s-ttcn .cm-meta { color: #555; } +.cm-s-ttcn .cm-negative { color: #d44; } +.cm-s-ttcn .cm-positive { color: #292; } +.cm-s-ttcn .cm-qualifier { color: #555; } +.cm-s-ttcn .cm-strikethrough { text-decoration: line-through; } +.cm-s-ttcn .cm-string { color: #006400; } +.cm-s-ttcn .cm-string-2 { color: #f50; } +.cm-s-ttcn .cm-strong { font-weight: bold; } +.cm-s-ttcn .cm-tag { color: #170; } +.cm-s-ttcn .cm-variable { color: #8B2252; } +.cm-s-ttcn .cm-variable-2 { color: #05a; } +.cm-s-ttcn .cm-variable-3, .cm-s-ttcn .cm-type { color: #085; } + +.cm-s-ttcn .cm-invalidchar { color: #f00; } + +/* ASN */ +.cm-s-ttcn .cm-accessTypes, +.cm-s-ttcn .cm-compareTypes { color: #27408B; } +.cm-s-ttcn .cm-cmipVerbs { color: #8B2252; } +.cm-s-ttcn .cm-modifier { color:#D2691E; } +.cm-s-ttcn .cm-status { color:#8B4545; } +.cm-s-ttcn .cm-storage { color:#A020F0; } +.cm-s-ttcn .cm-tags { color:#006400; } + +/* CFG */ +.cm-s-ttcn .cm-externalCommands { color: #8B4545; font-weight:bold; } +.cm-s-ttcn .cm-fileNCtrlMaskOptions, +.cm-s-ttcn .cm-sectionTitle { color: #2E8B57; font-weight:bold; } + +/* TTCN */ +.cm-s-ttcn .cm-booleanConsts, +.cm-s-ttcn .cm-otherConsts, +.cm-s-ttcn .cm-verdictConsts { color: #006400; } +.cm-s-ttcn .cm-configOps, +.cm-s-ttcn .cm-functionOps, +.cm-s-ttcn .cm-portOps, +.cm-s-ttcn .cm-sutOps, +.cm-s-ttcn .cm-timerOps, +.cm-s-ttcn .cm-verdictOps { color: #0000FF; } +.cm-s-ttcn .cm-preprocessor, +.cm-s-ttcn .cm-templateMatch, +.cm-s-ttcn .cm-ttcn3Macros { color: #27408B; } +.cm-s-ttcn .cm-types { color: #A52A2A; font-weight:bold; } +.cm-s-ttcn .cm-visibilityModifiers { font-weight:bold; } diff --git a/modules/editor/codemirror/theme/xq-dark.css b/modules/editor/codemirror/theme/xq-dark.css @@ -0,0 +1,53 @@ +/* +Copyright (C) 2011 by MarkLogic Corporation +Author: Mike Brevoort <mike@brevoort.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +.cm-s-xq-dark.CodeMirror { background: #0a001f; color: #f8f8f8; } +.cm-s-xq-dark div.CodeMirror-selected { background: #27007A; } +.cm-s-xq-dark .CodeMirror-line::selection, .cm-s-xq-dark .CodeMirror-line > span::selection, .cm-s-xq-dark .CodeMirror-line > span > span::selection { background: rgba(39, 0, 122, 0.99); } +.cm-s-xq-dark .CodeMirror-line::-moz-selection, .cm-s-xq-dark .CodeMirror-line > span::-moz-selection, .cm-s-xq-dark .CodeMirror-line > span > span::-moz-selection { background: rgba(39, 0, 122, 0.99); } +.cm-s-xq-dark .CodeMirror-gutters { background: #0a001f; border-right: 1px solid #aaa; } +.cm-s-xq-dark .CodeMirror-guttermarker { color: #FFBD40; } +.cm-s-xq-dark .CodeMirror-guttermarker-subtle { color: #f8f8f8; } +.cm-s-xq-dark .CodeMirror-linenumber { color: #f8f8f8; } +.cm-s-xq-dark .CodeMirror-cursor { border-left: 1px solid white; } + +.cm-s-xq-dark span.cm-keyword { color: #FFBD40; } +.cm-s-xq-dark span.cm-atom { color: #6C8CD5; } +.cm-s-xq-dark span.cm-number { color: #164; } +.cm-s-xq-dark span.cm-def { color: #FFF; text-decoration:underline; } +.cm-s-xq-dark span.cm-variable { color: #FFF; } +.cm-s-xq-dark span.cm-variable-2 { color: #EEE; } +.cm-s-xq-dark span.cm-variable-3, .cm-s-xq-dark span.cm-type { color: #DDD; } +.cm-s-xq-dark span.cm-property {} +.cm-s-xq-dark span.cm-operator {} +.cm-s-xq-dark span.cm-comment { color: gray; } +.cm-s-xq-dark span.cm-string { color: #9FEE00; } +.cm-s-xq-dark span.cm-meta { color: yellow; } +.cm-s-xq-dark span.cm-qualifier { color: #FFF700; } +.cm-s-xq-dark span.cm-builtin { color: #30a; } +.cm-s-xq-dark span.cm-bracket { color: #cc7; } +.cm-s-xq-dark span.cm-tag { color: #FFBD40; } +.cm-s-xq-dark span.cm-attribute { color: #FFF700; } +.cm-s-xq-dark span.cm-error { color: #f00; } + +.cm-s-xq-dark .CodeMirror-activeline-background { background: #27282E; } +.cm-s-xq-dark .CodeMirror-matchingbracket { outline:1px solid grey; color:white !important; } diff --git a/modules/template-engine/components/components.ini b/modules/template-engine/components/components.ini @@ -0,0 +1,42 @@ +; Control-file for template elements + +output = +button = +checkbox = +column = +date = +dummy = +focus = +form = +group = +hidden = +header = +editor = +else = +if = +image = +input = +inputarea= +insert = +label = +link = +list = +logo = +newline = +page = +part = +password = +radio = +raw = +row = +selectbox= +radiobox = +selector = +set = +table = +text = +tree = +upload = +user = +window = +qrcode = + \ No newline at end of file diff --git a/modules/util/ProjectTree.class.php b/modules/util/ProjectTree.class.php @@ -4,7 +4,7 @@ use cms\model\Element; use cms\model\Template; use cms\model\Page; use cms\model\Folder; -use cms\model\Object; +use cms\model\BaseObject; use cms\model\File; use cms\model\Link; @@ -108,7 +108,7 @@ class ProjectTree extends AbstractTree $objectid = intval($value->linkToObjectId); if ( $objectid != 0 ) { - $object = new Object( $objectid ); + $object = new BaseObject( $objectid ); $object->load(); $treeElement = new TreeElement(); @@ -143,7 +143,7 @@ class ProjectTree extends AbstractTree if ( $link->isLinkToObject ) { - $o = new Object( $link->linkedObjectId ); + $o = new BaseObject( $link->linkedObjectId ); $o->load(); $treeElement = new TreeElement(); diff --git a/modules/util/Transformer.class.php b/modules/util/Transformer.class.php @@ -1,7 +1,7 @@ <?php use cms\model\Link; -use cms\model\Object; +use cms\model\BaseObject; use cms\model\Url; /** @@ -77,7 +77,7 @@ class Transformer // anderen (insbesondere Preview-Links zu andereen Seiten) darf die Umsetzung nicht erfolgen. // Der Renderer kann dies nicht tun, denn der erzeugt nur "object://..."-URLs. // Beispiel: "...?a=1&b=2" wird zu "...?a=1&amp;b=2" - $o = new Object($objectId); + $o = new BaseObject($objectId); try { $o->load();