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"; + }