openrat-cms

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

commit 8207afa90990a5d4c6e5940a1e4799e94b687d59
parent 0dfbaff17a0b100c933986d26c32b9331ca67f46
Author: Jan Dankert <devnull@localhost>
Date:   Tue, 22 May 2018 22:39:55 +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:
modules/cms-core/model/Project.class.php | 2+-
modules/cms-core/model/Url.class.php | 2+-
modules/cms-ui/themes/default/html/views/configuration/show.php | 28++++++++++++++++++++++++++++
modules/cms-ui/themes/default/html/views/file/prop.php | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/cms-ui/themes/default/html/views/folder/prop.tpl.src.xml | 1+
modules/cms-ui/themes/default/html/views/modellist/show.php | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/cms-ui/themes/default/html/views/project/edit.php | 162+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/cms-ui/themes/default/html/views/template/srcelement.php | 66++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/cms-ui/themes/default/html/views/text/edit.php | 22++++++++++++++++++++++
modules/cms-ui/themes/default/html/views/text/prop.php | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/LICENSE | 21+++++++++++++++++++++
modules/editor/codemirror/addon/dialog/dialog.min.js | 157+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/display/autorefresh.min.js | 47+++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/display/fullscreen.js | 41+++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/display/fullscreen.min.js | 41+++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/display/panel.min.js | 123+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/display/rulers.js | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/display/rulers.min.js | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/hint/anyword-hint.min.js | 41+++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/hint/xml-hint.js | 110+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/lint/css-lint.js | 40++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/merge/merge.css | 113+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/mode/loadmode.min.js | 64++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/runmode/runmode.node.min.js | 197+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/scroll/scrollpastend.js | 48++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/addon/search/search.min.js | 252+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/bin/compress | 92+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/demo/anywordhint.html | 79+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/demo/bidi.html | 106+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/demo/preview.html | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/demo/simplescrollbars.html | 82+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/demo/xmlcomplete.html | 119+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/doc/activebookmark.js | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/doc/yinyang.png | 0
modules/editor/codemirror/keymap/vim.min.js | 5212+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/asn.1/asn.1.min.js | 204+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/cobol/cobol.min.js | 255+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/dockerfile/dockerfile.min.js | 79+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/dylan/dylan.min.js | 352+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/fcl/fcl.min.js | 173+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/http/http.min.js | 113+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/idl/idl.min.js | 290+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/javascript/test.min.js | 423+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/mbox/mbox.min.js | 129+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/mscgen/xu_test.min.js | 86+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/nginx/nginx.min.js | 178+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/oz/oz.min.js | 252+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/pascal/pascal.min.js | 109+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/powershell/test.min.js | 74++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/rst/rst.min.js | 557+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/spreadsheet/spreadsheet.min.js | 112+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/tcl/tcl.min.js | 139+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/textile/textile.min.js | 469+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/tornado/tornado.min.js | 68++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/mode/yaml/yaml.min.js | 118+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/rollup.config.js | 18++++++++++++++++++
modules/editor/codemirror/src/codemirror.js | 3+++
modules/editor/codemirror/src/display/Display.min.js | 106+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/display/operations.js | 205+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/display/scroll_events.js | 115+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/display/view_tracking.js | 153+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/edit/commands.min.js | 178+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/edit/deleteNearSelection.js | 30++++++++++++++++++++++++++++++
modules/editor/codemirror/src/edit/deleteNearSelection.min.js | 30++++++++++++++++++++++++++++++
modules/editor/codemirror/src/edit/global_events.min.js | 44++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/edit/legacy.js | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/input/input.js | 135+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/line/line_data.js | 337+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/model/selection.min.js | 82+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/modes.min.js | 96+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/util/dom.js | 97+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/util/dom.min.js | 97+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/src/util/operation_group.min.js | 72++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/test/lint.js | 20++++++++++++++++++++
modules/editor/codemirror/test/sql-hint-test.js | 238+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/test/test.min.js | 2550+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/theme/base16-light.css | 38++++++++++++++++++++++++++++++++++++++
modules/editor/codemirror/theme/mbo.css | 37+++++++++++++++++++++++++++++++++++++
modules/template-engine/components/html/editor/editor.css | 30++++++++++++++++--------------
modules/template-engine/components/html/link/link.min.js | 4++--
80 files changed, 16643 insertions(+), 18 deletions(-)

diff --git a/modules/cms-core/model/Project.class.php b/modules/cms-core/model/Project.class.php @@ -504,7 +504,7 @@ EOF foreach( $idList as $id ) { $this->log[] = 'Lost file! Moving '.$id.' to lost+found.'; - $obj = new Object( $id ); + $obj = new BaseObject( $id ); $obj->setParentId( $lostAndFoundFolder->objectid ); } } diff --git a/modules/cms-core/model/Url.class.php b/modules/cms-core/model/Url.class.php @@ -7,7 +7,7 @@ namespace cms\model; * @author Jan Dankert * @package openrat.objects */ -class Url extends Object +class Url extends BaseObject { public $urlid; public $url = ''; diff --git a/modules/cms-ui/themes/default/html/views/configuration/show.php b/modules/cms-ui/themes/default/html/views/configuration/show.php @@ -0,0 +1,27 @@ + + + <table width="100%"> + <tr class="headline"> + <td class="help"> + <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_VALUE'.'')))); ?></span> + + </td> + </tr> + <?php foreach($config as $list_key=>$list_value){ ?><?php extract($list_value) ?> + <tr class="data"> + <td> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities($key))); ?></span> + + </td> + <td class="<?php echo $class ?>"> + <span class="<?php echo $class ?>"><?php echo nl2br(encodeHtml(htmlentities($value))); ?></span> + + </td> + </tr> + <?php } ?> + </table> + + \ No newline at end of file diff --git a/modules/cms-ui/themes/default/html/views/file/prop.php b/modules/cms-ui/themes/default/html/views/file/prop.php @@ -0,0 +1,55 @@ + + + <div class="headermenu"><div class="toolbar-icon clickable"><a href="javascript:void(0);" title="<?php echo lang('MENU_SIZE') ?>" data-type="dialog" data-name="<?php echo lang('MENU_SIZE') ?>" data-method="size"><img src="./themes/default/images/icon/action/size.svg" title="<?php echo lang('MENU_size_DESC') ?>" /><?php echo lang('MENU_size') ?></a></div><div class="toolbar-icon clickable"><a href="javascript:void(0);" title="<?php echo lang('MENU_COMPRESS') ?>" data-type="dialog" data-name="<?php echo lang('MENU_COMPRESS') ?>" data-method="compress"><img src="./themes/default/images/icon/action/compress.svg" title="<?php echo lang('MENU_compress_DESC') ?>" /><?php echo lang('MENU_compress') ?></a></div><div class="toolbar-icon clickable"><a href="javascript:void(0);" title="<?php echo lang('MENU_UNCOMPRESS') ?>" data-type="dialog" data-name="<?php echo lang('MENU_UNCOMPRESS') ?>" data-method="uncompress"><img src="./themes/default/images/icon/action/uncompress.svg" title="<?php echo lang('MENU_uncompress_DESC') ?>" /><?php echo lang('MENU_uncompress') ?></a></div><div class="toolbar-icon clickable"><a href="javascript:void(0);" title="<?php echo lang('MENU_EXTRACT') ?>" data-type="dialog" data-name="<?php echo lang('MENU_EXTRACT') ?>" data-method="extract"><img src="./themes/default/images/icon/action/extract.svg" title="<?php echo lang('MENU_extract_DESC') ?>" /><?php echo lang('MENU_extract') ?></a></div></div> + + <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"> + <label for="<?php echo REQUEST_ID ?>_name" class="label"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('global_name')))); ?></span> + + </label> + </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="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"> + <label for="<?php echo REQUEST_ID ?>_filename" class="label"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('global_filename')))); ?></span> + + </label> + </div> + <div class="input"> + <div class="inputholder"><input<?php if ('') echo ' disabled="true"' ?> id="<?php echo REQUEST_ID ?>_filename" name="filename<?php if ('') echo '_disabled' ?>" type="text" maxlength="256" class="filename" value="<?php echo Text::encodeHtml(@$filename) ?>" /><?php if ('') { ?><input type="hidden" name="filename" value="<?php $filename ?>"/><?php } ?></div> + + </div> + </div> + <div class="line"> + <div class="label"> + <label for="<?php echo REQUEST_ID ?>_extension" class="label"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('file_extension')))); ?></span> + + </label> + </div> + <div class="input"> + <div class="inputholder"><input<?php if ('') echo ' disabled="true"' ?> id="<?php echo REQUEST_ID ?>_extension" name="extension<?php if ('') echo '_disabled' ?>" type="text" maxlength="256" class="extension" value="<?php echo Text::encodeHtml(@$extension) ?>" /><?php if ('') { ?><input type="hidden" name="extension" value="<?php $extension ?>"/><?php } ?></div> + + </div> + </div> + <div class="line"> + <div class="label"> + <label for="<?php echo REQUEST_ID ?>_description" class="label"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('global_description')))); ?></span> + + </label> + </div> + <div class="input"> + <div class="inputholder"><textarea class="description" name="description"><?php echo Text::encodeHtml($description) ?></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/prop.tpl.src.xml b/modules/cms-ui/themes/default/html/views/folder/prop.tpl.src.xml @@ -3,6 +3,7 @@ <header></header> <form label="message:global_save"> + <hidden name="languageid" /> <part class="line"> <part class="label"> <label for="name" key="global_name" /> diff --git a/modules/cms-ui/themes/default/html/views/modellist/show.php b/modules/cms-ui/themes/default/html/views/modellist/show.php @@ -0,0 +1,77 @@ + + + <table width="100%"> + <tr class="headline"> + <td> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang(''.'name'.'')))); ?></span> + + </td> + <td> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(''))); ?></span> + + </td> + <td> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(''))); ?></span> + + </td> + </tr> + <?php foreach($el as $list_key=>$list_value){ ?><?php extract($list_value) ?> + <tr class="data"> + <td class="clickable"> + <img class="" title="" src="./modules/cms-ui/themes/default/images/icon/icon_model.png" /> + + <a target="_self" date-name="<?php echo $name ?>" name="<?php echo $name ?>" data-type="open" data-action="model" data-method="<?php echo OR_METHOD ?>" data-id="<?php echo $id ?>" href="javascript:void(0);"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(Text::maxLength( $name,25,'..',constant('STR_PAD_BOTH') )))); ?></span> + + </a> + + </td> + <?php $if5=(!empty($default_url)); if($if5){?> + <td class="clickable"> + <a target="_self" data-type="post" data-action="model" data-method="setdefault" data-id="<?php echo $id ?>" data-data="{&quot;action&quot;:&quot;model&quot;,&quot;subaction&quot;:&quot;setdefault&quot;,&quot;id&quot;:&quot;<?php echo $id ?>&quot;,&quot;token&quot;:&quot;<?php echo token() ?>&quot;,&quot;none&quot;:&quot;0&quot;}"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('GLOBAL_make_default')))); ?></span> + + </a> + + </td> + <?php } ?> + <?php if(!$if5){?> + <td> + <em class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('GLOBAL_is_default')))); ?></em> + + </td> + <?php } ?> + <?php $if5=(!empty($select_url)); if($if5){?> + <td class="clickable"> + <a target="_self" data-type="post" data-action="start" data-method="model" data-id="<?php echo $id ?>" data-data="{&quot;action&quot;:&quot;start&quot;,&quot;subaction&quot;:&quot;model&quot;,&quot;id&quot;:&quot;<?php echo $id ?>&quot;,&quot;token&quot;:&quot;<?php echo token() ?>&quot;,&quot;none&quot;:&quot;0&quot;}"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('GLOBAL_select')))); ?></span> + + </a> + + </td> + <?php } ?> + <?php if(!$if5){?> + <td> + <em class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('GLOBAL_selected')))); ?></em> + + </td> + <?php } ?> + </tr> + <?php unset($select_url) ?> + + <?php unset($default_url) ?> + + <?php } ?> + <tr class="data"> + <td colspan="3" class="clickable"> + <a target="_self" data-type="view" data-action="" data-method="add" data-id="<?php echo OR_ID ?>" 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('new')))); ?></span> + + </a> + + </td> + </tr> + </table> + + \ No newline at end of file diff --git a/modules/cms-ui/themes/default/html/views/project/edit.php b/modules/cms-ui/themes/default/html/views/project/edit.php @@ -0,0 +1,161 @@ + + + <div class="headermenu"><div class="toolbar-icon clickable"><a href="javascript:void(0);" title="<?php echo lang('MENU_REMOVE') ?>" data-type="dialog" data-name="<?php echo lang('MENU_REMOVE') ?>" data-method="remove"><img src="./themes/default/images/icon/action/remove.svg" title="<?php echo lang('MENU_remove_DESC') ?>" /><?php echo lang('MENU_remove') ?></a></div><div class="toolbar-icon clickable"><a href="javascript:void(0);" title="<?php echo lang('MENU_EXPORT') ?>" data-type="dialog" data-name="<?php echo lang('MENU_EXPORT') ?>" data-method="export"><img src="./themes/default/images/icon/action/export.svg" title="<?php echo lang('MENU_export_DESC') ?>" /><?php echo lang('MENU_export') ?></a></div><div class="toolbar-icon clickable"><a href="javascript:void(0);" title="<?php echo lang('MENU_MAINTENANCE') ?>" data-type="dialog" data-name="<?php echo lang('MENU_MAINTENANCE') ?>" data-method="maintenance"><img src="./themes/default/images/icon/action/maintenance.svg" title="<?php echo lang('MENU_maintenance_DESC') ?>" /><?php echo lang('MENU_maintenance') ?></a></div></div> + + <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('NAME') ?></legend><div> + <div class="line"> + <div class="label"> + <label for="<?php echo REQUEST_ID ?>_name" class="label"><?php echo lang('PROJECT_NAME') ?> + </label> + </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="name" value="<?php echo Text::encodeHtml(@$name) ?>" /><?php if ('') { ?><input type="hidden" name="name" value="<?php $name ?>"/><?php } ?></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('PUBLISH') ?></legend><div> + <div class="line"> + <div class="label"> + <label for="<?php echo REQUEST_ID ?>_target_dir" class="label"><?php echo lang('PROJECT_TARGET_DIR') ?> + </label> + </div> + <div class="input"> + <div class="inputholder"><input<?php if ('') echo ' disabled="true"' ?> id="<?php echo REQUEST_ID ?>_target_dir" name="target_dir<?php if ('') echo '_disabled' ?>" type="text" maxlength="256" class="filename" value="<?php echo Text::encodeHtml(@$target_dir) ?>" /><?php if ('') { ?><input type="hidden" name="target_dir" value="<?php $target_dir ?>"/><?php } ?></div> + + </div> + </div> + <div class="line"> + <div class="label"> + <label for="<?php echo REQUEST_ID ?>_cmd_after_publish" class="label"><?php echo lang('PROJECT_CMD_AFTER_PUBLISH') ?> + </label> + </div> + <div class="input"> + <div class="inputholder"><input<?php if (!config('publish','project','override_system_command')) echo ' disabled="true"' ?> id="<?php echo REQUEST_ID ?>_cmd_after_publish" name="cmd_after_publish<?php if (!config('publish','project','override_system_command')) echo '_disabled' ?>" type="text" maxlength="256" class="filename" value="<?php echo Text::encodeHtml(@$cmd_after_publish) ?>" /><?php if (!config('publish','project','override_system_command')) { ?><input type="hidden" name="cmd_after_publish" value="<?php $cmd_after_publish ?>"/><?php } ?></div> + + </div> + </div> + <div class="line"> + <div class="label"> + </div> + <div class="input"> + <?php { $tmpname = 'publishFileExtension';$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 ?>_publishFileExtension" class="label"><?php echo lang('PROJECT_publish_File_Extension') ?> + </label> + </div> + </div> + <div class="line"> + <div class="label"> + </div> + <div class="input"> + <?php { $tmpname = 'publishPageExtension';$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 ?>_publishPageExtension" class="label"><?php echo lang('PROJECT_publish_page_Extension') ?> + </label> + </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('project_FTP') ?></legend><div> + <div class="line"> + <div class="label"> + <label for="<?php echo REQUEST_ID ?>_ftp_url" class="label"><?php echo lang('PROJECT_FTP_URL') ?> + </label> + </div> + <div class="input"> + <div class="inputholder"><input<?php if (!config('publish','ftp','enable')) echo ' disabled="true"' ?> id="<?php echo REQUEST_ID ?>_ftp_url" name="ftp_url<?php if (!config('publish','ftp','enable')) echo '_disabled' ?>" type="text" maxlength="256" class="filename" value="<?php echo Text::encodeHtml(@$ftp_url) ?>" /><?php if (!config('publish','ftp','enable')) { ?><input type="hidden" name="ftp_url" value="<?php $ftp_url ?>"/><?php } ?></div> + + <br/> + + <?php { $tmpname = 'ftp_passive';$default = '';$readonly = !config('publish','ftp','enable'); + 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 ?>_ftp_passive" class="label"><?php echo lang('PROJECT_FTP_PASSIVE') ?> + </label> + </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('options') ?></legend><div> + <div class="line"> + <div class="label"> + </div> + <div class="input"> + <?php { $tmpname = 'content_negotiation';$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 ?>_content_negotiation" class="label"><?php echo lang('PROJECT_CONTENT_NEGOTIATION') ?> + </label> + </div> + </div> + <div class="line"> + <div class="label"> + </div> + <div class="input"> + <?php { $tmpname = 'cut_index';$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 ?>_cut_index" class="label"><?php echo lang('PROJECT_CUT_INDEX') ?> + </label> + </div> + </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/srcelement.php b/modules/cms-ui/themes/default/html/views/template/srcelement.php @@ -0,0 +1,65 @@ + + + + + <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=(!empty($elements)); if($if3){?> + <div class="line"> + <div class="label"> + <input class="radio" type="radio" id="<?php echo REQUEST_ID ?>_type_addelement" name="type" value="addelement"<?php if('addelement'==@$type)echo ' checked="checked"' ?> /> + + <label for="<?php echo REQUEST_ID ?>_type_addelement" class="label"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang(''.'value'.'')))); ?></span> + + </label> + </div> + <div class="input"> + <div class="inputholder"><select id="<?php echo REQUEST_ID ?>_elementid" name="elementid" title="" class=""<?php if (count($elements)<=1) echo ' disabled="disabled"'; ?> size=1"><?php include_once( 'modules/template-engine/components/html/selectbox/component-select-box.php') ?><?php component_select_option_list($elements,$elementid,0,0) ?><?php if (count($elements)==0) { ?><input type="hidden" name="elementid" value="" /><?php } ?><?php if (count($elements)==1) { ?><input type="hidden" name="elementid" value="<?php echo array_keys($elements)[0] ?>" /><?php } ?> + </select></div> + </div> + </div> + <?php } ?> + <?php $if3=(!empty($writable_elements)); if($if3){?> + <fieldset class="<?php echo '1'?" open":"" ?><?php echo '1'?" show":"" ?>"><div> + </div></fieldset> + <div class="line"> + <div class="label"> + <input class="radio" type="radio" id="<?php echo REQUEST_ID ?>_type_addicon" name="type" value="addicon"<?php if('addicon'==@$type)echo ' checked="checked"' ?> /> + + <label for="<?php echo REQUEST_ID ?>_type_addicon" class="label"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang(''.'GLOBAL_ICON'.'')))); ?></span> + + </label> + </div> + <div class="input"> + <div class="inputholder"><select id="<?php echo REQUEST_ID ?>_writable_elementid" name="writable_elementid" title="" class=""<?php if (count($writable_elements)<=1) echo ' disabled="disabled"'; ?> size=1"><?php include_once( 'modules/template-engine/components/html/selectbox/component-select-box.php') ?><?php component_select_option_list($writable_elements,$writable_elementid,0,0) ?><?php if (count($writable_elements)==0) { ?><input type="hidden" name="writable_elementid" value="" /><?php } ?><?php if (count($writable_elements)==1) { ?><input type="hidden" name="writable_elementid" value="<?php echo array_keys($writable_elements)[0] ?>" /><?php } ?> + </select></div> + </div> + </div> + <div class="line"> + <div class="label"> + <input class="radio" type="radio" id="<?php echo REQUEST_ID ?>_type_addifempty" name="type" value="addifempty"<?php if('addifempty'==@$type)echo ' checked="checked"' ?> /> + + <label for="<?php echo REQUEST_ID ?>_type_addifempty" class="label"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang(''.'TEMPLATE_SRC_IFEMPTY'.'')))); ?></span> + + </label> + </div> + <div class="input"> + </div> + </div> + <div class="line"> + <div class="label"> + <input class="radio" type="radio" id="<?php echo REQUEST_ID ?>_type_addifnotempty" name="type" value="addifnotempty"<?php if('addifnotempty'==@$type)echo ' checked="checked"' ?> /> + + <label for="<?php echo REQUEST_ID ?>_type_addifnotempty" class="label"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang(''.'TEMPLATE_SRC_IFNOTEMPTY'.'')))); ?></span> + + </label> + </div> + <div class="input"> + </div> + </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/text/edit.php b/modules/cms-ui/themes/default/html/views/text/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="req15182100161107736781_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/text/prop.php b/modules/cms-ui/themes/default/html/views/text/prop.php @@ -0,0 +1,55 @@ + + + <div class="headermenu"><div class="toolbar-icon clickable"><a href="javascript:void(0);" title="<?php echo lang('MENU_SIZE') ?>" data-type="dialog" data-name="<?php echo lang('MENU_SIZE') ?>" data-method="size"><img src="./themes/default/images/icon/action/size.svg" title="<?php echo lang('MENU_size_DESC') ?>" /><?php echo lang('MENU_size') ?></a></div><div class="toolbar-icon clickable"><a href="javascript:void(0);" title="<?php echo lang('MENU_COMPRESS') ?>" data-type="dialog" data-name="<?php echo lang('MENU_COMPRESS') ?>" data-method="compress"><img src="./themes/default/images/icon/action/compress.svg" title="<?php echo lang('MENU_compress_DESC') ?>" /><?php echo lang('MENU_compress') ?></a></div><div class="toolbar-icon clickable"><a href="javascript:void(0);" title="<?php echo lang('MENU_UNCOMPRESS') ?>" data-type="dialog" data-name="<?php echo lang('MENU_UNCOMPRESS') ?>" data-method="uncompress"><img src="./themes/default/images/icon/action/uncompress.svg" title="<?php echo lang('MENU_uncompress_DESC') ?>" /><?php echo lang('MENU_uncompress') ?></a></div><div class="toolbar-icon clickable"><a href="javascript:void(0);" title="<?php echo lang('MENU_EXTRACT') ?>" data-type="dialog" data-name="<?php echo lang('MENU_EXTRACT') ?>" data-method="extract"><img src="./themes/default/images/icon/action/extract.svg" title="<?php echo lang('MENU_extract_DESC') ?>" /><?php echo lang('MENU_extract') ?></a></div></div> + + <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"> + <label for="<?php echo REQUEST_ID ?>_name" class="label"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('global_name')))); ?></span> + + </label> + </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="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"> + <label for="<?php echo REQUEST_ID ?>_filename" class="label"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('global_filename')))); ?></span> + + </label> + </div> + <div class="input"> + <div class="inputholder"><input<?php if ('') echo ' disabled="true"' ?> id="<?php echo REQUEST_ID ?>_filename" name="filename<?php if ('') echo '_disabled' ?>" type="text" maxlength="256" class="filename" value="<?php echo Text::encodeHtml(@$filename) ?>" /><?php if ('') { ?><input type="hidden" name="filename" value="<?php $filename ?>"/><?php } ?></div> + + </div> + </div> + <div class="line"> + <div class="label"> + <label for="<?php echo REQUEST_ID ?>_extension" class="label"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('file_extension')))); ?></span> + + </label> + </div> + <div class="input"> + <div class="inputholder"><input<?php if ('') echo ' disabled="true"' ?> id="<?php echo REQUEST_ID ?>_extension" name="extension<?php if ('') echo '_disabled' ?>" type="text" maxlength="256" class="extension" value="<?php echo Text::encodeHtml(@$extension) ?>" /><?php if ('') { ?><input type="hidden" name="extension" value="<?php $extension ?>"/><?php } ?></div> + + </div> + </div> + <div class="line"> + <div class="label"> + <label for="<?php echo REQUEST_ID ?>_description" class="label"> + <span class="text"><?php echo nl2br(encodeHtml(htmlentities(lang('global_description')))); ?></span> + + </label> + </div> + <div class="input"> + <div class="inputholder"><textarea class="description" name="description"><?php echo Text::encodeHtml($description) ?></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/editor/codemirror/LICENSE b/modules/editor/codemirror/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (C) 2017 by Marijn Haverbeke <marijnh@gmail.com> and others + +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. diff --git a/modules/editor/codemirror/addon/dialog/dialog.min.js b/modules/editor/codemirror/addon/dialog/dialog.min.js @@ -0,0 +1,157 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// Open simple dialogs on top of an editor. Relies on dialog.css. + +(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 dialogDiv(cm, template, bottom) { + var wrap = cm.getWrapperElement(); + var dialog; + dialog = wrap.appendChild(document.createElement("div")); + if (bottom) + dialog.className = "CodeMirror-dialog CodeMirror-dialog-bottom"; + else + dialog.className = "CodeMirror-dialog CodeMirror-dialog-top"; + + if (typeof template == "string") { + dialog.innerHTML = template; + } else { // Assuming it's a detached DOM element. + dialog.appendChild(template); + } + return dialog; + } + + function closeNotification(cm, newVal) { + if (cm.state.currentNotificationClose) + cm.state.currentNotificationClose(); + cm.state.currentNotificationClose = newVal; + } + + CodeMirror.defineExtension("openDialog", function(template, callback, options) { + if (!options) options = {}; + + closeNotification(this, null); + + var dialog = dialogDiv(this, template, options.bottom); + var closed = false, me = this; + function close(newVal) { + if (typeof newVal == 'string') { + inp.value = newVal; + } else { + if (closed) return; + closed = true; + dialog.parentNode.removeChild(dialog); + me.focus(); + + if (options.onClose) options.onClose(dialog); + } + } + + var inp = dialog.getElementsByTagName("input")[0], button; + if (inp) { + inp.focus(); + + if (options.value) { + inp.value = options.value; + if (options.selectValueOnOpen !== false) { + inp.select(); + } + } + + if (options.onInput) + CodeMirror.on(inp, "input", function(e) { options.onInput(e, inp.value, close);}); + if (options.onKeyUp) + CodeMirror.on(inp, "keyup", function(e) {options.onKeyUp(e, inp.value, close);}); + + CodeMirror.on(inp, "keydown", function(e) { + if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { return; } + if (e.keyCode == 27 || (options.closeOnEnter !== false && e.keyCode == 13)) { + inp.blur(); + CodeMirror.e_stop(e); + close(); + } + if (e.keyCode == 13) callback(inp.value, e); + }); + + if (options.closeOnBlur !== false) CodeMirror.on(inp, "blur", close); + } else if (button = dialog.getElementsByTagName("button")[0]) { + CodeMirror.on(button, "click", function() { + close(); + me.focus(); + }); + + if (options.closeOnBlur !== false) CodeMirror.on(button, "blur", close); + + button.focus(); + } + return close; + }); + + CodeMirror.defineExtension("openConfirm", function(template, callbacks, options) { + closeNotification(this, null); + var dialog = dialogDiv(this, template, options && options.bottom); + var buttons = dialog.getElementsByTagName("button"); + var closed = false, me = this, blurring = 1; + function close() { + if (closed) return; + closed = true; + dialog.parentNode.removeChild(dialog); + me.focus(); + } + buttons[0].focus(); + for (var i = 0; i < buttons.length; ++i) { + var b = buttons[i]; + (function(callback) { + CodeMirror.on(b, "click", function(e) { + CodeMirror.e_preventDefault(e); + close(); + if (callback) callback(me); + }); + })(callbacks[i]); + CodeMirror.on(b, "blur", function() { + --blurring; + setTimeout(function() { if (blurring <= 0) close(); }, 200); + }); + CodeMirror.on(b, "focus", function() { ++blurring; }); + } + }); + + /* + * openNotification + * Opens a notification, that can be closed with an optional timer + * (default 5000ms timer) and always closes on click. + * + * If a notification is opened while another is opened, it will close the + * currently opened one and open the new one immediately. + */ + CodeMirror.defineExtension("openNotification", function(template, options) { + closeNotification(this, close); + var dialog = dialogDiv(this, template, options && options.bottom); + var closed = false, doneTimer; + var duration = options && typeof options.duration !== "undefined" ? options.duration : 5000; + + function close() { + if (closed) return; + closed = true; + clearTimeout(doneTimer); + dialog.parentNode.removeChild(dialog); + } + + CodeMirror.on(dialog, 'click', function(e) { + CodeMirror.e_preventDefault(e); + close(); + }); + + if (duration) + doneTimer = setTimeout(close, duration); + + return close; + }); +}); diff --git a/modules/editor/codemirror/addon/display/autorefresh.min.js b/modules/editor/codemirror/addon/display/autorefresh.min.js @@ -0,0 +1,47 @@ +// 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.defineOption("autoRefresh", false, function(cm, val) { + if (cm.state.autoRefresh) { + stopListening(cm, cm.state.autoRefresh) + cm.state.autoRefresh = null + } + if (val && cm.display.wrapper.offsetHeight == 0) + startListening(cm, cm.state.autoRefresh = {delay: val.delay || 250}) + }) + + function startListening(cm, state) { + function check() { + if (cm.display.wrapper.offsetHeight) { + stopListening(cm, state) + if (cm.display.lastWrapHeight != cm.display.wrapper.clientHeight) + cm.refresh() + } else { + state.timeout = setTimeout(check, state.delay) + } + } + state.timeout = setTimeout(check, state.delay) + state.hurry = function() { + clearTimeout(state.timeout) + state.timeout = setTimeout(check, 50) + } + CodeMirror.on(window, "mouseup", state.hurry) + CodeMirror.on(window, "keyup", state.hurry) + } + + function stopListening(_cm, state) { + clearTimeout(state.timeout) + CodeMirror.off(window, "mouseup", state.hurry) + CodeMirror.off(window, "keyup", state.hurry) + } +}); diff --git a/modules/editor/codemirror/addon/display/fullscreen.js b/modules/editor/codemirror/addon/display/fullscreen.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"; + + CodeMirror.defineOption("fullScreen", false, function(cm, val, old) { + if (old == CodeMirror.Init) old = false; + if (!old == !val) return; + if (val) setFullscreen(cm); + else setNormal(cm); + }); + + function setFullscreen(cm) { + var wrap = cm.getWrapperElement(); + cm.state.fullScreenRestore = {scrollTop: window.pageYOffset, scrollLeft: window.pageXOffset, + width: wrap.style.width, height: wrap.style.height}; + wrap.style.width = ""; + wrap.style.height = "auto"; + wrap.className += " CodeMirror-fullscreen"; + document.documentElement.style.overflow = "hidden"; + cm.refresh(); + } + + function setNormal(cm) { + var wrap = cm.getWrapperElement(); + wrap.className = wrap.className.replace(/\s*CodeMirror-fullscreen\b/, ""); + document.documentElement.style.overflow = ""; + var info = cm.state.fullScreenRestore; + wrap.style.width = info.width; wrap.style.height = info.height; + window.scrollTo(info.scrollLeft, info.scrollTop); + cm.refresh(); + } +}); diff --git a/modules/editor/codemirror/addon/display/fullscreen.min.js b/modules/editor/codemirror/addon/display/fullscreen.min.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"; + + CodeMirror.defineOption("fullScreen", false, function(cm, val, old) { + if (old == CodeMirror.Init) old = false; + if (!old == !val) return; + if (val) setFullscreen(cm); + else setNormal(cm); + }); + + function setFullscreen(cm) { + var wrap = cm.getWrapperElement(); + cm.state.fullScreenRestore = {scrollTop: window.pageYOffset, scrollLeft: window.pageXOffset, + width: wrap.style.width, height: wrap.style.height}; + wrap.style.width = ""; + wrap.style.height = "auto"; + wrap.className += " CodeMirror-fullscreen"; + document.documentElement.style.overflow = "hidden"; + cm.refresh(); + } + + function setNormal(cm) { + var wrap = cm.getWrapperElement(); + wrap.className = wrap.className.replace(/\s*CodeMirror-fullscreen\b/, ""); + document.documentElement.style.overflow = ""; + var info = cm.state.fullScreenRestore; + wrap.style.width = info.width; wrap.style.height = info.height; + window.scrollTo(info.scrollLeft, info.scrollTop); + cm.refresh(); + } +}); diff --git a/modules/editor/codemirror/addon/display/panel.min.js b/modules/editor/codemirror/addon/display/panel.min.js @@ -0,0 +1,123 @@ +// 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.defineExtension("addPanel", function(node, options) { + options = options || {}; + + if (!this.state.panels) initPanels(this); + + var info = this.state.panels; + var wrapper = info.wrapper; + var cmWrapper = this.getWrapperElement(); + + if (options.after instanceof Panel && !options.after.cleared) { + wrapper.insertBefore(node, options.before.node.nextSibling); + } else if (options.before instanceof Panel && !options.before.cleared) { + wrapper.insertBefore(node, options.before.node); + } else if (options.replace instanceof Panel && !options.replace.cleared) { + wrapper.insertBefore(node, options.replace.node); + options.replace.clear(); + } else if (options.position == "bottom") { + wrapper.appendChild(node); + } else if (options.position == "before-bottom") { + wrapper.insertBefore(node, cmWrapper.nextSibling); + } else if (options.position == "after-top") { + wrapper.insertBefore(node, cmWrapper); + } else { + wrapper.insertBefore(node, wrapper.firstChild); + } + + var height = (options && options.height) || node.offsetHeight; + this._setSize(null, info.heightLeft -= height); + info.panels++; + if (options.stable && isAtTop(this, node)) + this.scrollTo(null, this.getScrollInfo().top + height) + + return new Panel(this, node, options, height); + }); + + function Panel(cm, node, options, height) { + this.cm = cm; + this.node = node; + this.options = options; + this.height = height; + this.cleared = false; + } + + Panel.prototype.clear = function() { + if (this.cleared) return; + this.cleared = true; + var info = this.cm.state.panels; + this.cm._setSize(null, info.heightLeft += this.height); + if (this.options.stable && isAtTop(this.cm, this.node)) + this.cm.scrollTo(null, this.cm.getScrollInfo().top - this.height) + info.wrapper.removeChild(this.node); + if (--info.panels == 0) removePanels(this.cm); + }; + + Panel.prototype.changed = function(height) { + var newHeight = height == null ? this.node.offsetHeight : height; + var info = this.cm.state.panels; + this.cm._setSize(null, info.heightLeft -= (newHeight - this.height)); + this.height = newHeight; + }; + + function initPanels(cm) { + var wrap = cm.getWrapperElement(); + var style = window.getComputedStyle ? window.getComputedStyle(wrap) : wrap.currentStyle; + var height = parseInt(style.height); + var info = cm.state.panels = { + setHeight: wrap.style.height, + heightLeft: height, + panels: 0, + wrapper: document.createElement("div") + }; + wrap.parentNode.insertBefore(info.wrapper, wrap); + var hasFocus = cm.hasFocus(); + info.wrapper.appendChild(wrap); + if (hasFocus) cm.focus(); + + cm._setSize = cm.setSize; + if (height != null) cm.setSize = function(width, newHeight) { + if (newHeight == null) return this._setSize(width, newHeight); + info.setHeight = newHeight; + if (typeof newHeight != "number") { + var px = /^(\d+\.?\d*)px$/.exec(newHeight); + if (px) { + newHeight = Number(px[1]); + } else { + info.wrapper.style.height = newHeight; + newHeight = info.wrapper.offsetHeight; + info.wrapper.style.height = ""; + } + } + cm._setSize(width, info.heightLeft += (newHeight - height)); + height = newHeight; + }; + } + + function removePanels(cm) { + var info = cm.state.panels; + cm.state.panels = null; + + var wrap = cm.getWrapperElement(); + info.wrapper.parentNode.replaceChild(wrap, info.wrapper); + wrap.style.height = info.setHeight; + cm.setSize = cm._setSize; + cm.setSize(); + } + + function isAtTop(cm, dom) { + for (var sibling = dom.nextSibling; sibling; sibling = sibling.nextSibling) + if (sibling == cm.getWrapperElement()) return true + return false + } +}); diff --git a/modules/editor/codemirror/addon/display/rulers.js b/modules/editor/codemirror/addon/display/rulers.js @@ -0,0 +1,51 @@ +// 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.defineOption("rulers", false, function(cm, val) { + if (cm.state.rulerDiv) { + cm.state.rulerDiv.parentElement.removeChild(cm.state.rulerDiv) + cm.state.rulerDiv = null + cm.off("refresh", drawRulers) + } + if (val && val.length) { + cm.state.rulerDiv = cm.display.lineSpace.parentElement.insertBefore(document.createElement("div"), cm.display.lineSpace) + cm.state.rulerDiv.className = "CodeMirror-rulers" + drawRulers(cm) + cm.on("refresh", drawRulers) + } + }); + + function drawRulers(cm) { + cm.state.rulerDiv.textContent = "" + var val = cm.getOption("rulers"); + var cw = cm.defaultCharWidth(); + var left = cm.charCoords(CodeMirror.Pos(cm.firstLine(), 0), "div").left; + cm.state.rulerDiv.style.minHeight = (cm.display.scroller.offsetHeight + 30) + "px"; + for (var i = 0; i < val.length; i++) { + var elt = document.createElement("div"); + elt.className = "CodeMirror-ruler"; + var col, conf = val[i]; + if (typeof conf == "number") { + col = conf; + } else { + col = conf.column; + if (conf.className) elt.className += " " + conf.className; + if (conf.color) elt.style.borderColor = conf.color; + if (conf.lineStyle) elt.style.borderLeftStyle = conf.lineStyle; + if (conf.width) elt.style.borderLeftWidth = conf.width; + } + elt.style.left = (left + col * cw) + "px"; + cm.state.rulerDiv.appendChild(elt) + } + } +}); diff --git a/modules/editor/codemirror/addon/display/rulers.min.js b/modules/editor/codemirror/addon/display/rulers.min.js @@ -0,0 +1,51 @@ +// 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.defineOption("rulers", false, function(cm, val) { + if (cm.state.rulerDiv) { + cm.state.rulerDiv.parentElement.removeChild(cm.state.rulerDiv) + cm.state.rulerDiv = null + cm.off("refresh", drawRulers) + } + if (val && val.length) { + cm.state.rulerDiv = cm.display.lineSpace.parentElement.insertBefore(document.createElement("div"), cm.display.lineSpace) + cm.state.rulerDiv.className = "CodeMirror-rulers" + drawRulers(cm) + cm.on("refresh", drawRulers) + } + }); + + function drawRulers(cm) { + cm.state.rulerDiv.textContent = "" + var val = cm.getOption("rulers"); + var cw = cm.defaultCharWidth(); + var left = cm.charCoords(CodeMirror.Pos(cm.firstLine(), 0), "div").left; + cm.state.rulerDiv.style.minHeight = (cm.display.scroller.offsetHeight + 30) + "px"; + for (var i = 0; i < val.length; i++) { + var elt = document.createElement("div"); + elt.className = "CodeMirror-ruler"; + var col, conf = val[i]; + if (typeof conf == "number") { + col = conf; + } else { + col = conf.column; + if (conf.className) elt.className += " " + conf.className; + if (conf.color) elt.style.borderColor = conf.color; + if (conf.lineStyle) elt.style.borderLeftStyle = conf.lineStyle; + if (conf.width) elt.style.borderLeftWidth = conf.width; + } + elt.style.left = (left + col * cw) + "px"; + cm.state.rulerDiv.appendChild(elt) + } + } +}); diff --git a/modules/editor/codemirror/addon/hint/anyword-hint.min.js b/modules/editor/codemirror/addon/hint/anyword-hint.min.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/xml-hint.js b/modules/editor/codemirror/addon/hint/xml-hint.js @@ -0,0 +1,110 @@ +// 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 getHints(cm, options) { + var tags = options && options.schemaInfo; + var quote = (options && options.quoteChar) || '"'; + if (!tags) return; + var cur = cm.getCursor(), token = cm.getTokenAt(cur); + if (token.end > cur.ch) { + token.end = cur.ch; + token.string = token.string.slice(0, cur.ch - token.start); + } + var inner = CodeMirror.innerMode(cm.getMode(), token.state); + if (inner.mode.name != "xml") return; + var result = [], replaceToken = false, prefix; + var tag = /\btag\b/.test(token.type) && !/>$/.test(token.string); + var tagName = tag && /^\w/.test(token.string), tagStart; + + if (tagName) { + var before = cm.getLine(cur.line).slice(Math.max(0, token.start - 2), token.start); + var tagType = /<\/$/.test(before) ? "close" : /<$/.test(before) ? "open" : null; + if (tagType) tagStart = token.start - (tagType == "close" ? 2 : 1); + } else if (tag && token.string == "<") { + tagType = "open"; + } else if (tag && token.string == "</") { + tagType = "close"; + } + + if (!tag && !inner.state.tagName || tagType) { + if (tagName) + prefix = token.string; + replaceToken = tagType; + var cx = inner.state.context, curTag = cx && tags[cx.tagName]; + var childList = cx ? curTag && curTag.children : tags["!top"]; + if (childList && tagType != "close") { + for (var i = 0; i < childList.length; ++i) if (!prefix || childList[i].lastIndexOf(prefix, 0) == 0) + result.push("<" + childList[i]); + } else if (tagType != "close") { + for (var name in tags) + if (tags.hasOwnProperty(name) && name != "!top" && name != "!attrs" && (!prefix || name.lastIndexOf(prefix, 0) == 0)) + result.push("<" + name); + } + if (cx && (!prefix || tagType == "close" && cx.tagName.lastIndexOf(prefix, 0) == 0)) + result.push("</" + cx.tagName + ">"); + } else { + // Attribute completion + var curTag = tags[inner.state.tagName], attrs = curTag && curTag.attrs; + var globalAttrs = tags["!attrs"]; + if (!attrs && !globalAttrs) return; + if (!attrs) { + attrs = globalAttrs; + } else if (globalAttrs) { // Combine tag-local and global attributes + var set = {}; + for (var nm in globalAttrs) if (globalAttrs.hasOwnProperty(nm)) set[nm] = globalAttrs[nm]; + for (var nm in attrs) if (attrs.hasOwnProperty(nm)) set[nm] = attrs[nm]; + attrs = set; + } + if (token.type == "string" || token.string == "=") { // A value + var before = cm.getRange(Pos(cur.line, Math.max(0, cur.ch - 60)), + Pos(cur.line, token.type == "string" ? token.start : token.end)); + var atName = before.match(/([^\s\u00a0=<>\"\']+)=$/), atValues; + if (!atName || !attrs.hasOwnProperty(atName[1]) || !(atValues = attrs[atName[1]])) return; + if (typeof atValues == 'function') atValues = atValues.call(this, cm); // Functions can be used to supply values for autocomplete widget + if (token.type == "string") { + prefix = token.string; + var n = 0; + if (/['"]/.test(token.string.charAt(0))) { + quote = token.string.charAt(0); + prefix = token.string.slice(1); + n++; + } + var len = token.string.length; + if (/['"]/.test(token.string.charAt(len - 1))) { + quote = token.string.charAt(len - 1); + prefix = token.string.substr(n, len - 2); + } + replaceToken = true; + } + for (var i = 0; i < atValues.length; ++i) if (!prefix || atValues[i].lastIndexOf(prefix, 0) == 0) + result.push(quote + atValues[i] + quote); + } else { // An attribute name + if (token.type == "attribute") { + prefix = token.string; + replaceToken = true; + } + for (var attr in attrs) if (attrs.hasOwnProperty(attr) && (!prefix || attr.lastIndexOf(prefix, 0) == 0)) + result.push(attr); + } + } + return { + list: result, + from: replaceToken ? Pos(cur.line, tagStart == null ? token.start : tagStart) : cur, + to: replaceToken ? Pos(cur.line, token.end) : cur + }; + } + + CodeMirror.registerHelper("hint", "xml", getHints); +}); diff --git a/modules/editor/codemirror/addon/lint/css-lint.js b/modules/editor/codemirror/addon/lint/css-lint.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/merge/merge.css b/modules/editor/codemirror/addon/merge/merge.css @@ -0,0 +1,113 @@ +.CodeMirror-merge { + position: relative; + border: 1px solid #ddd; + white-space: pre; +} + +.CodeMirror-merge, .CodeMirror-merge .CodeMirror { + height: 350px; +} + +.CodeMirror-merge-2pane .CodeMirror-merge-pane { width: 47%; } +.CodeMirror-merge-2pane .CodeMirror-merge-gap { width: 6%; } +.CodeMirror-merge-3pane .CodeMirror-merge-pane { width: 31%; } +.CodeMirror-merge-3pane .CodeMirror-merge-gap { width: 3.5%; } + +.CodeMirror-merge-pane { + display: inline-block; + white-space: normal; + vertical-align: top; +} +.CodeMirror-merge-pane-rightmost { + position: absolute; + right: 0px; + z-index: 1; +} + +.CodeMirror-merge-gap { + z-index: 2; + display: inline-block; + height: 100%; + -moz-box-sizing: border-box; + box-sizing: border-box; + overflow: hidden; + border-left: 1px solid #ddd; + border-right: 1px solid #ddd; + position: relative; + background: #f8f8f8; +} + +.CodeMirror-merge-scrolllock-wrap { + position: absolute; + bottom: 0; left: 50%; +} +.CodeMirror-merge-scrolllock { + position: relative; + left: -50%; + cursor: pointer; + color: #555; + line-height: 1; +} + +.CodeMirror-merge-copybuttons-left, .CodeMirror-merge-copybuttons-right { + position: absolute; + left: 0; top: 0; + right: 0; bottom: 0; + line-height: 1; +} + +.CodeMirror-merge-copy { + position: absolute; + cursor: pointer; + color: #44c; + z-index: 3; +} + +.CodeMirror-merge-copy-reverse { + position: absolute; + cursor: pointer; + color: #44c; +} + +.CodeMirror-merge-copybuttons-left .CodeMirror-merge-copy { left: 2px; } +.CodeMirror-merge-copybuttons-right .CodeMirror-merge-copy { right: 2px; } + +.CodeMirror-merge-r-inserted, .CodeMirror-merge-l-inserted { + background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAACCAYAAACddGYaAAAAGUlEQVQI12MwuCXy3+CWyH8GBgYGJgYkAABZbAQ9ELXurwAAAABJRU5ErkJggg==); + background-position: bottom left; + background-repeat: repeat-x; +} + +.CodeMirror-merge-r-deleted, .CodeMirror-merge-l-deleted { + background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAACCAYAAACddGYaAAAAGUlEQVQI12M4Kyb2/6yY2H8GBgYGJgYkAABURgPz6Ks7wQAAAABJRU5ErkJggg==); + background-position: bottom left; + background-repeat: repeat-x; +} + +.CodeMirror-merge-r-chunk { background: #ffffe0; } +.CodeMirror-merge-r-chunk-start { border-top: 1px solid #ee8; } +.CodeMirror-merge-r-chunk-end { border-bottom: 1px solid #ee8; } +.CodeMirror-merge-r-connect { fill: #ffffe0; stroke: #ee8; stroke-width: 1px; } + +.CodeMirror-merge-l-chunk { background: #eef; } +.CodeMirror-merge-l-chunk-start { border-top: 1px solid #88e; } +.CodeMirror-merge-l-chunk-end { border-bottom: 1px solid #88e; } +.CodeMirror-merge-l-connect { fill: #eef; stroke: #88e; stroke-width: 1px; } + +.CodeMirror-merge-l-chunk.CodeMirror-merge-r-chunk { background: #dfd; } +.CodeMirror-merge-l-chunk-start.CodeMirror-merge-r-chunk-start { border-top: 1px solid #4e4; } +.CodeMirror-merge-l-chunk-end.CodeMirror-merge-r-chunk-end { border-bottom: 1px solid #4e4; } + +.CodeMirror-merge-collapsed-widget:before { + content: "(...)"; +} +.CodeMirror-merge-collapsed-widget { + cursor: pointer; + color: #88b; + background: #eef; + border: 1px solid #ddf; + font-size: 90%; + padding: 0 3px; + border-radius: 4px; +} +.CodeMirror-merge-collapsed-line .CodeMirror-gutter-elt { display: none; } diff --git a/modules/editor/codemirror/addon/mode/loadmode.min.js b/modules/editor/codemirror/addon/mode/loadmode.min.js @@ -0,0 +1,64 @@ +// 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"), "cjs"); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], function(CM) { mod(CM, "amd"); }); + else // Plain browser env + mod(CodeMirror, "plain"); +})(function(CodeMirror, env) { + if (!CodeMirror.modeURL) CodeMirror.modeURL = "../mode/%N/%N.js"; + + var loading = {}; + function splitCallback(cont, n) { + var countDown = n; + return function() { if (--countDown == 0) cont(); }; + } + function ensureDeps(mode, cont) { + var deps = CodeMirror.modes[mode].dependencies; + if (!deps) return cont(); + var missing = []; + for (var i = 0; i < deps.length; ++i) { + if (!CodeMirror.modes.hasOwnProperty(deps[i])) + missing.push(deps[i]); + } + if (!missing.length) return cont(); + var split = splitCallback(cont, missing.length); + for (var i = 0; i < missing.length; ++i) + CodeMirror.requireMode(missing[i], split); + } + + CodeMirror.requireMode = function(mode, cont) { + if (typeof mode != "string") mode = mode.name; + if (CodeMirror.modes.hasOwnProperty(mode)) return ensureDeps(mode, cont); + if (loading.hasOwnProperty(mode)) return loading[mode].push(cont); + + var file = CodeMirror.modeURL.replace(/%N/g, mode); + if (env == "plain") { + var script = document.createElement("script"); + script.src = file; + var others = document.getElementsByTagName("script")[0]; + var list = loading[mode] = [cont]; + CodeMirror.on(script, "load", function() { + ensureDeps(mode, function() { + for (var i = 0; i < list.length; ++i) list[i](); + }); + }); + others.parentNode.insertBefore(script, others); + } else if (env == "cjs") { + require(file); + cont(); + } else if (env == "amd") { + requirejs([file], cont); + } + }; + + CodeMirror.autoLoadMode = function(instance, mode) { + if (!CodeMirror.modes.hasOwnProperty(mode)) + CodeMirror.requireMode(mode, function() { + instance.setOption("mode", instance.getOption("mode")); + }); + }; +}); diff --git a/modules/editor/codemirror/addon/runmode/runmode.node.min.js b/modules/editor/codemirror/addon/runmode/runmode.node.min.js @@ -0,0 +1,197 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +/* Just enough of CodeMirror to run runMode under node.js */ + +function splitLines(string){return string.split(/\r\n?|\n/);}; + +// Counts the column offset in a string, taking tabs into account. +// Used mostly to find indentation. +var countColumn = exports.countColumn = function(string, end, tabSize, startIndex, startValue) { + if (end == null) { + end = string.search(/[^\s\u00a0]/); + if (end == -1) end = string.length; + } + for (var i = startIndex || 0, n = startValue || 0;;) { + var nextTab = string.indexOf("\t", i); + if (nextTab < 0 || nextTab >= end) + return n + (end - i); + n += nextTab - i; + n += tabSize - (n % tabSize); + i = nextTab + 1; + } +}; + +function StringStream(string, tabSize, context) { + this.pos = this.start = 0; + this.string = string; + this.tabSize = tabSize || 8; + this.lastColumnPos = this.lastColumnValue = 0; + this.lineStart = 0; + this.context = context +}; + +StringStream.prototype = { + eol: function() {return this.pos >= this.string.length;}, + sol: function() {return this.pos == this.lineStart;}, + peek: function() {return this.string.charAt(this.pos) || undefined;}, + next: function() { + if (this.pos < this.string.length) + return this.string.charAt(this.pos++); + }, + eat: function(match) { + var ch = this.string.charAt(this.pos); + if (typeof match == "string") var ok = ch == match; + else var ok = ch && (match.test ? match.test(ch) : match(ch)); + if (ok) {++this.pos; return ch;} + }, + eatWhile: function(match) { + var start = this.pos; + while (this.eat(match)){} + return this.pos > start; + }, + eatSpace: function() { + var start = this.pos; + while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; + return this.pos > start; + }, + skipToEnd: function() {this.pos = this.string.length;}, + skipTo: function(ch) { + var found = this.string.indexOf(ch, this.pos); + if (found > -1) {this.pos = found; return true;} + }, + backUp: function(n) {this.pos -= n;}, + column: function() { + if (this.lastColumnPos < this.start) { + this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); + this.lastColumnPos = this.start; + } + return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); + }, + indentation: function() { + return countColumn(this.string, null, this.tabSize) - + (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); + }, + match: function(pattern, consume, caseInsensitive) { + if (typeof pattern == "string") { + var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;}; + var substr = this.string.substr(this.pos, pattern.length); + if (cased(substr) == cased(pattern)) { + if (consume !== false) this.pos += pattern.length; + return true; + } + } else { + var match = this.string.slice(this.pos).match(pattern); + if (match && match.index > 0) return null; + if (match && consume !== false) this.pos += match[0].length; + return match; + } + }, + current: function(){return this.string.slice(this.start, this.pos);}, + hideFirstChars: function(n, inner) { + this.lineStart += n; + try { return inner(); } + finally { this.lineStart -= n; } + }, + lookAhead: function(n) { + var line = this.context.line + n + return line >= this.context.lines.length ? null : this.context.lines[line] + } +}; +exports.StringStream = StringStream; + +exports.startState = function(mode, a1, a2) { + return mode.startState ? mode.startState(a1, a2) : true; +}; + +var modes = exports.modes = {}, mimeModes = exports.mimeModes = {}; +exports.defineMode = function(name, mode) { + if (arguments.length > 2) + mode.dependencies = Array.prototype.slice.call(arguments, 2); + modes[name] = mode; +}; +exports.defineMIME = function(mime, spec) { mimeModes[mime] = spec; }; + +exports.defineMode("null", function() { + return {token: function(stream) {stream.skipToEnd();}}; +}); +exports.defineMIME("text/plain", "null"); + +exports.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"}; +}; + +function copyObj(obj, target, overwrite) { + if (!target) target = {}; + for (var prop in obj) + if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) + target[prop] = obj[prop]; + return target; +} + +// This can be used to attach properties to mode objects from +// outside the actual mode definition. +var modeExtensions = exports.modeExtensions = {}; +exports.extendMode = function(mode, properties) { + var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); + copyObj(properties, exts); +}; + +exports.getMode = function(options, spec) { + var spec = exports.resolveMode(spec); + var mfactory = modes[spec.name]; + if (!mfactory) return exports.getMode(options, "text/plain"); + var modeObj = mfactory(options, spec); + if (modeExtensions.hasOwnProperty(spec.name)) { + var exts = modeExtensions[spec.name]; + for (var prop in exts) { + if (!exts.hasOwnProperty(prop)) continue; + if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop]; + modeObj[prop] = exts[prop]; + } + } + modeObj.name = spec.name; + if (spec.helperType) modeObj.helperType = spec.helperType; + if (spec.modeProps) for (var prop in spec.modeProps) + modeObj[prop] = spec.modeProps[prop]; + + return modeObj; +}; + +exports.innerMode = function(mode, state) { + var info; + while (mode.innerMode) { + info = mode.innerMode(state); + if (!info || info.mode == mode) break; + state = info.state; + mode = info.mode; + } + return info || {mode: mode, state: state}; +} + +exports.registerHelper = exports.registerGlobalHelper = Math.min; + +exports.runMode = function(string, modespec, callback, options) { + var mode = exports.getMode({indentUnit: 2}, modespec); + var lines = splitLines(string), state = (options && options.state) || exports.startState(mode); + var context = {lines: lines, line: 0} + for (var i = 0, e = lines.length; i < e; ++i, ++context.line) { + if (i) callback("\n"); + var stream = new exports.StringStream(lines[i], 4, context); + 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; + } + } +}; + +require.cache[require.resolve("../../lib/codemirror")] = require.cache[require.resolve("./runmode.node")]; +require.cache[require.resolve("../../addon/runmode/runmode")] = require.cache[require.resolve("./runmode.node")]; diff --git a/modules/editor/codemirror/addon/scroll/scrollpastend.js b/modules/editor/codemirror/addon/scroll/scrollpastend.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"; + + CodeMirror.defineOption("scrollPastEnd", false, function(cm, val, old) { + if (old && old != CodeMirror.Init) { + cm.off("change", onChange); + cm.off("refresh", updateBottomMargin); + cm.display.lineSpace.parentNode.style.paddingBottom = ""; + cm.state.scrollPastEndPadding = null; + } + if (val) { + cm.on("change", onChange); + cm.on("refresh", updateBottomMargin); + updateBottomMargin(cm); + } + }); + + function onChange(cm, change) { + if (CodeMirror.changeEnd(change).line == cm.lastLine()) + updateBottomMargin(cm); + } + + function updateBottomMargin(cm) { + var padding = ""; + if (cm.lineCount() > 1) { + var totalH = cm.display.scroller.clientHeight - 30, + lastLineH = cm.getLineHandle(cm.lastLine()).height; + padding = (totalH - lastLineH) + "px"; + } + if (cm.state.scrollPastEndPadding != padding) { + cm.state.scrollPastEndPadding = padding; + cm.display.lineSpace.parentNode.style.paddingBottom = padding; + cm.off("refresh", updateBottomMargin); + cm.setSize(); + cm.on("refresh", updateBottomMargin); + } + } +}); diff --git a/modules/editor/codemirror/addon/search/search.min.js b/modules/editor/codemirror/addon/search/search.min.js @@ -0,0 +1,252 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// Define search commands. Depends on dialog.js or another +// implementation of the openDialog method. + +// Replace works a little oddly -- it will do the replace on the next +// Ctrl-G (or whatever is bound to findNext) press. You prevent a +// replace by making sure the match is no longer selected when hitting +// Ctrl-G. + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror"), require("./searchcursor"), require("../dialog/dialog")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror", "./searchcursor", "../dialog/dialog"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + function searchOverlay(query, caseInsensitive) { + if (typeof query == "string") + query = new RegExp(query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), caseInsensitive ? "gi" : "g"); + else if (!query.global) + query = new RegExp(query.source, query.ignoreCase ? "gi" : "g"); + + return {token: function(stream) { + query.lastIndex = stream.pos; + var match = query.exec(stream.string); + if (match && match.index == stream.pos) { + stream.pos += match[0].length || 1; + return "searching"; + } else if (match) { + stream.pos = match.index; + } else { + stream.skipToEnd(); + } + }}; + } + + function SearchState() { + this.posFrom = this.posTo = this.lastQuery = this.query = null; + this.overlay = null; + } + + function getSearchState(cm) { + return cm.state.search || (cm.state.search = new SearchState()); + } + + function queryCaseInsensitive(query) { + return typeof query == "string" && query == query.toLowerCase(); + } + + function getSearchCursor(cm, query, pos) { + // Heuristic: if the query string is all lowercase, do a case insensitive search. + return cm.getSearchCursor(query, pos, {caseFold: queryCaseInsensitive(query), multiline: true}); + } + + function persistentDialog(cm, text, deflt, onEnter, onKeyDown) { + cm.openDialog(text, onEnter, { + value: deflt, + selectValueOnOpen: true, + closeOnEnter: false, + onClose: function() { clearSearch(cm); }, + onKeyDown: onKeyDown + }); + } + + function dialog(cm, text, shortText, deflt, f) { + if (cm.openDialog) cm.openDialog(text, f, {value: deflt, selectValueOnOpen: true}); + else f(prompt(shortText, deflt)); + } + + function confirmDialog(cm, text, shortText, fs) { + if (cm.openConfirm) cm.openConfirm(text, fs); + else if (confirm(shortText)) fs[0](); + } + + function parseString(string) { + return string.replace(/\\(.)/g, function(_, ch) { + if (ch == "n") return "\n" + if (ch == "r") return "\r" + return ch + }) + } + + function parseQuery(query) { + var isRE = query.match(/^\/(.*)\/([a-z]*)$/); + if (isRE) { + try { query = new RegExp(isRE[1], isRE[2].indexOf("i") == -1 ? "" : "i"); } + catch(e) {} // Not a regular expression after all, do a string search + } else { + query = parseString(query) + } + if (typeof query == "string" ? query == "" : query.test("")) + query = /x^/; + return query; + } + + var queryDialog = + '<span class="CodeMirror-search-label">Search:</span> <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">(Use /re/ syntax for regexp search)</span>'; + + function startSearch(cm, state, query) { + state.queryText = query; + state.query = parseQuery(query); + cm.removeOverlay(state.overlay, queryCaseInsensitive(state.query)); + state.overlay = searchOverlay(state.query, queryCaseInsensitive(state.query)); + cm.addOverlay(state.overlay); + if (cm.showMatchesOnScrollbar) { + if (state.annotate) { state.annotate.clear(); state.annotate = null; } + state.annotate = cm.showMatchesOnScrollbar(state.query, queryCaseInsensitive(state.query)); + } + } + + function doSearch(cm, rev, persistent, immediate) { + var state = getSearchState(cm); + if (state.query) return findNext(cm, rev); + var q = cm.getSelection() || state.lastQuery; + if (q instanceof RegExp && q.source == "x^") q = null + if (persistent && cm.openDialog) { + var hiding = null + var searchNext = function(query, event) { + CodeMirror.e_stop(event); + if (!query) return; + if (query != state.queryText) { + startSearch(cm, state, query); + state.posFrom = state.posTo = cm.getCursor(); + } + if (hiding) hiding.style.opacity = 1 + findNext(cm, event.shiftKey, function(_, to) { + var dialog + if (to.line < 3 && document.querySelector && + (dialog = cm.display.wrapper.querySelector(".CodeMirror-dialog")) && + dialog.getBoundingClientRect().bottom - 4 > cm.cursorCoords(to, "window").top) + (hiding = dialog).style.opacity = .4 + }) + }; + persistentDialog(cm, queryDialog, q, searchNext, function(event, query) { + var keyName = CodeMirror.keyName(event) + var extra = cm.getOption('extraKeys'), cmd = (extra && extra[keyName]) || CodeMirror.keyMap[cm.getOption("keyMap")][keyName] + if (cmd == "findNext" || cmd == "findPrev" || + cmd == "findPersistentNext" || cmd == "findPersistentPrev") { + CodeMirror.e_stop(event); + startSearch(cm, getSearchState(cm), query); + cm.execCommand(cmd); + } else if (cmd == "find" || cmd == "findPersistent") { + CodeMirror.e_stop(event); + searchNext(query, event); + } + }); + if (immediate && q) { + startSearch(cm, state, q); + findNext(cm, rev); + } + } else { + dialog(cm, queryDialog, "Search for:", q, function(query) { + if (query && !state.query) cm.operation(function() { + startSearch(cm, state, query); + state.posFrom = state.posTo = cm.getCursor(); + findNext(cm, rev); + }); + }); + } + } + + function findNext(cm, rev, callback) {cm.operation(function() { + var state = getSearchState(cm); + var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo); + if (!cursor.find(rev)) { + cursor = getSearchCursor(cm, state.query, rev ? CodeMirror.Pos(cm.lastLine()) : CodeMirror.Pos(cm.firstLine(), 0)); + if (!cursor.find(rev)) return; + } + cm.setSelection(cursor.from(), cursor.to()); + cm.scrollIntoView({from: cursor.from(), to: cursor.to()}, 20); + state.posFrom = cursor.from(); state.posTo = cursor.to(); + if (callback) callback(cursor.from(), cursor.to()) + });} + + function clearSearch(cm) {cm.operation(function() { + var state = getSearchState(cm); + state.lastQuery = state.query; + if (!state.query) return; + state.query = state.queryText = null; + cm.removeOverlay(state.overlay); + if (state.annotate) { state.annotate.clear(); state.annotate = null; } + });} + + var replaceQueryDialog = + ' <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">(Use /re/ syntax for regexp search)</span>'; + var replacementQueryDialog = '<span class="CodeMirror-search-label">With:</span> <input type="text" style="width: 10em" class="CodeMirror-search-field"/>'; + var doReplaceConfirm = '<span class="CodeMirror-search-label">Replace?</span> <button>Yes</button> <button>No</button> <button>All</button> <button>Stop</button>'; + + function replaceAll(cm, query, text) { + cm.operation(function() { + for (var cursor = getSearchCursor(cm, query); cursor.findNext();) { + if (typeof query != "string") { + var match = cm.getRange(cursor.from(), cursor.to()).match(query); + cursor.replace(text.replace(/\$(\d)/g, function(_, i) {return match[i];})); + } else cursor.replace(text); + } + }); + } + + function replace(cm, all) { + if (cm.getOption("readOnly")) return; + var query = cm.getSelection() || getSearchState(cm).lastQuery; + var dialogText = '<span class="CodeMirror-search-label">' + (all ? 'Replace all:' : 'Replace:') + '</span>'; + dialog(cm, dialogText + replaceQueryDialog, dialogText, query, function(query) { + if (!query) return; + query = parseQuery(query); + dialog(cm, replacementQueryDialog, "Replace with:", "", function(text) { + text = parseString(text) + if (all) { + replaceAll(cm, query, text) + } else { + clearSearch(cm); + var cursor = getSearchCursor(cm, query, cm.getCursor("from")); + var advance = function() { + var start = cursor.from(), match; + if (!(match = cursor.findNext())) { + cursor = getSearchCursor(cm, query); + if (!(match = cursor.findNext()) || + (start && cursor.from().line == start.line && cursor.from().ch == start.ch)) return; + } + cm.setSelection(cursor.from(), cursor.to()); + cm.scrollIntoView({from: cursor.from(), to: cursor.to()}); + confirmDialog(cm, doReplaceConfirm, "Replace?", + [function() {doReplace(match);}, advance, + function() {replaceAll(cm, query, text)}]); + }; + var doReplace = function(match) { + cursor.replace(typeof query == "string" ? text : + text.replace(/\$(\d)/g, function(_, i) {return match[i];})); + advance(); + }; + advance(); + } + }); + }); + } + + CodeMirror.commands.find = function(cm) {clearSearch(cm); doSearch(cm);}; + CodeMirror.commands.findPersistent = function(cm) {clearSearch(cm); doSearch(cm, false, true);}; + CodeMirror.commands.findPersistentNext = function(cm) {doSearch(cm, false, true, true);}; + CodeMirror.commands.findPersistentPrev = function(cm) {doSearch(cm, true, true, true);}; + CodeMirror.commands.findNext = doSearch; + CodeMirror.commands.findPrev = function(cm) {doSearch(cm, true);}; + CodeMirror.commands.clearSearch = clearSearch; + CodeMirror.commands.replace = replace; + CodeMirror.commands.replaceAll = function(cm) {replace(cm, true);}; +}); diff --git a/modules/editor/codemirror/bin/compress b/modules/editor/codemirror/bin/compress @@ -0,0 +1,92 @@ +#!/usr/bin/env node + +// Compression helper for CodeMirror +// +// Example: +// +// bin/compress codemirror runmode javascript xml +// +// Will take lib/codemirror.js, addon/runmode/runmode.js, +// mode/javascript/javascript.js, and mode/xml/xml.js, run them though +// the online minifier at http://marijnhaverbeke.nl/uglifyjs, and spit +// out the result. +// +// bin/compress codemirror --local /path/to/bin/UglifyJS +// +// Will use a local minifier instead of the online default one. +// +// Script files are specified without .js ending. Prefixing them with +// their full (local) path is optional. So you may say lib/codemirror +// or mode/xml/xml to be more precise. In fact, even the .js suffix +// may be specified, if wanted. + +"use strict"; + +var fs = require("fs"); + +function help(ok) { + console.log("usage: " + process.argv[1] + " [--local /path/to/uglifyjs] files..."); + process.exit(ok ? 0 : 1); +} + +var local = null, args = [], extraArgs = null, files = [], blob = ""; + +for (var i = 2; i < process.argv.length; ++i) { + var arg = process.argv[i]; + if (arg == "--local" && i + 1 < process.argv.length) { + var parts = process.argv[++i].split(/\s+/); + local = parts[0]; + extraArgs = parts.slice(1); + if (!extraArgs.length) extraArgs = ["-c", "-m"]; + } else if (arg == "--help") { + help(true); + } else if (arg[0] != "-") { + files.push({name: arg, re: new RegExp("(?:\\/|^)" + arg + (/\.js$/.test(arg) ? "$" : "\\.js$"))}); + } else help(false); +} + +function walk(dir) { + fs.readdirSync(dir).forEach(function(fname) { + if (/^[_\.]/.test(fname)) return; + var file = dir + fname; + if (fs.statSync(file).isDirectory()) return walk(file + "/"); + if (files.some(function(spec, i) { + var match = spec.re.test(file); + if (match) files.splice(i, 1); + return match; + })) { + if (local) args.push(file); + else blob += fs.readFileSync(file, "utf8"); + } + }); +} + +walk("lib/"); +walk("addon/"); +walk("mode/"); + +if (!local && !blob) help(false); + +if (files.length) { + console.log("Some specified files were not found: " + + files.map(function(a){return a.name;}).join(", ")); + process.exit(1); +} + +if (local) { + require("child_process").spawn(local, args.concat(extraArgs), {stdio: ["ignore", process.stdout, process.stderr]}); +} else { + var data = new Buffer("js_code=" + require("querystring").escape(blob), "utf8"); + var req = require("http").request({ + host: "marijnhaverbeke.nl", + port: 80, + method: "POST", + path: "/uglifyjs", + headers: {"content-type": "application/x-www-form-urlencoded", + "content-length": data.length} + }); + req.on("response", function(resp) { + resp.on("data", function (chunk) { process.stdout.write(chunk); }); + }); + req.end(data); +} diff --git a/modules/editor/codemirror/demo/anywordhint.html b/modules/editor/codemirror/demo/anywordhint.html @@ -0,0 +1,79 @@ +<!doctype html> + +<title>CodeMirror: Any Word Completion 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/hint/show-hint.css"> +<script src="../lib/codemirror.js"></script> +<script src="../addon/hint/show-hint.js"></script> +<script src="../addon/hint/anyword-hint.js"></script> +<script src="../mode/javascript/javascript.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="#">Any Word Completion</a> + </ul> +</div> + +<article> +<h2>Any Word Completion Demo</h2> +<form><textarea id="code" name="code"> +(function() { + "use strict"; + + var WORD = /[\w$]+/g, 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 start = cur.ch, end = start; + while (end < curLine.length && word.test(curLine.charAt(end))) ++end; + while (start && word.test(curLine.charAt(start - 1))) --start; + var curWord = start != end && curLine.slice(start, end); + + var list = [], seen = {}; + function scan(dir) { + var line = cur.line, end = Math.min(Math.max(line + dir * range, editor.firstLine()), editor.lastLine()) + dir; + for (; line != end; line += dir) { + var text = editor.getLine(line), m; + word.lastIndex = 0; + while (m = word.exec(text)) { + if ((!curWord || m[0].indexOf(curWord) == 0) && !seen.hasOwnProperty(m[0])) { + seen[m[0]] = true; + list.push(m[0]); + } + } + } + } + scan(-1); + scan(1); + return {list: list, from: CodeMirror.Pos(cur.line, start), to: CodeMirror.Pos(cur.line, end)}; + }); +})(); +</textarea></form> + +<p>Press <strong>ctrl-space</strong> to activate autocompletion. The +completion uses +the <a href="../doc/manual.html#addon_anyword-hint">anyword-hint.js</a> +module, which simply looks at nearby words in the buffer and completes +to those.</p> + + <script> + CodeMirror.commands.autocomplete = function(cm) { + cm.showHint({hint: CodeMirror.hint.anyword}); + } + var editor = CodeMirror.fromTextArea(document.getElementById("code"), { + lineNumbers: true, + extraKeys: {"Ctrl-Space": "autocomplete"} + }); + </script> + </article> diff --git a/modules/editor/codemirror/demo/bidi.html b/modules/editor/codemirror/demo/bidi.html @@ -0,0 +1,106 @@ +<!doctype html> + +<title>CodeMirror: Bi-directional Text 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> +<style type="text/css"> + .CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;} + fieldset {border: none} +</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="#">Bi-directional Text</a> + </ul> +</div> + +<article> +<h2>Bi-directional Text Demo</h2> +<form><textarea id="code" name="code"><!-- Piece of the CodeMirror manual, 'translated' into Arabic by Google Translate --> +<!-- قطعة من دليل CodeMirror، "ترجم" إلى العربية بواسطة جوجل ترجمة --> + +<dl> + <dt id=option_value><code>value (string or Doc)</code></dt> + <dd>قيمة البداية المحرر. يمكن أن تكون سلسلة، أو. كائن مستند.</dd> + <dt id=option_mode><code>mode (string or object)</code></dt> + <dd>وضع الاستخدام. عندما لا تعطى، وهذا الافتراضي إلى الطريقة الاولى + التي تم تحميلها. قد يكون من سلسلة، والتي إما أسماء أو ببساطة هو وضع + MIME نوع المرتبطة اسطة. بدلا من ذلك، قد يكون من كائن يحتوي على + خيارات التكوين لواسطة، مع <code>name</code> الخاصية التي وضع أسماء + (على سبيل المثال <code>{name: "javascript", json: true}</code>). + صفحات التجريبي لكل وضع تحتوي على معلومات حول ما معلمات تكوين وضع + يدعمها. يمكنك أن تطلب CodeMirror التي تم تعريفها طرق وأنواع MIME + الكشف على <code>CodeMirror.modes</code> + و <code>CodeMirror.mimeModes</code> الكائنات. وضع خرائط الأسماء + الأولى لمنشئات الخاصة بهم، وخرائط لأنواع MIME 2 المواصفات + واسطة.</dd> + <dt id=option_theme><code>theme (string)</code></dt> + <dd>موضوع لنمط المحرر مع. يجب عليك التأكد من الملف CSS تحديد + المقابلة <code>.cm-s-[name]</code> يتم تحميل أنماط (انظر + <a href="../theme/"><code>theme</code></a> الدليل في التوزيع). + الافتراضي هو <code>"default"</code> ، والتي تم تضمينها في + الألوان <code>codemirror.css</code>. فمن الممكن استخدام فئات متعددة + في تطبيق السمات مرة واحدة على سبيل المثال <code>"foo bar"</code> + سيتم تعيين كل من <code>cm-s-foo</code> و <code>cm-s-bar</code> + الطبقات إلى المحرر.</dd> +</dl> +</textarea> + <fieldset> + Editor default direction: + <input type="radio" id="ltr" name="direction"/><label for="ltr">LTR</label> + <input type="radio" id="rtl" name="direction"/><label for="rtl">RTL</label> + </fieldset> + <fieldset> + HTML document direction: + <input type="radio" id="htmlltr" name="htmldirection"/><label for="htmlltr">LTR</label> + <input type="radio" id="htmlrtl" name="htmldirection"/><label for="htmlrtl">RTL</label> + </fieldset> + <fieldset> + <input type="checkbox" id="rtlMoveVisually"/><label for="rtlMoveVisually">Use visual order for arrow key movement.</label> + </fieldset> +</form> + + <script> +var editor = CodeMirror.fromTextArea(document.getElementById("code"), { + mode: "text/html", + lineNumbers: true, + lineWrapping: true, + direction: "rtl" +}); + +var dirRadios = {ltr: document.getElementById("ltr"), + rtl: document.getElementById("rtl")}; +dirRadios[editor.getOption("direction")].checked = true; +dirRadios["rtl"].onchange = dirRadios["ltr"].onchange = function() { + editor.setOption("direction", dirRadios["rtl"].checked ? "rtl" : "ltr"); +}; + +var HtmlDirRadios = {ltr: document.getElementById("htmlltr"), + rtl: document.getElementById("htmlrtl")}; +HtmlDirRadios["ltr"].checked = true; +HtmlDirRadios["rtl"].onchange = HtmlDirRadios["ltr"].onchange = function() { + document.dir = (HtmlDirRadios["rtl"].checked ? "rtl" : "ltr"); +}; + +var moveCheckbox = document.getElementById("rtlMoveVisually"); +moveCheckbox.checked = editor.getOption("rtlMoveVisually"); +moveCheckbox.onchange = function() { + editor.setOption("rtlMoveVisually", moveCheckbox.checked); +}; +</script> + + <p>Demonstration of bi-directional text support. See + the <a href="http://marijnhaverbeke.nl/blog/cursor-in-bidi-text.html">related + blog post</a> for more background.</p> + +</article> diff --git a/modules/editor/codemirror/demo/preview.html b/modules/editor/codemirror/demo/preview.html @@ -0,0 +1,87 @@ +<!doctype html> + +<title>CodeMirror: HTML5 preview</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=../mode/javascript/javascript.js></script> +<script src=../mode/css/css.js></script> +<script src=../mode/htmlmixed/htmlmixed.js></script> +<style type=text/css> + .CodeMirror { + float: left; + width: 50%; + border: 1px solid black; + } + iframe { + width: 49%; + float: left; + height: 300px; + border: 1px solid black; + border-left: 0px; + } + </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="#">HTML5 preview</a> + </ul> +</div> + +<article> +<h2>HTML5 preview</h2> + + <textarea id=code name=code> +<!doctype html> +<html> + <head> + <meta charset=utf-8> + <title>HTML5 canvas demo</title> + <style>p {font-family: monospace;}</style> + </head> + <body> + <p>Canvas pane goes here:</p> + <canvas id=pane width=300 height=200></canvas> + <script> + var canvas = document.getElementById('pane'); + var context = canvas.getContext('2d'); + + context.fillStyle = 'rgb(250,0,0)'; + context.fillRect(10, 10, 55, 50); + + context.fillStyle = 'rgba(0, 0, 250, 0.5)'; + context.fillRect(30, 30, 55, 50); + </script> + </body> +</html></textarea> + <iframe id=preview></iframe> + <script> + var delay; + // Initialize CodeMirror editor with a nice html5 canvas demo. + var editor = CodeMirror.fromTextArea(document.getElementById('code'), { + mode: 'text/html' + }); + editor.on("change", function() { + clearTimeout(delay); + delay = setTimeout(updatePreview, 300); + }); + + function updatePreview() { + var previewFrame = document.getElementById('preview'); + var preview = previewFrame.contentDocument || previewFrame.contentWindow.document; + preview.open(); + preview.write(editor.getValue()); + preview.close(); + } + setTimeout(updatePreview, 300); + </script> + </article> diff --git a/modules/editor/codemirror/demo/simplescrollbars.html b/modules/editor/codemirror/demo/simplescrollbars.html @@ -0,0 +1,82 @@ +<!doctype html> + +<title>CodeMirror: Simple Scrollbar 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/scroll/simplescrollbars.css"> +<script src="../lib/codemirror.js"></script> +<script src="../mode/markdown/markdown.js"></script> +<script src="../mode/xml/xml.js"></script> +<script src="../addon/scroll/simplescrollbars.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="#">Simple Scrollbar</a> + </ul> +</div> + +<article> +<h2>Simple Scrollbar Demo</h2> +<form><textarea id="code" name="code"># Custom Scrollbars + +This is a piece of text that creates scrollbars + +Lorem ipsum dolor sit amet, turpis nec facilisis neque vestibulum adipiscing, magna nunc est luctus orci a, +aliquam duis ad volutpat nostra. Vestibulum ultricies suspendisse commodo volutpat pede sed. Bibendum odio +dignissim, ad vitae mollis ac sed nibh quis, suspendisse diam, risus quas blandit phasellus luctus nec, +integer nunc vitae posuere scelerisque. Lobortis quam porta conubia nulla. Et nisl ac, imperdiet vitae ac. +Parturient sit. Et vestibulum euismod, rutrum nunc libero mauris purus convallis. Cum id adipiscing et eget +pretium rutrum, ultrices sapien magnis fringilla sit lorem, eu vitae scelerisque ipsum aliquet, magna sed +fusce vel. + +Lectus ultricies libero dolor convallis, sed etiam vel hendrerit egestas viverra, at urna mauris, eget +vulputate dolor voluptatem, nulla eget sollicitudin. Sed tincidunt, elit sociis. Mattis mi tortor dui id +sodales mi, maecenas nam fringilla risus turpis mauris praesent, imperdiet maecenas ultrices nonummy tellus +quis est. Scelerisque nec pharetra quis varius fringilla. Varius vestibulum non dictum pharetra, tincidunt in +vestibulum iaculis molestie, id condimentum blandit elit urna magna pulvinar, quam suspendisse pellentesque +donec. Vel amet ad ac. Nec aut viverra, morbi mi neque massa, turpis enim proin. Tellus eu, fermentum velit +est convallis aliquam velit, rutrum in diam lacus, praesent tempor pellentesque dictum semper augue. Felis +explicabo massa amet lectus phasellus dolor. Ut lorem quis arcu neque felis ultricies, senectus vitae +curabitur sed pellentesque et, id sed risus in sed ac accumsan, blandit arcu quam duis nunc. + +Sed leo sollicitudin odio vitae, purus sit egestas, justo eros inceptos auctor fermentum lectus. Ligula luctus +turpis, quod massa vitae elementum orci, nullam fringilla elit tortor. Justo ante tempor amet quam posuere +volutpat. Facilisis pede erat ut hac ultrices ipsum, wisi duis sit metus. Dolor vitae est sed sed vitae. Sed +eu ligula, morbi vestibulum nunc nibh velit ut taciti, ligula elit semper sagittis in, auctor arcu vel eget. +Mauris at vitae nec suspendisse et, aenean proin blandit suscipit. Morbi quam, dolor ultricies. Viverra +tempus. Suspendisse sit dapibus, ac fuga aenean, magna nisl nonummy augue posuere, dictum ut fuga velit +parturient augue interdum, mattis sit tellus. + +Vehicula commodo tempus curabitur eros, lacinia erat vulputate lorem vel fermentum donec, lectus sed conubia +id pellentesque. Vel senectus donec pede aliquet dolor sit, nec vivamus justo placerat interdum maecenas, +sodales euismod. Quis netus sapien amet, vestibulum quam nec amet lacinia, quis aliquet, tempor vivamus tellus +enim, suscipit quis eleifend. Amet class phasellus orci pretium, risus in nulla. Neque sit ullamcorper, +ultricies platea id nec suspendisse ac. Et elementum. Dictum nam, ut dui fermentum egestas facilisis elit +augue, adipiscing donec ipsum erat nam pellentesque convallis, vestibulum vestibulum risus id nulla ut mauris, +curabitur aute aptent. Ultrices orci wisi dui ipsum praesent, pharetra felis eu quis. Est fringilla etiam, +maxime sem dapibus et eget, mi enim dignissim nec pretium, augue vehicula, volutpat proin. Et occaecati +lobortis viverra, cum in sed, vivamus tellus. Libero at malesuada est vivamus leo tortor. +</textarea></form> + +<p>The <a href="../doc/manual.html#addon_simplescrollbars"><code>simplescrollbars</code></a> addon defines two +styles of non-native scrollbars: <a href="javascript:editor.setOption('scrollbarStyle', 'simple')"><code>"simple"</code></a> and <a href="javascript:editor.setOption('scrollbarStyle', 'overlay')"><code>"overlay"</code></a> (click to try), which can be passed to +the <a href="../doc/manual.html#option_scrollbarStyle"><code>scrollbarStyle</code></a> option. These implement +the scrollbar using DOM elements, allowing more control over +its <a href="../addon/scroll/simplescrollbars.css">appearance</a>.</p> + + <script> + var editor = CodeMirror.fromTextArea(document.getElementById("code"), { + lineNumbers: true, + scrollbarStyle: "simple" + }); + </script> +</article> diff --git a/modules/editor/codemirror/demo/xmlcomplete.html b/modules/editor/codemirror/demo/xmlcomplete.html @@ -0,0 +1,119 @@ +<!doctype html> + +<title>CodeMirror: XML Autocomplete 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/hint/show-hint.css"> +<script src="../lib/codemirror.js"></script> +<script src="../addon/hint/show-hint.js"></script> +<script src="../addon/hint/xml-hint.js"></script> +<script src="../mode/xml/xml.js"></script> +<style type="text/css"> + .CodeMirror { border: 1px solid #eee; } + </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="#">XML Autocomplete</a> + </ul> +</div> + +<article> +<h2>XML Autocomplete Demo</h2> +<form><textarea id="code" name="code"><!-- write some xml below --> +</textarea></form> + + <p>Press <strong>ctrl-space</strong>, or type a '&lt;' character to + activate autocompletion. This demo defines a simple schema that + guides completion. The schema can be customized—see + the <a href="../doc/manual.html#addon_xml-hint">manual</a>.</p> + + <p>Development of the <code>xml-hint</code> addon was kindly + sponsored + by <a href="http://www.xperiment.mobi">www.xperiment.mobi</a>.</p> + + <script> + var dummy = { + attrs: { + color: ["red", "green", "blue", "purple", "white", "black", "yellow"], + size: ["large", "medium", "small"], + description: null + }, + children: [] + }; + + var tags = { + "!top": ["top"], + "!attrs": { + id: null, + class: ["A", "B", "C"] + }, + top: { + attrs: { + lang: ["en", "de", "fr", "nl"], + freeform: null + }, + children: ["animal", "plant"] + }, + animal: { + attrs: { + name: null, + isduck: ["yes", "no"] + }, + children: ["wings", "feet", "body", "head", "tail"] + }, + plant: { + attrs: {name: null}, + children: ["leaves", "stem", "flowers"] + }, + wings: dummy, feet: dummy, body: dummy, head: dummy, tail: dummy, + leaves: dummy, stem: dummy, flowers: dummy + }; + + function completeAfter(cm, pred) { + var cur = cm.getCursor(); + if (!pred || pred()) setTimeout(function() { + if (!cm.state.completionActive) + cm.showHint({completeSingle: false}); + }, 100); + return CodeMirror.Pass; + } + + function completeIfAfterLt(cm) { + return completeAfter(cm, function() { + var cur = cm.getCursor(); + return cm.getRange(CodeMirror.Pos(cur.line, cur.ch - 1), cur) == "<"; + }); + } + + function completeIfInTag(cm) { + return completeAfter(cm, function() { + var tok = cm.getTokenAt(cm.getCursor()); + if (tok.type == "string" && (!/['"]/.test(tok.string.charAt(tok.string.length - 1)) || tok.string.length == 1)) return false; + var inner = CodeMirror.innerMode(cm.getMode(), tok.state).state; + return inner.tagName; + }); + } + + var editor = CodeMirror.fromTextArea(document.getElementById("code"), { + mode: "xml", + lineNumbers: true, + extraKeys: { + "'<'": completeAfter, + "'/'": completeIfAfterLt, + "' '": completeIfInTag, + "'='": completeIfInTag, + "Ctrl-Space": "autocomplete" + }, + hintOptions: {schemaInfo: tags} + }); + </script> + </article> diff --git a/modules/editor/codemirror/doc/activebookmark.js b/modules/editor/codemirror/doc/activebookmark.js @@ -0,0 +1,57 @@ +// Kludge in HTML5 tag recognition in IE8 +document.createElement("section"); +document.createElement("article"); + +(function() { + if (!window.addEventListener) return; + var pending = false, prevVal = null; + + function updateSoon() { + if (!pending) { + pending = true; + setTimeout(update, 250); + } + } + + function update() { + pending = false; + var marks = document.getElementById("nav").getElementsByTagName("a"), found; + for (var i = 0; i < marks.length; ++i) { + var mark = marks[i], m; + if (mark.getAttribute("data-default")) { + if (found == null) found = i; + } else if (m = mark.href.match(/#(.*)/)) { + var ref = document.getElementById(m[1]); + if (ref && ref.getBoundingClientRect().top < 50) + found = i; + } + } + if (found != null && found != prevVal) { + prevVal = found; + var lis = document.getElementById("nav").getElementsByTagName("li"); + for (var i = 0; i < lis.length; ++i) lis[i].className = ""; + for (var i = 0; i < marks.length; ++i) { + if (found == i) { + marks[i].className = "active"; + for (var n = marks[i]; n; n = n.parentNode) + if (n.nodeName == "LI") n.className = "active"; + } else { + marks[i].className = ""; + } + } + } + } + + window.addEventListener("scroll", updateSoon); + window.addEventListener("load", updateSoon); + window.addEventListener("hashchange", function() { + setTimeout(function() { + var hash = document.location.hash, found = null, m; + var marks = document.getElementById("nav").getElementsByTagName("a"); + for (var i = 0; i < marks.length; i++) + if ((m = marks[i].href.match(/(#.*)/)) && m[1] == hash) { found = i; break; } + if (found != null) for (var i = 0; i < marks.length; i++) + marks[i].className = i == found ? "active" : ""; + }, 300); + }); +})(); diff --git a/modules/editor/codemirror/doc/yinyang.png b/modules/editor/codemirror/doc/yinyang.png Binary files differ. diff --git a/modules/editor/codemirror/keymap/vim.min.js b/modules/editor/codemirror/keymap/vim.min.js @@ -0,0 +1,5212 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +/** + * Supported keybindings: + * Too many to list. Refer to defaultKeyMap below. + * + * Supported Ex commands: + * Refer to defaultExCommandMap below. + * + * Registers: unnamed, -, a-z, A-Z, 0-9 + * (Does not respect the special case for number registers when delete + * operator is made with these commands: %, (, ), , /, ?, n, N, {, } ) + * TODO: Implement the remaining registers. + * + * Marks: a-z, A-Z, and 0-9 + * TODO: Implement the remaining special marks. They have more complex + * behavior. + * + * Events: + * 'vim-mode-change' - raised on the editor anytime the current mode changes, + * Event object: {mode: "visual", subMode: "linewise"} + * + * Code structure: + * 1. Default keymap + * 2. Variable declarations and short basic helpers + * 3. Instance (External API) implementation + * 4. Internal state tracking objects (input state, counter) implementation + * and instantiation + * 5. Key handler (the main command dispatcher) implementation + * 6. Motion, operator, and action implementations + * 7. Helper functions for the key handler, motions, operators, and actions + * 8. Set up Vim to work as a keymap for CodeMirror. + * 9. Ex command implementations. + */ + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../lib/codemirror"), require("../addon/search/searchcursor"), require("../addon/dialog/dialog"), require("../addon/edit/matchbrackets.js")); + else if (typeof define == "function" && define.amd) // AMD + define(["../lib/codemirror", "../addon/search/searchcursor", "../addon/dialog/dialog", "../addon/edit/matchbrackets"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + 'use strict'; + + var defaultKeymap = [ + // Key to key mapping. This goes first to make it possible to override + // existing mappings. + { keys: '<Left>', type: 'keyToKey', toKeys: 'h' }, + { keys: '<Right>', type: 'keyToKey', toKeys: 'l' }, + { keys: '<Up>', type: 'keyToKey', toKeys: 'k' }, + { keys: '<Down>', type: 'keyToKey', toKeys: 'j' }, + { keys: '<Space>', type: 'keyToKey', toKeys: 'l' }, + { keys: '<BS>', type: 'keyToKey', toKeys: 'h', context: 'normal'}, + { keys: '<C-Space>', type: 'keyToKey', toKeys: 'W' }, + { keys: '<C-BS>', type: 'keyToKey', toKeys: 'B', context: 'normal' }, + { keys: '<S-Space>', type: 'keyToKey', toKeys: 'w' }, + { keys: '<S-BS>', type: 'keyToKey', toKeys: 'b', context: 'normal' }, + { keys: '<C-n>', type: 'keyToKey', toKeys: 'j' }, + { keys: '<C-p>', type: 'keyToKey', toKeys: 'k' }, + { keys: '<C-[>', type: 'keyToKey', toKeys: '<Esc>' }, + { keys: '<C-c>', type: 'keyToKey', toKeys: '<Esc>' }, + { keys: '<C-[>', type: 'keyToKey', toKeys: '<Esc>', context: 'insert' }, + { keys: '<C-c>', type: 'keyToKey', toKeys: '<Esc>', context: 'insert' }, + { keys: 's', type: 'keyToKey', toKeys: 'cl', context: 'normal' }, + { keys: 's', type: 'keyToKey', toKeys: 'c', context: 'visual'}, + { keys: 'S', type: 'keyToKey', toKeys: 'cc', context: 'normal' }, + { keys: 'S', type: 'keyToKey', toKeys: 'VdO', context: 'visual' }, + { keys: '<Home>', type: 'keyToKey', toKeys: '0' }, + { keys: '<End>', type: 'keyToKey', toKeys: '$' }, + { keys: '<PageUp>', type: 'keyToKey', toKeys: '<C-b>' }, + { keys: '<PageDown>', type: 'keyToKey', toKeys: '<C-f>' }, + { keys: '<CR>', type: 'keyToKey', toKeys: 'j^', context: 'normal' }, + { keys: '<Ins>', type: 'action', action: 'toggleOverwrite', context: 'insert' }, + // Motions + { keys: 'H', type: 'motion', motion: 'moveToTopLine', motionArgs: { linewise: true, toJumplist: true }}, + { keys: 'M', type: 'motion', motion: 'moveToMiddleLine', motionArgs: { linewise: true, toJumplist: true }}, + { keys: 'L', type: 'motion', motion: 'moveToBottomLine', motionArgs: { linewise: true, toJumplist: true }}, + { keys: 'h', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: false }}, + { keys: 'l', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: true }}, + { keys: 'j', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, linewise: true }}, + { keys: 'k', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, linewise: true }}, + { keys: 'gj', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: true }}, + { keys: 'gk', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: false }}, + { keys: 'w', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false }}, + { keys: 'W', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false, bigWord: true }}, + { keys: 'e', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, inclusive: true }}, + { keys: 'E', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, bigWord: true, inclusive: true }}, + { keys: 'b', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }}, + { keys: 'B', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false, bigWord: true }}, + { keys: 'ge', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, inclusive: true }}, + { keys: 'gE', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, bigWord: true, inclusive: true }}, + { keys: '{', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: false, toJumplist: true }}, + { keys: '}', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: true, toJumplist: true }}, + { keys: '<C-f>', type: 'motion', motion: 'moveByPage', motionArgs: { forward: true }}, + { keys: '<C-b>', type: 'motion', motion: 'moveByPage', motionArgs: { forward: false }}, + { keys: '<C-d>', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: true, explicitRepeat: true }}, + { keys: '<C-u>', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: false, explicitRepeat: true }}, + { keys: 'gg', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: false, explicitRepeat: true, linewise: true, toJumplist: true }}, + { keys: 'G', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: true, explicitRepeat: true, linewise: true, toJumplist: true }}, + { keys: '0', type: 'motion', motion: 'moveToStartOfLine' }, + { keys: '^', type: 'motion', motion: 'moveToFirstNonWhiteSpaceCharacter' }, + { keys: '+', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true }}, + { keys: '-', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, toFirstChar:true }}, + { keys: '_', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true, repeatOffset:-1 }}, + { keys: '$', type: 'motion', motion: 'moveToEol', motionArgs: { inclusive: true }}, + { keys: '%', type: 'motion', motion: 'moveToMatchedSymbol', motionArgs: { inclusive: true, toJumplist: true }}, + { keys: 'f<character>', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: true , inclusive: true }}, + { keys: 'F<character>', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: false }}, + { keys: 't<character>', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: true, inclusive: true }}, + { keys: 'T<character>', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: false }}, + { keys: ';', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: true }}, + { keys: ',', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: false }}, + { keys: '\'<character>', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true, linewise: true}}, + { keys: '`<character>', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true}}, + { keys: ']`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true } }, + { keys: '[`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false } }, + { keys: ']\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true, linewise: true } }, + { keys: '[\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false, linewise: true } }, + // the next two aren't motions but must come before more general motion declarations + { keys: ']p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true, matchIndent: true}}, + { keys: '[p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true, matchIndent: true}}, + { keys: ']<character>', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: true, toJumplist: true}}, + { keys: '[<character>', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: false, toJumplist: true}}, + { keys: '|', type: 'motion', motion: 'moveToColumn'}, + { keys: 'o', type: 'motion', motion: 'moveToOtherHighlightedEnd', context:'visual'}, + { keys: 'O', type: 'motion', motion: 'moveToOtherHighlightedEnd', motionArgs: {sameLine: true}, context:'visual'}, + // Operators + { keys: 'd', type: 'operator', operator: 'delete' }, + { keys: 'y', type: 'operator', operator: 'yank' }, + { keys: 'c', type: 'operator', operator: 'change' }, + { keys: '>', type: 'operator', operator: 'indent', operatorArgs: { indentRight: true }}, + { keys: '<', type: 'operator', operator: 'indent', operatorArgs: { indentRight: false }}, + { keys: 'g~', type: 'operator', operator: 'changeCase' }, + { keys: 'gu', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, isEdit: true }, + { keys: 'gU', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, isEdit: true }, + { keys: 'n', type: 'motion', motion: 'findNext', motionArgs: { forward: true, toJumplist: true }}, + { keys: 'N', type: 'motion', motion: 'findNext', motionArgs: { forward: false, toJumplist: true }}, + // Operator-Motion dual commands + { keys: 'x', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorMotionArgs: { visualLine: false }}, + { keys: 'X', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: false }, operatorMotionArgs: { visualLine: true }}, + { keys: 'D', type: 'operatorMotion', operator: 'delete', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'}, + { keys: 'D', type: 'operator', operator: 'delete', operatorArgs: { linewise: true }, context: 'visual'}, + { keys: 'Y', type: 'operatorMotion', operator: 'yank', motion: 'expandToLine', motionArgs: { linewise: true }, context: 'normal'}, + { keys: 'Y', type: 'operator', operator: 'yank', operatorArgs: { linewise: true }, context: 'visual'}, + { keys: 'C', type: 'operatorMotion', operator: 'change', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'}, + { keys: 'C', type: 'operator', operator: 'change', operatorArgs: { linewise: true }, context: 'visual'}, + { keys: '~', type: 'operatorMotion', operator: 'changeCase', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorArgs: { shouldMoveCursor: true }, context: 'normal'}, + { keys: '~', type: 'operator', operator: 'changeCase', context: 'visual'}, + { keys: '<C-w>', type: 'operatorMotion', operator: 'delete', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }, context: 'insert' }, + // Actions + { keys: '<C-i>', type: 'action', action: 'jumpListWalk', actionArgs: { forward: true }}, + { keys: '<C-o>', type: 'action', action: 'jumpListWalk', actionArgs: { forward: false }}, + { keys: '<C-e>', type: 'action', action: 'scroll', actionArgs: { forward: true, linewise: true }}, + { keys: '<C-y>', type: 'action', action: 'scroll', actionArgs: { forward: false, linewise: true }}, + { keys: 'a', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'charAfter' }, context: 'normal' }, + { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'eol' }, context: 'normal' }, + { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'endOfSelectedArea' }, context: 'visual' }, + { keys: 'i', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'inplace' }, context: 'normal' }, + { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'firstNonBlank'}, context: 'normal' }, + { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'startOfSelectedArea' }, context: 'visual' }, + { keys: 'o', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: true }, context: 'normal' }, + { keys: 'O', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: false }, context: 'normal' }, + { keys: 'v', type: 'action', action: 'toggleVisualMode' }, + { keys: 'V', type: 'action', action: 'toggleVisualMode', actionArgs: { linewise: true }}, + { keys: '<C-v>', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }}, + { keys: '<C-q>', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }}, + { keys: 'gv', type: 'action', action: 'reselectLastSelection' }, + { keys: 'J', type: 'action', action: 'joinLines', isEdit: true }, + { keys: 'p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true }}, + { keys: 'P', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true }}, + { keys: 'r<character>', type: 'action', action: 'replace', isEdit: true }, + { keys: '@<character>', type: 'action', action: 'replayMacro' }, + { keys: 'q<character>', type: 'action', action: 'enterMacroRecordMode' }, + // Handle Replace-mode as a special case of insert mode. + { keys: 'R', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { replace: true }}, + { keys: 'u', type: 'action', action: 'undo', context: 'normal' }, + { keys: 'u', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, context: 'visual', isEdit: true }, + { keys: 'U', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, context: 'visual', isEdit: true }, + { keys: '<C-r>', type: 'action', action: 'redo' }, + { keys: 'm<character>', type: 'action', action: 'setMark' }, + { keys: '"<character>', type: 'action', action: 'setRegister' }, + { keys: 'zz', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }}, + { keys: 'z.', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }, motion: 'moveToFirstNonWhiteSpaceCharacter' }, + { keys: 'zt', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }}, + { keys: 'z<CR>', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }, motion: 'moveToFirstNonWhiteSpaceCharacter' }, + { keys: 'z-', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }}, + { keys: 'zb', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }, motion: 'moveToFirstNonWhiteSpaceCharacter' }, + { keys: '.', type: 'action', action: 'repeatLastEdit' }, + { keys: '<C-a>', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: true, backtrack: false}}, + { keys: '<C-x>', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: false, backtrack: false}}, + { keys: '<C-t>', type: 'action', action: 'indent', actionArgs: { indentRight: true }, context: 'insert' }, + { keys: '<C-d>', type: 'action', action: 'indent', actionArgs: { indentRight: false }, context: 'insert' }, + // Text object motions + { keys: 'a<character>', type: 'motion', motion: 'textObjectManipulation' }, + { keys: 'i<character>', type: 'motion', motion: 'textObjectManipulation', motionArgs: { textObjectInner: true }}, + // Search + { keys: '/', type: 'search', searchArgs: { forward: true, querySrc: 'prompt', toJumplist: true }}, + { keys: '?', type: 'search', searchArgs: { forward: false, querySrc: 'prompt', toJumplist: true }}, + { keys: '*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }}, + { keys: '#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }}, + { keys: 'g*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', toJumplist: true }}, + { keys: 'g#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', toJumplist: true }}, + // Ex command + { keys: ':', type: 'ex' } + ]; + + /** + * Ex commands + * Care must be taken when adding to the default Ex command map. For any + * pair of commands that have a shared prefix, at least one of their + * shortNames must not match the prefix of the other command. + */ + var defaultExCommandMap = [ + { name: 'colorscheme', shortName: 'colo' }, + { name: 'map' }, + { name: 'imap', shortName: 'im' }, + { name: 'nmap', shortName: 'nm' }, + { name: 'vmap', shortName: 'vm' }, + { name: 'unmap' }, + { name: 'write', shortName: 'w' }, + { name: 'undo', shortName: 'u' }, + { name: 'redo', shortName: 'red' }, + { name: 'set', shortName: 'se' }, + { name: 'set', shortName: 'se' }, + { name: 'setlocal', shortName: 'setl' }, + { name: 'setglobal', shortName: 'setg' }, + { name: 'sort', shortName: 'sor' }, + { name: 'substitute', shortName: 's', possiblyAsync: true }, + { name: 'nohlsearch', shortName: 'noh' }, + { name: 'yank', shortName: 'y' }, + { name: 'delmarks', shortName: 'delm' }, + { name: 'registers', shortName: 'reg', excludeFromCommandHistory: true }, + { name: 'global', shortName: 'g' } + ]; + + var Pos = CodeMirror.Pos; + + var Vim = function() { + function enterVimMode(cm) { + cm.setOption('disableInput', true); + cm.setOption('showCursorWhenSelecting', false); + CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"}); + cm.on('cursorActivity', onCursorActivity); + maybeInitVimState(cm); + CodeMirror.on(cm.getInputField(), 'paste', getOnPasteFn(cm)); + } + + function leaveVimMode(cm) { + cm.setOption('disableInput', false); + cm.off('cursorActivity', onCursorActivity); + CodeMirror.off(cm.getInputField(), 'paste', getOnPasteFn(cm)); + cm.state.vim = null; + } + + function detachVimMap(cm, next) { + if (this == CodeMirror.keyMap.vim) { + CodeMirror.rmClass(cm.getWrapperElement(), "cm-fat-cursor"); + if (cm.getOption("inputStyle") == "contenteditable" && document.body.style.caretColor != null) { + disableFatCursorMark(cm); + cm.getInputField().style.caretColor = ""; + } + } + + if (!next || next.attach != attachVimMap) + leaveVimMode(cm); + } + function attachVimMap(cm, prev) { + if (this == CodeMirror.keyMap.vim) { + CodeMirror.addClass(cm.getWrapperElement(), "cm-fat-cursor"); + if (cm.getOption("inputStyle") == "contenteditable" && document.body.style.caretColor != null) { + enableFatCursorMark(cm); + cm.getInputField().style.caretColor = "transparent"; + } + } + + if (!prev || prev.attach != attachVimMap) + enterVimMode(cm); + } + + function fatCursorMarks(cm) { + var ranges = cm.listSelections(), result = [] + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i] + if (range.empty()) { + if (range.anchor.ch < cm.getLine(range.anchor.line).length) { + result.push(cm.markText(range.anchor, Pos(range.anchor.line, range.anchor.ch + 1), + {className: "cm-fat-cursor-mark"})) + } else { + var widget = document.createElement("span") + widget.textContent = "\u00a0" + widget.className = "cm-fat-cursor-mark" + result.push(cm.setBookmark(range.anchor, {widget: widget})) + } + } + } + return result + } + + function updateFatCursorMark(cm) { + var marks = cm.state.fatCursorMarks + if (marks) for (var i = 0; i < marks.length; i++) marks[i].clear() + cm.state.fatCursorMarks = fatCursorMarks(cm) + } + + function enableFatCursorMark(cm) { + cm.state.fatCursorMarks = fatCursorMarks(cm) + cm.on("cursorActivity", updateFatCursorMark) + } + + function disableFatCursorMark(cm) { + var marks = cm.state.fatCursorMarks + if (marks) for (var i = 0; i < marks.length; i++) marks[i].clear() + cm.state.fatCursorMarks = null + cm.off("cursorActivity", updateFatCursorMark) + } + + // Deprecated, simply setting the keymap works again. + CodeMirror.defineOption('vimMode', false, function(cm, val, prev) { + if (val && cm.getOption("keyMap") != "vim") + cm.setOption("keyMap", "vim"); + else if (!val && prev != CodeMirror.Init && /^vim/.test(cm.getOption("keyMap"))) + cm.setOption("keyMap", "default"); + }); + + function cmKey(key, cm) { + if (!cm) { return undefined; } + if (this[key]) { return this[key]; } + var vimKey = cmKeyToVimKey(key); + if (!vimKey) { + return false; + } + var cmd = CodeMirror.Vim.findKey(cm, vimKey); + if (typeof cmd == 'function') { + CodeMirror.signal(cm, 'vim-keypress', vimKey); + } + return cmd; + } + + var modifiers = {'Shift': 'S', 'Ctrl': 'C', 'Alt': 'A', 'Cmd': 'D', 'Mod': 'A'}; + var specialKeys = {Enter:'CR',Backspace:'BS',Delete:'Del',Insert:'Ins'}; + function cmKeyToVimKey(key) { + if (key.charAt(0) == '\'') { + // Keypress character binding of format "'a'" + return key.charAt(1); + } + var pieces = key.split(/-(?!$)/); + var lastPiece = pieces[pieces.length - 1]; + if (pieces.length == 1 && pieces[0].length == 1) { + // No-modifier bindings use literal character bindings above. Skip. + return false; + } else if (pieces.length == 2 && pieces[0] == 'Shift' && lastPiece.length == 1) { + // Ignore Shift+char bindings as they should be handled by literal character. + return false; + } + var hasCharacter = false; + for (var i = 0; i < pieces.length; i++) { + var piece = pieces[i]; + if (piece in modifiers) { pieces[i] = modifiers[piece]; } + else { hasCharacter = true; } + if (piece in specialKeys) { pieces[i] = specialKeys[piece]; } + } + if (!hasCharacter) { + // Vim does not support modifier only keys. + return false; + } + // TODO: Current bindings expect the character to be lower case, but + // it looks like vim key notation uses upper case. + if (isUpperCase(lastPiece)) { + pieces[pieces.length - 1] = lastPiece.toLowerCase(); + } + return '<' + pieces.join('-') + '>'; + } + + function getOnPasteFn(cm) { + var vim = cm.state.vim; + if (!vim.onPasteFn) { + vim.onPasteFn = function() { + if (!vim.insertMode) { + cm.setCursor(offsetCursor(cm.getCursor(), 0, 1)); + actions.enterInsertMode(cm, {}, vim); + } + }; + } + return vim.onPasteFn; + } + + var numberRegex = /[\d]/; + var wordCharTest = [CodeMirror.isWordChar, function(ch) { + return ch && !CodeMirror.isWordChar(ch) && !/\s/.test(ch); + }], bigWordCharTest = [function(ch) { + return /\S/.test(ch); + }]; + function makeKeyRange(start, size) { + var keys = []; + for (var i = start; i < start + size; i++) { + keys.push(String.fromCharCode(i)); + } + return keys; + } + var upperCaseAlphabet = makeKeyRange(65, 26); + var lowerCaseAlphabet = makeKeyRange(97, 26); + var numbers = makeKeyRange(48, 10); + var validMarks = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['<', '>']); + var validRegisters = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['-', '"', '.', ':', '/']); + + function isLine(cm, line) { + return line >= cm.firstLine() && line <= cm.lastLine(); + } + function isLowerCase(k) { + return (/^[a-z]$/).test(k); + } + function isMatchableSymbol(k) { + return '()[]{}'.indexOf(k) != -1; + } + function isNumber(k) { + return numberRegex.test(k); + } + function isUpperCase(k) { + return (/^[A-Z]$/).test(k); + } + function isWhiteSpaceString(k) { + return (/^\s*$/).test(k); + } + function inArray(val, arr) { + for (var i = 0; i < arr.length; i++) { + if (arr[i] == val) { + return true; + } + } + return false; + } + + var options = {}; + function defineOption(name, defaultValue, type, aliases, callback) { + if (defaultValue === undefined && !callback) { + throw Error('defaultValue is required unless callback is provided'); + } + if (!type) { type = 'string'; } + options[name] = { + type: type, + defaultValue: defaultValue, + callback: callback + }; + if (aliases) { + for (var i = 0; i < aliases.length; i++) { + options[aliases[i]] = options[name]; + } + } + if (defaultValue) { + setOption(name, defaultValue); + } + } + + function setOption(name, value, cm, cfg) { + var option = options[name]; + cfg = cfg || {}; + var scope = cfg.scope; + if (!option) { + return new Error('Unknown option: ' + name); + } + if (option.type == 'boolean') { + if (value && value !== true) { + return new Error('Invalid argument: ' + name + '=' + value); + } else if (value !== false) { + // Boolean options are set to true if value is not defined. + value = true; + } + } + if (option.callback) { + if (scope !== 'local') { + option.callback(value, undefined); + } + if (scope !== 'global' && cm) { + option.callback(value, cm); + } + } else { + if (scope !== 'local') { + option.value = option.type == 'boolean' ? !!value : value; + } + if (scope !== 'global' && cm) { + cm.state.vim.options[name] = {value: value}; + } + } + } + + function getOption(name, cm, cfg) { + var option = options[name]; + cfg = cfg || {}; + var scope = cfg.scope; + if (!option) { + return new Error('Unknown option: ' + name); + } + if (option.callback) { + var local = cm && option.callback(undefined, cm); + if (scope !== 'global' && local !== undefined) { + return local; + } + if (scope !== 'local') { + return option.callback(); + } + return; + } else { + var local = (scope !== 'global') && (cm && cm.state.vim.options[name]); + return (local || (scope !== 'local') && option || {}).value; + } + } + + defineOption('filetype', undefined, 'string', ['ft'], function(name, cm) { + // Option is local. Do nothing for global. + if (cm === undefined) { + return; + } + // The 'filetype' option proxies to the CodeMirror 'mode' option. + if (name === undefined) { + var mode = cm.getOption('mode'); + return mode == 'null' ? '' : mode; + } else { + var mode = name == '' ? 'null' : name; + cm.setOption('mode', mode); + } + }); + + var createCircularJumpList = function() { + var size = 100; + var pointer = -1; + var head = 0; + var tail = 0; + var buffer = new Array(size); + function add(cm, oldCur, newCur) { + var current = pointer % size; + var curMark = buffer[current]; + function useNextSlot(cursor) { + var next = ++pointer % size; + var trashMark = buffer[next]; + if (trashMark) { + trashMark.clear(); + } + buffer[next] = cm.setBookmark(cursor); + } + if (curMark) { + var markPos = curMark.find(); + // avoid recording redundant cursor position + if (markPos && !cursorEqual(markPos, oldCur)) { + useNextSlot(oldCur); + } + } else { + useNextSlot(oldCur); + } + useNextSlot(newCur); + head = pointer; + tail = pointer - size + 1; + if (tail < 0) { + tail = 0; + } + } + function move(cm, offset) { + pointer += offset; + if (pointer > head) { + pointer = head; + } else if (pointer < tail) { + pointer = tail; + } + var mark = buffer[(size + pointer) % size]; + // skip marks that are temporarily removed from text buffer + if (mark && !mark.find()) { + var inc = offset > 0 ? 1 : -1; + var newCur; + var oldCur = cm.getCursor(); + do { + pointer += inc; + mark = buffer[(size + pointer) % size]; + // skip marks that are the same as current position + if (mark && + (newCur = mark.find()) && + !cursorEqual(oldCur, newCur)) { + break; + } + } while (pointer < head && pointer > tail); + } + return mark; + } + return { + cachedCursor: undefined, //used for # and * jumps + add: add, + move: move + }; + }; + + // Returns an object to track the changes associated insert mode. It + // clones the object that is passed in, or creates an empty object one if + // none is provided. + var createInsertModeChanges = function(c) { + if (c) { + // Copy construction + return { + changes: c.changes, + expectCursorActivityForChange: c.expectCursorActivityForChange + }; + } + return { + // Change list + changes: [], + // Set to true on change, false on cursorActivity. + expectCursorActivityForChange: false + }; + }; + + function MacroModeState() { + this.latestRegister = undefined; + this.isPlaying = false; + this.isRecording = false; + this.replaySearchQueries = []; + this.onRecordingDone = undefined; + this.lastInsertModeChanges = createInsertModeChanges(); + } + MacroModeState.prototype = { + exitMacroRecordMode: function() { + var macroModeState = vimGlobalState.macroModeState; + if (macroModeState.onRecordingDone) { + macroModeState.onRecordingDone(); // close dialog + } + macroModeState.onRecordingDone = undefined; + macroModeState.isRecording = false; + }, + enterMacroRecordMode: function(cm, registerName) { + var register = + vimGlobalState.registerController.getRegister(registerName); + if (register) { + register.clear(); + this.latestRegister = registerName; + if (cm.openDialog) { + this.onRecordingDone = cm.openDialog( + '(recording)['+registerName+']', null, {bottom:true}); + } + this.isRecording = true; + } + } + }; + + function maybeInitVimState(cm) { + if (!cm.state.vim) { + // Store instance state in the CodeMirror object. + cm.state.vim = { + inputState: new InputState(), + // Vim's input state that triggered the last edit, used to repeat + // motions and operators with '.'. + lastEditInputState: undefined, + // Vim's action command before the last edit, used to repeat actions + // with '.' and insert mode repeat. + lastEditActionCommand: undefined, + // When using jk for navigation, if you move from a longer line to a + // shorter line, the cursor may clip to the end of the shorter line. + // If j is pressed again and cursor goes to the next line, the + // cursor should go back to its horizontal position on the longer + // line if it can. This is to keep track of the horizontal position. + lastHPos: -1, + // Doing the same with screen-position for gj/gk + lastHSPos: -1, + // The last motion command run. Cleared if a non-motion command gets + // executed in between. + lastMotion: null, + marks: {}, + // Mark for rendering fake cursor for visual mode. + fakeCursor: null, + insertMode: false, + // Repeat count for changes made in insert mode, triggered by key + // sequences like 3,i. Only exists when insertMode is true. + insertModeRepeat: undefined, + visualMode: false, + // If we are in visual line mode. No effect if visualMode is false. + visualLine: false, + visualBlock: false, + lastSelection: null, + lastPastedText: null, + sel: {}, + // Buffer-local/window-local values of vim options. + options: {} + }; + } + return cm.state.vim; + } + var vimGlobalState; + function resetVimGlobalState() { + vimGlobalState = { + // The current search query. + searchQuery: null, + // Whether we are searching backwards. + searchIsReversed: false, + // Replace part of the last substituted pattern + lastSubstituteReplacePart: undefined, + jumpList: createCircularJumpList(), + macroModeState: new MacroModeState, + // Recording latest f, t, F or T motion command. + lastCharacterSearch: {increment:0, forward:true, selectedCharacter:''}, + registerController: new RegisterController({}), + // search history buffer + searchHistoryController: new HistoryController(), + // ex Command history buffer + exCommandHistoryController : new HistoryController() + }; + for (var optionName in options) { + var option = options[optionName]; + option.value = option.defaultValue; + } + } + + var lastInsertModeKeyTimer; + var vimApi= { + buildKeyMap: function() { + // TODO: Convert keymap into dictionary format for fast lookup. + }, + // Testing hook, though it might be useful to expose the register + // controller anyways. + getRegisterController: function() { + return vimGlobalState.registerController; + }, + // Testing hook. + resetVimGlobalState_: resetVimGlobalState, + + // Testing hook. + getVimGlobalState_: function() { + return vimGlobalState; + }, + + // Testing hook. + maybeInitVimState_: maybeInitVimState, + + suppressErrorLogging: false, + + InsertModeKey: InsertModeKey, + map: function(lhs, rhs, ctx) { + // Add user defined key bindings. + exCommandDispatcher.map(lhs, rhs, ctx); + }, + unmap: function(lhs, ctx) { + exCommandDispatcher.unmap(lhs, ctx); + }, + // TODO: Expose setOption and getOption as instance methods. Need to decide how to namespace + // them, or somehow make them work with the existing CodeMirror setOption/getOption API. + setOption: setOption, + getOption: getOption, + defineOption: defineOption, + defineEx: function(name, prefix, func){ + if (!prefix) { + prefix = name; + } else if (name.indexOf(prefix) !== 0) { + throw new Error('(Vim.defineEx) "'+prefix+'" is not a prefix of "'+name+'", command not registered'); + } + exCommands[name]=func; + exCommandDispatcher.commandMap_[prefix]={name:name, shortName:prefix, type:'api'}; + }, + handleKey: function (cm, key, origin) { + var command = this.findKey(cm, key, origin); + if (typeof command === 'function') { + return command(); + } + }, + /** + * This is the outermost function called by CodeMirror, after keys have + * been mapped to their Vim equivalents. + * + * Finds a command based on the key (and cached keys if there is a + * multi-key sequence). Returns `undefined` if no key is matched, a noop + * function if a partial match is found (multi-key), and a function to + * execute the bound command if a a key is matched. The function always + * returns true. + */ + findKey: function(cm, key, origin) { + var vim = maybeInitVimState(cm); + function handleMacroRecording() { + var macroModeState = vimGlobalState.macroModeState; + if (macroModeState.isRecording) { + if (key == 'q') { + macroModeState.exitMacroRecordMode(); + clearInputState(cm); + return true; + } + if (origin != 'mapping') { + logKey(macroModeState, key); + } + } + } + function handleEsc() { + if (key == '<Esc>') { + // Clear input state and get back to normal mode. + clearInputState(cm); + if (vim.visualMode) { + exitVisualMode(cm); + } else if (vim.insertMode) { + exitInsertMode(cm); + } + return true; + } + } + function doKeyToKey(keys) { + // TODO: prevent infinite recursion. + var match; + while (keys) { + // Pull off one command key, which is either a single character + // or a special sequence wrapped in '<' and '>', e.g. '<Space>'. + match = (/<\w+-.+?>|<\w+>|./).exec(keys); + key = match[0]; + keys = keys.substring(match.index + key.length); + CodeMirror.Vim.handleKey(cm, key, 'mapping'); + } + } + + function handleKeyInsertMode() { + if (handleEsc()) { return true; } + var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key; + var keysAreChars = key.length == 1; + var match = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert'); + // Need to check all key substrings in insert mode. + while (keys.length > 1 && match.type != 'full') { + var keys = vim.inputState.keyBuffer = keys.slice(1); + var thisMatch = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert'); + if (thisMatch.type != 'none') { match = thisMatch; } + } + if (match.type == 'none') { clearInputState(cm); return false; } + else if (match.type == 'partial') { + if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); } + lastInsertModeKeyTimer = window.setTimeout( + function() { if (vim.insertMode && vim.inputState.keyBuffer) { clearInputState(cm); } }, + getOption('insertModeEscKeysTimeout')); + return !keysAreChars; + } + + if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); } + if (keysAreChars) { + var selections = cm.listSelections(); + for (var i = 0; i < selections.length; i++) { + var here = selections[i].head; + cm.replaceRange('', offsetCursor(here, 0, -(keys.length - 1)), here, '+input'); + } + vimGlobalState.macroModeState.lastInsertModeChanges.changes.pop(); + } + clearInputState(cm); + return match.command; + } + + function handleKeyNonInsertMode() { + if (handleMacroRecording() || handleEsc()) { return true; }; + + var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key; + if (/^[1-9]\d*$/.test(keys)) { return true; } + + var keysMatcher = /^(\d*)(.*)$/.exec(keys); + if (!keysMatcher) { clearInputState(cm); return false; } + var context = vim.visualMode ? 'visual' : + 'normal'; + var match = commandDispatcher.matchCommand(keysMatcher[2] || keysMatcher[1], defaultKeymap, vim.inputState, context); + if (match.type == 'none') { clearInputState(cm); return false; } + else if (match.type == 'partial') { return true; } + + vim.inputState.keyBuffer = ''; + var keysMatcher = /^(\d*)(.*)$/.exec(keys); + if (keysMatcher[1] && keysMatcher[1] != '0') { + vim.inputState.pushRepeatDigit(keysMatcher[1]); + } + return match.command; + } + + var command; + if (vim.insertMode) { command = handleKeyInsertMode(); } + else { command = handleKeyNonInsertMode(); } + if (command === false) { + return undefined; + } else if (command === true) { + // TODO: Look into using CodeMirror's multi-key handling. + // Return no-op since we are caching the key. Counts as handled, but + // don't want act on it just yet. + return function() { return true; }; + } else { + return function() { + return cm.operation(function() { + cm.curOp.isVimOp = true; + try { + if (command.type == 'keyToKey') { + doKeyToKey(command.toKeys); + } else { + commandDispatcher.processCommand(cm, vim, command); + } + } catch (e) { + // clear VIM state in case it's in a bad state. + cm.state.vim = undefined; + maybeInitVimState(cm); + if (!CodeMirror.Vim.suppressErrorLogging) { + console['log'](e); + } + throw e; + } + return true; + }); + }; + } + }, + handleEx: function(cm, input) { + exCommandDispatcher.processCommand(cm, input); + }, + + defineMotion: defineMotion, + defineAction: defineAction, + defineOperator: defineOperator, + mapCommand: mapCommand, + _mapCommand: _mapCommand, + + defineRegister: defineRegister, + + exitVisualMode: exitVisualMode, + exitInsertMode: exitInsertMode + }; + + // Represents the current input state. + function InputState() { + this.prefixRepeat = []; + this.motionRepeat = []; + + this.operator = null; + this.operatorArgs = null; + this.motion = null; + this.motionArgs = null; + this.keyBuffer = []; // For matching multi-key commands. + this.registerName = null; // Defaults to the unnamed register. + } + InputState.prototype.pushRepeatDigit = function(n) { + if (!this.operator) { + this.prefixRepeat = this.prefixRepeat.concat(n); + } else { + this.motionRepeat = this.motionRepeat.concat(n); + } + }; + InputState.prototype.getRepeat = function() { + var repeat = 0; + if (this.prefixRepeat.length > 0 || this.motionRepeat.length > 0) { + repeat = 1; + if (this.prefixRepeat.length > 0) { + repeat *= parseInt(this.prefixRepeat.join(''), 10); + } + if (this.motionRepeat.length > 0) { + repeat *= parseInt(this.motionRepeat.join(''), 10); + } + } + return repeat; + }; + + function clearInputState(cm, reason) { + cm.state.vim.inputState = new InputState(); + CodeMirror.signal(cm, 'vim-command-done', reason); + } + + /* + * Register stores information about copy and paste registers. Besides + * text, a register must store whether it is linewise (i.e., when it is + * pasted, should it insert itself into a new line, or should the text be + * inserted at the cursor position.) + */ + function Register(text, linewise, blockwise) { + this.clear(); + this.keyBuffer = [text || '']; + this.insertModeChanges = []; + this.searchQueries = []; + this.linewise = !!linewise; + this.blockwise = !!blockwise; + } + Register.prototype = { + setText: function(text, linewise, blockwise) { + this.keyBuffer = [text || '']; + this.linewise = !!linewise; + this.blockwise = !!blockwise; + }, + pushText: function(text, linewise) { + // if this register has ever been set to linewise, use linewise. + if (linewise) { + if (!this.linewise) { + this.keyBuffer.push('\n'); + } + this.linewise = true; + } + this.keyBuffer.push(text); + }, + pushInsertModeChanges: function(changes) { + this.insertModeChanges.push(createInsertModeChanges(changes)); + }, + pushSearchQuery: function(query) { + this.searchQueries.push(query); + }, + clear: function() { + this.keyBuffer = []; + this.insertModeChanges = []; + this.searchQueries = []; + this.linewise = false; + }, + toString: function() { + return this.keyBuffer.join(''); + } + }; + + /** + * Defines an external register. + * + * The name should be a single character that will be used to reference the register. + * The register should support setText, pushText, clear, and toString(). See Register + * for a reference implementation. + */ + function defineRegister(name, register) { + var registers = vimGlobalState.registerController.registers; + if (!name || name.length != 1) { + throw Error('Register name must be 1 character'); + } + if (registers[name]) { + throw Error('Register already defined ' + name); + } + registers[name] = register; + validRegisters.push(name); + } + + /* + * vim registers allow you to keep many independent copy and paste buffers. + * See http://usevim.com/2012/04/13/registers/ for an introduction. + * + * RegisterController keeps the state of all the registers. An initial + * state may be passed in. The unnamed register '"' will always be + * overridden. + */ + function RegisterController(registers) { + this.registers = registers; + this.unnamedRegister = registers['"'] = new Register(); + registers['.'] = new Register(); + registers[':'] = new Register(); + registers['/'] = new Register(); + } + RegisterController.prototype = { + pushText: function(registerName, operator, text, linewise, blockwise) { + if (linewise && text.charAt(text.length - 1) !== '\n'){ + text += '\n'; + } + // Lowercase and uppercase registers refer to the same register. + // Uppercase just means append. + var register = this.isValidRegister(registerName) ? + this.getRegister(registerName) : null; + // if no register/an invalid register was specified, things go to the + // default registers + if (!register) { + switch (operator) { + case 'yank': + // The 0 register contains the text from the most recent yank. + this.registers['0'] = new Register(text, linewise, blockwise); + break; + case 'delete': + case 'change': + if (text.indexOf('\n') == -1) { + // Delete less than 1 line. Update the small delete register. + this.registers['-'] = new Register(text, linewise); + } else { + // Shift down the contents of the numbered registers and put the + // deleted text into register 1. + this.shiftNumericRegisters_(); + this.registers['1'] = new Register(text, linewise); + } + break; + } + // Make sure the unnamed register is set to what just happened + this.unnamedRegister.setText(text, linewise, blockwise); + return; + } + + // If we've gotten to this point, we've actually specified a register + var append = isUpperCase(registerName); + if (append) { + register.pushText(text, linewise); + } else { + register.setText(text, linewise, blockwise); + } + // The unnamed register always has the same value as the last used + // register. + this.unnamedRegister.setText(register.toString(), linewise); + }, + // Gets the register named @name. If one of @name doesn't already exist, + // create it. If @name is invalid, return the unnamedRegister. + getRegister: function(name) { + if (!this.isValidRegister(name)) { + return this.unnamedRegister; + } + name = name.toLowerCase(); + if (!this.registers[name]) { + this.registers[name] = new Register(); + } + return this.registers[name]; + }, + isValidRegister: function(name) { + return name && inArray(name, validRegisters); + }, + shiftNumericRegisters_: function() { + for (var i = 9; i >= 2; i--) { + this.registers[i] = this.getRegister('' + (i - 1)); + } + } + }; + function HistoryController() { + this.historyBuffer = []; + this.iterator = 0; + this.initialPrefix = null; + } + HistoryController.prototype = { + // the input argument here acts a user entered prefix for a small time + // until we start autocompletion in which case it is the autocompleted. + nextMatch: function (input, up) { + var historyBuffer = this.historyBuffer; + var dir = up ? -1 : 1; + if (this.initialPrefix === null) this.initialPrefix = input; + for (var i = this.iterator + dir; up ? i >= 0 : i < historyBuffer.length; i+= dir) { + var element = historyBuffer[i]; + for (var j = 0; j <= element.length; j++) { + if (this.initialPrefix == element.substring(0, j)) { + this.iterator = i; + return element; + } + } + } + // should return the user input in case we reach the end of buffer. + if (i >= historyBuffer.length) { + this.iterator = historyBuffer.length; + return this.initialPrefix; + } + // return the last autocompleted query or exCommand as it is. + if (i < 0 ) return input; + }, + pushInput: function(input) { + var index = this.historyBuffer.indexOf(input); + if (index > -1) this.historyBuffer.splice(index, 1); + if (input.length) this.historyBuffer.push(input); + }, + reset: function() { + this.initialPrefix = null; + this.iterator = this.historyBuffer.length; + } + }; + var commandDispatcher = { + matchCommand: function(keys, keyMap, inputState, context) { + var matches = commandMatches(keys, keyMap, context, inputState); + if (!matches.full && !matches.partial) { + return {type: 'none'}; + } else if (!matches.full && matches.partial) { + return {type: 'partial'}; + } + + var bestMatch; + for (var i = 0; i < matches.full.length; i++) { + var match = matches.full[i]; + if (!bestMatch) { + bestMatch = match; + } + } + if (bestMatch.keys.slice(-11) == '<character>') { + var character = lastChar(keys); + if (!character) return {type: 'none'}; + inputState.selectedCharacter = character; + } + return {type: 'full', command: bestMatch}; + }, + processCommand: function(cm, vim, command) { + vim.inputState.repeatOverride = command.repeatOverride; + switch (command.type) { + case 'motion': + this.processMotion(cm, vim, command); + break; + case 'operator': + this.processOperator(cm, vim, command); + break; + case 'operatorMotion': + this.processOperatorMotion(cm, vim, command); + break; + case 'action': + this.processAction(cm, vim, command); + break; + case 'search': + this.processSearch(cm, vim, command); + break; + case 'ex': + case 'keyToEx': + this.processEx(cm, vim, command); + break; + default: + break; + } + }, + processMotion: function(cm, vim, command) { + vim.inputState.motion = command.motion; + vim.inputState.motionArgs = copyArgs(command.motionArgs); + this.evalInput(cm, vim); + }, + processOperator: function(cm, vim, command) { + var inputState = vim.inputState; + if (inputState.operator) { + if (inputState.operator == command.operator) { + // Typing an operator twice like 'dd' makes the operator operate + // linewise + inputState.motion = 'expandToLine'; + inputState.motionArgs = { linewise: true }; + this.evalInput(cm, vim); + return; + } else { + // 2 different operators in a row doesn't make sense. + clearInputState(cm); + } + } + inputState.operator = command.operator; + inputState.operatorArgs = copyArgs(command.operatorArgs); + if (vim.visualMode) { + // Operating on a selection in visual mode. We don't need a motion. + this.evalInput(cm, vim); + } + }, + processOperatorMotion: function(cm, vim, command) { + var visualMode = vim.visualMode; + var operatorMotionArgs = copyArgs(command.operatorMotionArgs); + if (operatorMotionArgs) { + // Operator motions may have special behavior in visual mode. + if (visualMode && operatorMotionArgs.visualLine) { + vim.visualLine = true; + } + } + this.processOperator(cm, vim, command); + if (!visualMode) { + this.processMotion(cm, vim, command); + } + }, + processAction: function(cm, vim, command) { + var inputState = vim.inputState; + var repeat = inputState.getRepeat(); + var repeatIsExplicit = !!repeat; + var actionArgs = copyArgs(command.actionArgs) || {}; + if (inputState.selectedCharacter) { + actionArgs.selectedCharacter = inputState.selectedCharacter; + } + // Actions may or may not have motions and operators. Do these first. + if (command.operator) { + this.processOperator(cm, vim, command); + } + if (command.motion) { + this.processMotion(cm, vim, command); + } + if (command.motion || command.operator) { + this.evalInput(cm, vim); + } + actionArgs.repeat = repeat || 1; + actionArgs.repeatIsExplicit = repeatIsExplicit; + actionArgs.registerName = inputState.registerName; + clearInputState(cm); + vim.lastMotion = null; + if (command.isEdit) { + this.recordLastEdit(vim, inputState, command); + } + actions[command.action](cm, actionArgs, vim); + }, + processSearch: function(cm, vim, command) { + if (!cm.getSearchCursor) { + // Search depends on SearchCursor. + return; + } + var forward = command.searchArgs.forward; + var wholeWordOnly = command.searchArgs.wholeWordOnly; + getSearchState(cm).setReversed(!forward); + var promptPrefix = (forward) ? '/' : '?'; + var originalQuery = getSearchState(cm).getQuery(); + var originalScrollPos = cm.getScrollInfo(); + function handleQuery(query, ignoreCase, smartCase) { + vimGlobalState.searchHistoryController.pushInput(query); + vimGlobalState.searchHistoryController.reset(); + try { + updateSearchQuery(cm, query, ignoreCase, smartCase); + } catch (e) { + showConfirm(cm, 'Invalid regex: ' + query); + clearInputState(cm); + return; + } + commandDispatcher.processMotion(cm, vim, { + type: 'motion', + motion: 'findNext', + motionArgs: { forward: true, toJumplist: command.searchArgs.toJumplist } + }); + } + function onPromptClose(query) { + cm.scrollTo(originalScrollPos.left, originalScrollPos.top); + handleQuery(query, true /** ignoreCase */, true /** smartCase */); + var macroModeState = vimGlobalState.macroModeState; + if (macroModeState.isRecording) { + logSearchQuery(macroModeState, query); + } + } + function onPromptKeyUp(e, query, close) { + var keyName = CodeMirror.keyName(e), up, offset; + if (keyName == 'Up' || keyName == 'Down') { + up = keyName == 'Up' ? true : false; + offset = e.target ? e.target.selectionEnd : 0; + query = vimGlobalState.searchHistoryController.nextMatch(query, up) || ''; + close(query); + if (offset && e.target) e.target.selectionEnd = e.target.selectionStart = Math.min(offset, e.target.value.length); + } else { + if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift') + vimGlobalState.searchHistoryController.reset(); + } + var parsedQuery; + try { + parsedQuery = updateSearchQuery(cm, query, + true /** ignoreCase */, true /** smartCase */); + } catch (e) { + // Swallow bad regexes for incremental search. + } + if (parsedQuery) { + cm.scrollIntoView(findNext(cm, !forward, parsedQuery), 30); + } else { + clearSearchHighlight(cm); + cm.scrollTo(originalScrollPos.left, originalScrollPos.top); + } + } + function onPromptKeyDown(e, query, close) { + var keyName = CodeMirror.keyName(e); + if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[' || + (keyName == 'Backspace' && query == '')) { + vimGlobalState.searchHistoryController.pushInput(query); + vimGlobalState.searchHistoryController.reset(); + updateSearchQuery(cm, originalQuery); + clearSearchHighlight(cm); + cm.scrollTo(originalScrollPos.left, originalScrollPos.top); + CodeMirror.e_stop(e); + clearInputState(cm); + close(); + cm.focus(); + } else if (keyName == 'Up' || keyName == 'Down') { + CodeMirror.e_stop(e); + } else if (keyName == 'Ctrl-U') { + // Ctrl-U clears input. + CodeMirror.e_stop(e); + close(''); + } + } + switch (command.searchArgs.querySrc) { + case 'prompt': + var macroModeState = vimGlobalState.macroModeState; + if (macroModeState.isPlaying) { + var query = macroModeState.replaySearchQueries.shift(); + handleQuery(query, true /** ignoreCase */, false /** smartCase */); + } else { + showPrompt(cm, { + onClose: onPromptClose, + prefix: promptPrefix, + desc: searchPromptDesc, + onKeyUp: onPromptKeyUp, + onKeyDown: onPromptKeyDown + }); + } + break; + case 'wordUnderCursor': + var word = expandWordUnderCursor(cm, false /** inclusive */, + true /** forward */, false /** bigWord */, + true /** noSymbol */); + var isKeyword = true; + if (!word) { + word = expandWordUnderCursor(cm, false /** inclusive */, + true /** forward */, false /** bigWord */, + false /** noSymbol */); + isKeyword = false; + } + if (!word) { + return; + } + var query = cm.getLine(word.start.line).substring(word.start.ch, + word.end.ch); + if (isKeyword && wholeWordOnly) { + query = '\\b' + query + '\\b'; + } else { + query = escapeRegex(query); + } + + // cachedCursor is used to save the old position of the cursor + // when * or # causes vim to seek for the nearest word and shift + // the cursor before entering the motion. + vimGlobalState.jumpList.cachedCursor = cm.getCursor(); + cm.setCursor(word.start); + + handleQuery(query, true /** ignoreCase */, false /** smartCase */); + break; + } + }, + processEx: function(cm, vim, command) { + function onPromptClose(input) { + // Give the prompt some time to close so that if processCommand shows + // an error, the elements don't overlap. + vimGlobalState.exCommandHistoryController.pushInput(input); + vimGlobalState.exCommandHistoryController.reset(); + exCommandDispatcher.processCommand(cm, input); + } + function onPromptKeyDown(e, input, close) { + var keyName = CodeMirror.keyName(e), up, offset; + if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[' || + (keyName == 'Backspace' && input == '')) { + vimGlobalState.exCommandHistoryController.pushInput(input); + vimGlobalState.exCommandHistoryController.reset(); + CodeMirror.e_stop(e); + clearInputState(cm); + close(); + cm.focus(); + } + if (keyName == 'Up' || keyName == 'Down') { + CodeMirror.e_stop(e); + up = keyName == 'Up' ? true : false; + offset = e.target ? e.target.selectionEnd : 0; + input = vimGlobalState.exCommandHistoryController.nextMatch(input, up) || ''; + close(input); + if (offset && e.target) e.target.selectionEnd = e.target.selectionStart = Math.min(offset, e.target.value.length); + } else if (keyName == 'Ctrl-U') { + // Ctrl-U clears input. + CodeMirror.e_stop(e); + close(''); + } else { + if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift') + vimGlobalState.exCommandHistoryController.reset(); + } + } + if (command.type == 'keyToEx') { + // Handle user defined Ex to Ex mappings + exCommandDispatcher.processCommand(cm, command.exArgs.input); + } else { + if (vim.visualMode) { + showPrompt(cm, { onClose: onPromptClose, prefix: ':', value: '\'<,\'>', + onKeyDown: onPromptKeyDown}); + } else { + showPrompt(cm, { onClose: onPromptClose, prefix: ':', + onKeyDown: onPromptKeyDown}); + } + } + }, + evalInput: function(cm, vim) { + // If the motion command is set, execute both the operator and motion. + // Otherwise return. + var inputState = vim.inputState; + var motion = inputState.motion; + var motionArgs = inputState.motionArgs || {}; + var operator = inputState.operator; + var operatorArgs = inputState.operatorArgs || {}; + var registerName = inputState.registerName; + var sel = vim.sel; + // TODO: Make sure cm and vim selections are identical outside visual mode. + var origHead = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.head): cm.getCursor('head')); + var origAnchor = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.anchor) : cm.getCursor('anchor')); + var oldHead = copyCursor(origHead); + var oldAnchor = copyCursor(origAnchor); + var newHead, newAnchor; + var repeat; + if (operator) { + this.recordLastEdit(vim, inputState); + } + if (inputState.repeatOverride !== undefined) { + // If repeatOverride is specified, that takes precedence over the + // input state's repeat. Used by Ex mode and can be user defined. + repeat = inputState.repeatOverride; + } else { + repeat = inputState.getRepeat(); + } + if (repeat > 0 && motionArgs.explicitRepeat) { + motionArgs.repeatIsExplicit = true; + } else if (motionArgs.noRepeat || + (!motionArgs.explicitRepeat && repeat === 0)) { + repeat = 1; + motionArgs.repeatIsExplicit = false; + } + if (inputState.selectedCharacter) { + // If there is a character input, stick it in all of the arg arrays. + motionArgs.selectedCharacter = operatorArgs.selectedCharacter = + inputState.selectedCharacter; + } + motionArgs.repeat = repeat; + clearInputState(cm); + if (motion) { + var motionResult = motions[motion](cm, origHead, motionArgs, vim); + vim.lastMotion = motions[motion]; + if (!motionResult) { + return; + } + if (motionArgs.toJumplist) { + var jumpList = vimGlobalState.jumpList; + // if the current motion is # or *, use cachedCursor + var cachedCursor = jumpList.cachedCursor; + if (cachedCursor) { + recordJumpPosition(cm, cachedCursor, motionResult); + delete jumpList.cachedCursor; + } else { + recordJumpPosition(cm, origHead, motionResult); + } + } + if (motionResult instanceof Array) { + newAnchor = motionResult[0]; + newHead = motionResult[1]; + } else { + newHead = motionResult; + } + // TODO: Handle null returns from motion commands better. + if (!newHead) { + newHead = copyCursor(origHead); + } + if (vim.visualMode) { + if (!(vim.visualBlock && newHead.ch === Infinity)) { + newHead = clipCursorToContent(cm, newHead, vim.visualBlock); + } + if (newAnchor) { + newAnchor = clipCursorToContent(cm, newAnchor, true); + } + newAnchor = newAnchor || oldAnchor; + sel.anchor = newAnchor; + sel.head = newHead; + updateCmSelection(cm); + updateMark(cm, vim, '<', + cursorIsBefore(newAnchor, newHead) ? newAnchor + : newHead); + updateMark(cm, vim, '>', + cursorIsBefore(newAnchor, newHead) ? newHead + : newAnchor); + } else if (!operator) { + newHead = clipCursorToContent(cm, newHead); + cm.setCursor(newHead.line, newHead.ch); + } + } + if (operator) { + if (operatorArgs.lastSel) { + // Replaying a visual mode operation + newAnchor = oldAnchor; + var lastSel = operatorArgs.lastSel; + var lineOffset = Math.abs(lastSel.head.line - lastSel.anchor.line); + var chOffset = Math.abs(lastSel.head.ch - lastSel.anchor.ch); + if (lastSel.visualLine) { + // Linewise Visual mode: The same number of lines. + newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch); + } else if (lastSel.visualBlock) { + // Blockwise Visual mode: The same number of lines and columns. + newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch + chOffset); + } else if (lastSel.head.line == lastSel.anchor.line) { + // Normal Visual mode within one line: The same number of characters. + newHead = Pos(oldAnchor.line, oldAnchor.ch + chOffset); + } else { + // Normal Visual mode with several lines: The same number of lines, in the + // last line the same number of characters as in the last line the last time. + newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch); + } + vim.visualMode = true; + vim.visualLine = lastSel.visualLine; + vim.visualBlock = lastSel.visualBlock; + sel = vim.sel = { + anchor: newAnchor, + head: newHead + }; + updateCmSelection(cm); + } else if (vim.visualMode) { + operatorArgs.lastSel = { + anchor: copyCursor(sel.anchor), + head: copyCursor(sel.head), + visualBlock: vim.visualBlock, + visualLine: vim.visualLine + }; + } + var curStart, curEnd, linewise, mode; + var cmSel; + if (vim.visualMode) { + // Init visual op + curStart = cursorMin(sel.head, sel.anchor); + curEnd = cursorMax(sel.head, sel.anchor); + linewise = vim.visualLine || operatorArgs.linewise; + mode = vim.visualBlock ? 'block' : + linewise ? 'line' : + 'char'; + cmSel = makeCmSelection(cm, { + anchor: curStart, + head: curEnd + }, mode); + if (linewise) { + var ranges = cmSel.ranges; + if (mode == 'block') { + // Linewise operators in visual block mode extend to end of line + for (var i = 0; i < ranges.length; i++) { + ranges[i].head.ch = lineLength(cm, ranges[i].head.line); + } + } else if (mode == 'line') { + ranges[0].head = Pos(ranges[0].head.line + 1, 0); + } + } + } else { + // Init motion op + curStart = copyCursor(newAnchor || oldAnchor); + curEnd = copyCursor(newHead || oldHead); + if (cursorIsBefore(curEnd, curStart)) { + var tmp = curStart; + curStart = curEnd; + curEnd = tmp; + } + linewise = motionArgs.linewise || operatorArgs.linewise; + if (linewise) { + // Expand selection to entire line. + expandSelectionToLine(cm, curStart, curEnd); + } else if (motionArgs.forward) { + // Clip to trailing newlines only if the motion goes forward. + clipToLine(cm, curStart, curEnd); + } + mode = 'char'; + var exclusive = !motionArgs.inclusive || linewise; + cmSel = makeCmSelection(cm, { + anchor: curStart, + head: curEnd + }, mode, exclusive); + } + cm.setSelections(cmSel.ranges, cmSel.primary); + vim.lastMotion = null; + operatorArgs.repeat = repeat; // For indent in visual mode. + operatorArgs.registerName = registerName; + // Keep track of linewise as it affects how paste and change behave. + operatorArgs.linewise = linewise; + var operatorMoveTo = operators[operator]( + cm, operatorArgs, cmSel.ranges, oldAnchor, newHead); + if (vim.visualMode) { + exitVisualMode(cm, operatorMoveTo != null); + } + if (operatorMoveTo) { + cm.setCursor(operatorMoveTo); + } + } + }, + recordLastEdit: function(vim, inputState, actionCommand) { + var macroModeState = vimGlobalState.macroModeState; + if (macroModeState.isPlaying) { return; } + vim.lastEditInputState = inputState; + vim.lastEditActionCommand = actionCommand; + macroModeState.lastInsertModeChanges.changes = []; + macroModeState.lastInsertModeChanges.expectCursorActivityForChange = false; + } + }; + + /** + * typedef {Object{line:number,ch:number}} Cursor An object containing the + * position of the cursor. + */ + // All of the functions below return Cursor objects. + var motions = { + moveToTopLine: function(cm, _head, motionArgs) { + var line = getUserVisibleLines(cm).top + motionArgs.repeat -1; + return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line))); + }, + moveToMiddleLine: function(cm) { + var range = getUserVisibleLines(cm); + var line = Math.floor((range.top + range.bottom) * 0.5); + return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line))); + }, + moveToBottomLine: function(cm, _head, motionArgs) { + var line = getUserVisibleLines(cm).bottom - motionArgs.repeat +1; + return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line))); + }, + expandToLine: function(_cm, head, motionArgs) { + // Expands forward to end of line, and then to next line if repeat is + // >1. Does not handle backward motion! + var cur = head; + return Pos(cur.line + motionArgs.repeat - 1, Infinity); + }, + findNext: function(cm, _head, motionArgs) { + var state = getSearchState(cm); + var query = state.getQuery(); + if (!query) { + return; + } + var prev = !motionArgs.forward; + // If search is initiated with ? instead of /, negate direction. + prev = (state.isReversed()) ? !prev : prev; + highlightSearchMatches(cm, query); + return findNext(cm, prev/** prev */, query, motionArgs.repeat); + }, + goToMark: function(cm, _head, motionArgs, vim) { + var pos = getMarkPos(cm, vim, motionArgs.selectedCharacter); + if (pos) { + return motionArgs.linewise ? { line: pos.line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(pos.line)) } : pos; + } + return null; + }, + moveToOtherHighlightedEnd: function(cm, _head, motionArgs, vim) { + if (vim.visualBlock && motionArgs.sameLine) { + var sel = vim.sel; + return [ + clipCursorToContent(cm, Pos(sel.anchor.line, sel.head.ch)), + clipCursorToContent(cm, Pos(sel.head.line, sel.anchor.ch)) + ]; + } else { + return ([vim.sel.head, vim.sel.anchor]); + } + }, + jumpToMark: function(cm, head, motionArgs, vim) { + var best = head; + for (var i = 0; i < motionArgs.repeat; i++) { + var cursor = best; + for (var key in vim.marks) { + if (!isLowerCase(key)) { + continue; + } + var mark = vim.marks[key].find(); + var isWrongDirection = (motionArgs.forward) ? + cursorIsBefore(mark, cursor) : cursorIsBefore(cursor, mark); + + if (isWrongDirection) { + continue; + } + if (motionArgs.linewise && (mark.line == cursor.line)) { + continue; + } + + var equal = cursorEqual(cursor, best); + var between = (motionArgs.forward) ? + cursorIsBetween(cursor, mark, best) : + cursorIsBetween(best, mark, cursor); + + if (equal || between) { + best = mark; + } + } + } + + if (motionArgs.linewise) { + // Vim places the cursor on the first non-whitespace character of + // the line if there is one, else it places the cursor at the end + // of the line, regardless of whether a mark was found. + best = Pos(best.line, findFirstNonWhiteSpaceCharacter(cm.getLine(best.line))); + } + return best; + }, + moveByCharacters: function(_cm, head, motionArgs) { + var cur = head; + var repeat = motionArgs.repeat; + var ch = motionArgs.forward ? cur.ch + repeat : cur.ch - repeat; + return Pos(cur.line, ch); + }, + moveByLines: function(cm, head, motionArgs, vim) { + var cur = head; + var endCh = cur.ch; + // Depending what our last motion was, we may want to do different + // things. If our last motion was moving vertically, we want to + // preserve the HPos from our last horizontal move. If our last motion + // was going to the end of a line, moving vertically we should go to + // the end of the line, etc. + switch (vim.lastMotion) { + case this.moveByLines: + case this.moveByDisplayLines: + case this.moveByScroll: + case this.moveToColumn: + case this.moveToEol: + endCh = vim.lastHPos; + break; + default: + vim.lastHPos = endCh; + } + var repeat = motionArgs.repeat+(motionArgs.repeatOffset||0); + var line = motionArgs.forward ? cur.line + repeat : cur.line - repeat; + var first = cm.firstLine(); + var last = cm.lastLine(); + // Vim go to line begin or line end when cursor at first/last line and + // move to previous/next line is triggered. + if (line < first && cur.line == first){ + return this.moveToStartOfLine(cm, head, motionArgs, vim); + }else if (line > last && cur.line == last){ + return this.moveToEol(cm, head, motionArgs, vim); + } + if (motionArgs.toFirstChar){ + endCh=findFirstNonWhiteSpaceCharacter(cm.getLine(line)); + vim.lastHPos = endCh; + } + vim.lastHSPos = cm.charCoords(Pos(line, endCh),'div').left; + return Pos(line, endCh); + }, + moveByDisplayLines: function(cm, head, motionArgs, vim) { + var cur = head; + switch (vim.lastMotion) { + case this.moveByDisplayLines: + case this.moveByScroll: + case this.moveByLines: + case this.moveToColumn: + case this.moveToEol: + break; + default: + vim.lastHSPos = cm.charCoords(cur,'div').left; + } + var repeat = motionArgs.repeat; + var res=cm.findPosV(cur,(motionArgs.forward ? repeat : -repeat),'line',vim.lastHSPos); + if (res.hitSide) { + if (motionArgs.forward) { + var lastCharCoords = cm.charCoords(res, 'div'); + var goalCoords = { top: lastCharCoords.top + 8, left: vim.lastHSPos }; + var res = cm.coordsChar(goalCoords, 'div'); + } else { + var resCoords = cm.charCoords(Pos(cm.firstLine(), 0), 'div'); + resCoords.left = vim.lastHSPos; + res = cm.coordsChar(resCoords, 'div'); + } + } + vim.lastHPos = res.ch; + return res; + }, + moveByPage: function(cm, head, motionArgs) { + // CodeMirror only exposes functions that move the cursor page down, so + // doing this bad hack to move the cursor and move it back. evalInput + // will move the cursor to where it should be in the end. + var curStart = head; + var repeat = motionArgs.repeat; + return cm.findPosV(curStart, (motionArgs.forward ? repeat : -repeat), 'page'); + }, + moveByParagraph: function(cm, head, motionArgs) { + var dir = motionArgs.forward ? 1 : -1; + return findParagraph(cm, head, motionArgs.repeat, dir); + }, + moveByScroll: function(cm, head, motionArgs, vim) { + var scrollbox = cm.getScrollInfo(); + var curEnd = null; + var repeat = motionArgs.repeat; + if (!repeat) { + repeat = scrollbox.clientHeight / (2 * cm.defaultTextHeight()); + } + var orig = cm.charCoords(head, 'local'); + motionArgs.repeat = repeat; + var curEnd = motions.moveByDisplayLines(cm, head, motionArgs, vim); + if (!curEnd) { + return null; + } + var dest = cm.charCoords(curEnd, 'local'); + cm.scrollTo(null, scrollbox.top + dest.top - orig.top); + return curEnd; + }, + moveByWords: function(cm, head, motionArgs) { + return moveToWord(cm, head, motionArgs.repeat, !!motionArgs.forward, + !!motionArgs.wordEnd, !!motionArgs.bigWord); + }, + moveTillCharacter: function(cm, _head, motionArgs) { + var repeat = motionArgs.repeat; + var curEnd = moveToCharacter(cm, repeat, motionArgs.forward, + motionArgs.selectedCharacter); + var increment = motionArgs.forward ? -1 : 1; + recordLastCharacterSearch(increment, motionArgs); + if (!curEnd) return null; + curEnd.ch += increment; + return curEnd; + }, + moveToCharacter: function(cm, head, motionArgs) { + var repeat = motionArgs.repeat; + recordLastCharacterSearch(0, motionArgs); + return moveToCharacter(cm, repeat, motionArgs.forward, + motionArgs.selectedCharacter) || head; + }, + moveToSymbol: function(cm, head, motionArgs) { + var repeat = motionArgs.repeat; + return findSymbol(cm, repeat, motionArgs.forward, + motionArgs.selectedCharacter) || head; + }, + moveToColumn: function(cm, head, motionArgs, vim) { + var repeat = motionArgs.repeat; + // repeat is equivalent to which column we want to move to! + vim.lastHPos = repeat - 1; + vim.lastHSPos = cm.charCoords(head,'div').left; + return moveToColumn(cm, repeat); + }, + moveToEol: function(cm, head, motionArgs, vim) { + var cur = head; + vim.lastHPos = Infinity; + var retval= Pos(cur.line + motionArgs.repeat - 1, Infinity); + var end=cm.clipPos(retval); + end.ch--; + vim.lastHSPos = cm.charCoords(end,'div').left; + return retval; + }, + moveToFirstNonWhiteSpaceCharacter: function(cm, head) { + // Go to the start of the line where the text begins, or the end for + // whitespace-only lines + var cursor = head; + return Pos(cursor.line, + findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line))); + }, + moveToMatchedSymbol: function(cm, head) { + var cursor = head; + var line = cursor.line; + var ch = cursor.ch; + var lineText = cm.getLine(line); + var symbol; + for (; ch < lineText.length; ch++) { + symbol = lineText.charAt(ch); + if (symbol && isMatchableSymbol(symbol)) { + var style = cm.getTokenTypeAt(Pos(line, ch + 1)); + if (style !== "string" && style !== "comment") { + break; + } + } + } + if (ch < lineText.length) { + var matched = cm.findMatchingBracket(Pos(line, ch)); + return matched.to; + } else { + return cursor; + } + }, + moveToStartOfLine: function(_cm, head) { + return Pos(head.line, 0); + }, + moveToLineOrEdgeOfDocument: function(cm, _head, motionArgs) { + var lineNum = motionArgs.forward ? cm.lastLine() : cm.firstLine(); + if (motionArgs.repeatIsExplicit) { + lineNum = motionArgs.repeat - cm.getOption('firstLineNumber'); + } + return Pos(lineNum, + findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum))); + }, + textObjectManipulation: function(cm, head, motionArgs, vim) { + // TODO: lots of possible exceptions that can be thrown here. Try da( + // outside of a () block. + + // TODO: adding <> >< to this map doesn't work, presumably because + // they're operators + var mirroredPairs = {'(': ')', ')': '(', + '{': '}', '}': '{', + '[': ']', ']': '['}; + var selfPaired = {'\'': true, '"': true}; + + var character = motionArgs.selectedCharacter; + // 'b' refers to '()' block. + // 'B' refers to '{}' block. + if (character == 'b') { + character = '('; + } else if (character == 'B') { + character = '{'; + } + + // Inclusive is the difference between a and i + // TODO: Instead of using the additional text object map to perform text + // object operations, merge the map into the defaultKeyMap and use + // motionArgs to define behavior. Define separate entries for 'aw', + // 'iw', 'a[', 'i[', etc. + var inclusive = !motionArgs.textObjectInner; + + var tmp; + if (mirroredPairs[character]) { + tmp = selectCompanionObject(cm, head, character, inclusive); + } else if (selfPaired[character]) { + tmp = findBeginningAndEnd(cm, head, character, inclusive); + } else if (character === 'W') { + tmp = expandWordUnderCursor(cm, inclusive, true /** forward */, + true /** bigWord */); + } else if (character === 'w') { + tmp = expandWordUnderCursor(cm, inclusive, true /** forward */, + false /** bigWord */); + } else if (character === 'p') { + tmp = findParagraph(cm, head, motionArgs.repeat, 0, inclusive); + motionArgs.linewise = true; + if (vim.visualMode) { + if (!vim.visualLine) { vim.visualLine = true; } + } else { + var operatorArgs = vim.inputState.operatorArgs; + if (operatorArgs) { operatorArgs.linewise = true; } + tmp.end.line--; + } + } else { + // No text object defined for this, don't move. + return null; + } + + if (!cm.state.vim.visualMode) { + return [tmp.start, tmp.end]; + } else { + return expandSelection(cm, tmp.start, tmp.end); + } + }, + + repeatLastCharacterSearch: function(cm, head, motionArgs) { + var lastSearch = vimGlobalState.lastCharacterSearch; + var repeat = motionArgs.repeat; + var forward = motionArgs.forward === lastSearch.forward; + var increment = (lastSearch.increment ? 1 : 0) * (forward ? -1 : 1); + cm.moveH(-increment, 'char'); + motionArgs.inclusive = forward ? true : false; + var curEnd = moveToCharacter(cm, repeat, forward, lastSearch.selectedCharacter); + if (!curEnd) { + cm.moveH(increment, 'char'); + return head; + } + curEnd.ch += increment; + return curEnd; + } + }; + + function defineMotion(name, fn) { + motions[name] = fn; + } + + function fillArray(val, times) { + var arr = []; + for (var i = 0; i < times; i++) { + arr.push(val); + } + return arr; + } + /** + * An operator acts on a text selection. It receives the list of selections + * as input. The corresponding CodeMirror selection is guaranteed to + * match the input selection. + */ + var operators = { + change: function(cm, args, ranges) { + var finalHead, text; + var vim = cm.state.vim; + vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock = vim.visualBlock; + if (!vim.visualMode) { + var anchor = ranges[0].anchor, + head = ranges[0].head; + text = cm.getRange(anchor, head); + var lastState = vim.lastEditInputState || {}; + if (lastState.motion == "moveByWords" && !isWhiteSpaceString(text)) { + // Exclude trailing whitespace if the range is not all whitespace. + var match = (/\s+$/).exec(text); + if (match && lastState.motionArgs && lastState.motionArgs.forward) { + head = offsetCursor(head, 0, - match[0].length); + text = text.slice(0, - match[0].length); + } + } + var prevLineEnd = new Pos(anchor.line - 1, Number.MAX_VALUE); + var wasLastLine = cm.firstLine() == cm.lastLine(); + if (head.line > cm.lastLine() && args.linewise && !wasLastLine) { + cm.replaceRange('', prevLineEnd, head); + } else { + cm.replaceRange('', anchor, head); + } + if (args.linewise) { + // Push the next line back down, if there is a next line. + if (!wasLastLine) { + cm.setCursor(prevLineEnd); + CodeMirror.commands.newlineAndIndent(cm); + } + // make sure cursor ends up at the end of the line. + anchor.ch = Number.MAX_VALUE; + } + finalHead = anchor; + } else { + text = cm.getSelection(); + var replacement = fillArray('', ranges.length); + cm.replaceSelections(replacement); + finalHead = cursorMin(ranges[0].head, ranges[0].anchor); + } + vimGlobalState.registerController.pushText( + args.registerName, 'change', text, + args.linewise, ranges.length > 1); + actions.enterInsertMode(cm, {head: finalHead}, cm.state.vim); + }, + // delete is a javascript keyword. + 'delete': function(cm, args, ranges) { + var finalHead, text; + var vim = cm.state.vim; + if (!vim.visualBlock) { + var anchor = ranges[0].anchor, + head = ranges[0].head; + if (args.linewise && + head.line != cm.firstLine() && + anchor.line == cm.lastLine() && + anchor.line == head.line - 1) { + // Special case for dd on last line (and first line). + if (anchor.line == cm.firstLine()) { + anchor.ch = 0; + } else { + anchor = Pos(anchor.line - 1, lineLength(cm, anchor.line - 1)); + } + } + text = cm.getRange(anchor, head); + cm.replaceRange('', anchor, head); + finalHead = anchor; + if (args.linewise) { + finalHead = motions.moveToFirstNonWhiteSpaceCharacter(cm, anchor); + } + } else { + text = cm.getSelection(); + var replacement = fillArray('', ranges.length); + cm.replaceSelections(replacement); + finalHead = ranges[0].anchor; + } + vimGlobalState.registerController.pushText( + args.registerName, 'delete', text, + args.linewise, vim.visualBlock); + var includeLineBreak = vim.insertMode + return clipCursorToContent(cm, finalHead, includeLineBreak); + }, + indent: function(cm, args, ranges) { + var vim = cm.state.vim; + var startLine = ranges[0].anchor.line; + var endLine = vim.visualBlock ? + ranges[ranges.length - 1].anchor.line : + ranges[0].head.line; + // In visual mode, n> shifts the selection right n times, instead of + // shifting n lines right once. + var repeat = (vim.visualMode) ? args.repeat : 1; + if (args.linewise) { + // The only way to delete a newline is to delete until the start of + // the next line, so in linewise mode evalInput will include the next + // line. We don't want this in indent, so we go back a line. + endLine--; + } + for (var i = startLine; i <= endLine; i++) { + for (var j = 0; j < repeat; j++) { + cm.indentLine(i, args.indentRight); + } + } + return motions.moveToFirstNonWhiteSpaceCharacter(cm, ranges[0].anchor); + }, + changeCase: function(cm, args, ranges, oldAnchor, newHead) { + var selections = cm.getSelections(); + var swapped = []; + var toLower = args.toLower; + for (var j = 0; j < selections.length; j++) { + var toSwap = selections[j]; + var text = ''; + if (toLower === true) { + text = toSwap.toLowerCase(); + } else if (toLower === false) { + text = toSwap.toUpperCase(); + } else { + for (var i = 0; i < toSwap.length; i++) { + var character = toSwap.charAt(i); + text += isUpperCase(character) ? character.toLowerCase() : + character.toUpperCase(); + } + } + swapped.push(text); + } + cm.replaceSelections(swapped); + if (args.shouldMoveCursor){ + return newHead; + } else if (!cm.state.vim.visualMode && args.linewise && ranges[0].anchor.line + 1 == ranges[0].head.line) { + return motions.moveToFirstNonWhiteSpaceCharacter(cm, oldAnchor); + } else if (args.linewise){ + return oldAnchor; + } else { + return cursorMin(ranges[0].anchor, ranges[0].head); + } + }, + yank: function(cm, args, ranges, oldAnchor) { + var vim = cm.state.vim; + var text = cm.getSelection(); + var endPos = vim.visualMode + ? cursorMin(vim.sel.anchor, vim.sel.head, ranges[0].head, ranges[0].anchor) + : oldAnchor; + vimGlobalState.registerController.pushText( + args.registerName, 'yank', + text, args.linewise, vim.visualBlock); + return endPos; + } + }; + + function defineOperator(name, fn) { + operators[name] = fn; + } + + var actions = { + jumpListWalk: function(cm, actionArgs, vim) { + if (vim.visualMode) { + return; + } + var repeat = actionArgs.repeat; + var forward = actionArgs.forward; + var jumpList = vimGlobalState.jumpList; + + var mark = jumpList.move(cm, forward ? repeat : -repeat); + var markPos = mark ? mark.find() : undefined; + markPos = markPos ? markPos : cm.getCursor(); + cm.setCursor(markPos); + }, + scroll: function(cm, actionArgs, vim) { + if (vim.visualMode) { + return; + } + var repeat = actionArgs.repeat || 1; + var lineHeight = cm.defaultTextHeight(); + var top = cm.getScrollInfo().top; + var delta = lineHeight * repeat; + var newPos = actionArgs.forward ? top + delta : top - delta; + var cursor = copyCursor(cm.getCursor()); + var cursorCoords = cm.charCoords(cursor, 'local'); + if (actionArgs.forward) { + if (newPos > cursorCoords.top) { + cursor.line += (newPos - cursorCoords.top) / lineHeight; + cursor.line = Math.ceil(cursor.line); + cm.setCursor(cursor); + cursorCoords = cm.charCoords(cursor, 'local'); + cm.scrollTo(null, cursorCoords.top); + } else { + // Cursor stays within bounds. Just reposition the scroll window. + cm.scrollTo(null, newPos); + } + } else { + var newBottom = newPos + cm.getScrollInfo().clientHeight; + if (newBottom < cursorCoords.bottom) { + cursor.line -= (cursorCoords.bottom - newBottom) / lineHeight; + cursor.line = Math.floor(cursor.line); + cm.setCursor(cursor); + cursorCoords = cm.charCoords(cursor, 'local'); + cm.scrollTo( + null, cursorCoords.bottom - cm.getScrollInfo().clientHeight); + } else { + // Cursor stays within bounds. Just reposition the scroll window. + cm.scrollTo(null, newPos); + } + } + }, + scrollToCursor: function(cm, actionArgs) { + var lineNum = cm.getCursor().line; + var charCoords = cm.charCoords(Pos(lineNum, 0), 'local'); + var height = cm.getScrollInfo().clientHeight; + var y = charCoords.top; + var lineHeight = charCoords.bottom - y; + switch (actionArgs.position) { + case 'center': y = y - (height / 2) + lineHeight; + break; + case 'bottom': y = y - height + lineHeight; + break; + } + cm.scrollTo(null, y); + }, + replayMacro: function(cm, actionArgs, vim) { + var registerName = actionArgs.selectedCharacter; + var repeat = actionArgs.repeat; + var macroModeState = vimGlobalState.macroModeState; + if (registerName == '@') { + registerName = macroModeState.latestRegister; + } + while(repeat--){ + executeMacroRegister(cm, vim, macroModeState, registerName); + } + }, + enterMacroRecordMode: function(cm, actionArgs) { + var macroModeState = vimGlobalState.macroModeState; + var registerName = actionArgs.selectedCharacter; + if (vimGlobalState.registerController.isValidRegister(registerName)) { + macroModeState.enterMacroRecordMode(cm, registerName); + } + }, + toggleOverwrite: function(cm) { + if (!cm.state.overwrite) { + cm.toggleOverwrite(true); + cm.setOption('keyMap', 'vim-replace'); + CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"}); + } else { + cm.toggleOverwrite(false); + cm.setOption('keyMap', 'vim-insert'); + CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"}); + } + }, + enterInsertMode: function(cm, actionArgs, vim) { + if (cm.getOption('readOnly')) { return; } + vim.insertMode = true; + vim.insertModeRepeat = actionArgs && actionArgs.repeat || 1; + var insertAt = (actionArgs) ? actionArgs.insertAt : null; + var sel = vim.sel; + var head = actionArgs.head || cm.getCursor('head'); + var height = cm.listSelections().length; + if (insertAt == 'eol') { + head = Pos(head.line, lineLength(cm, head.line)); + } else if (insertAt == 'charAfter') { + head = offsetCursor(head, 0, 1); + } else if (insertAt == 'firstNonBlank') { + head = motions.moveToFirstNonWhiteSpaceCharacter(cm, head); + } else if (insertAt == 'startOfSelectedArea') { + if (!vim.visualBlock) { + if (sel.head.line < sel.anchor.line) { + head = sel.head; + } else { + head = Pos(sel.anchor.line, 0); + } + } else { + head = Pos( + Math.min(sel.head.line, sel.anchor.line), + Math.min(sel.head.ch, sel.anchor.ch)); + height = Math.abs(sel.head.line - sel.anchor.line) + 1; + } + } else if (insertAt == 'endOfSelectedArea') { + if (!vim.visualBlock) { + if (sel.head.line >= sel.anchor.line) { + head = offsetCursor(sel.head, 0, 1); + } else { + head = Pos(sel.anchor.line, 0); + } + } else { + head = Pos( + Math.min(sel.head.line, sel.anchor.line), + Math.max(sel.head.ch + 1, sel.anchor.ch)); + height = Math.abs(sel.head.line - sel.anchor.line) + 1; + } + } else if (insertAt == 'inplace') { + if (vim.visualMode){ + return; + } + } + cm.setOption('disableInput', false); + if (actionArgs && actionArgs.replace) { + // Handle Replace-mode as a special case of insert mode. + cm.toggleOverwrite(true); + cm.setOption('keyMap', 'vim-replace'); + CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"}); + } else { + cm.toggleOverwrite(false); + cm.setOption('keyMap', 'vim-insert'); + CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"}); + } + if (!vimGlobalState.macroModeState.isPlaying) { + // Only record if not replaying. + cm.on('change', onChange); + CodeMirror.on(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown); + } + if (vim.visualMode) { + exitVisualMode(cm); + } + selectForInsert(cm, head, height); + }, + toggleVisualMode: function(cm, actionArgs, vim) { + var repeat = actionArgs.repeat; + var anchor = cm.getCursor(); + var head; + // TODO: The repeat should actually select number of characters/lines + // equal to the repeat times the size of the previous visual + // operation. + if (!vim.visualMode) { + // Entering visual mode + vim.visualMode = true; + vim.visualLine = !!actionArgs.linewise; + vim.visualBlock = !!actionArgs.blockwise; + head = clipCursorToContent( + cm, Pos(anchor.line, anchor.ch + repeat - 1), + true /** includeLineBreak */); + vim.sel = { + anchor: anchor, + head: head + }; + CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""}); + updateCmSelection(cm); + updateMark(cm, vim, '<', cursorMin(anchor, head)); + updateMark(cm, vim, '>', cursorMax(anchor, head)); + } else if (vim.visualLine ^ actionArgs.linewise || + vim.visualBlock ^ actionArgs.blockwise) { + // Toggling between modes + vim.visualLine = !!actionArgs.linewise; + vim.visualBlock = !!actionArgs.blockwise; + CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""}); + updateCmSelection(cm); + } else { + exitVisualMode(cm); + } + }, + reselectLastSelection: function(cm, _actionArgs, vim) { + var lastSelection = vim.lastSelection; + if (vim.visualMode) { + updateLastSelection(cm, vim); + } + if (lastSelection) { + var anchor = lastSelection.anchorMark.find(); + var head = lastSelection.headMark.find(); + if (!anchor || !head) { + // If the marks have been destroyed due to edits, do nothing. + return; + } + vim.sel = { + anchor: anchor, + head: head + }; + vim.visualMode = true; + vim.visualLine = lastSelection.visualLine; + vim.visualBlock = lastSelection.visualBlock; + updateCmSelection(cm); + updateMark(cm, vim, '<', cursorMin(anchor, head)); + updateMark(cm, vim, '>', cursorMax(anchor, head)); + CodeMirror.signal(cm, 'vim-mode-change', { + mode: 'visual', + subMode: vim.visualLine ? 'linewise' : + vim.visualBlock ? 'blockwise' : ''}); + } + }, + joinLines: function(cm, actionArgs, vim) { + var curStart, curEnd; + if (vim.visualMode) { + curStart = cm.getCursor('anchor'); + curEnd = cm.getCursor('head'); + if (cursorIsBefore(curEnd, curStart)) { + var tmp = curEnd; + curEnd = curStart; + curStart = tmp; + } + curEnd.ch = lineLength(cm, curEnd.line) - 1; + } else { + // Repeat is the number of lines to join. Minimum 2 lines. + var repeat = Math.max(actionArgs.repeat, 2); + curStart = cm.getCursor(); + curEnd = clipCursorToContent(cm, Pos(curStart.line + repeat - 1, + Infinity)); + } + var finalCh = 0; + for (var i = curStart.line; i < curEnd.line; i++) { + finalCh = lineLength(cm, curStart.line); + var tmp = Pos(curStart.line + 1, + lineLength(cm, curStart.line + 1)); + var text = cm.getRange(curStart, tmp); + text = text.replace(/\n\s*/g, ' '); + cm.replaceRange(text, curStart, tmp); + } + var curFinalPos = Pos(curStart.line, finalCh); + if (vim.visualMode) { + exitVisualMode(cm, false); + } + cm.setCursor(curFinalPos); + }, + newLineAndEnterInsertMode: function(cm, actionArgs, vim) { + vim.insertMode = true; + var insertAt = copyCursor(cm.getCursor()); + if (insertAt.line === cm.firstLine() && !actionArgs.after) { + // Special case for inserting newline before start of document. + cm.replaceRange('\n', Pos(cm.firstLine(), 0)); + cm.setCursor(cm.firstLine(), 0); + } else { + insertAt.line = (actionArgs.after) ? insertAt.line : + insertAt.line - 1; + insertAt.ch = lineLength(cm, insertAt.line); + cm.setCursor(insertAt); + var newlineFn = CodeMirror.commands.newlineAndIndentContinueComment || + CodeMirror.commands.newlineAndIndent; + newlineFn(cm); + } + this.enterInsertMode(cm, { repeat: actionArgs.repeat }, vim); + }, + paste: function(cm, actionArgs, vim) { + var cur = copyCursor(cm.getCursor()); + var register = vimGlobalState.registerController.getRegister( + actionArgs.registerName); + var text = register.toString(); + if (!text) { + return; + } + if (actionArgs.matchIndent) { + var tabSize = cm.getOption("tabSize"); + // length that considers tabs and tabSize + var whitespaceLength = function(str) { + var tabs = (str.split("\t").length - 1); + var spaces = (str.split(" ").length - 1); + return tabs * tabSize + spaces * 1; + }; + var currentLine = cm.getLine(cm.getCursor().line); + var indent = whitespaceLength(currentLine.match(/^\s*/)[0]); + // chomp last newline b/c don't want it to match /^\s*/gm + var chompedText = text.replace(/\n$/, ''); + var wasChomped = text !== chompedText; + var firstIndent = whitespaceLength(text.match(/^\s*/)[0]); + var text = chompedText.replace(/^\s*/gm, function(wspace) { + var newIndent = indent + (whitespaceLength(wspace) - firstIndent); + if (newIndent < 0) { + return ""; + } + else if (cm.getOption("indentWithTabs")) { + var quotient = Math.floor(newIndent / tabSize); + return Array(quotient + 1).join('\t'); + } + else { + return Array(newIndent + 1).join(' '); + } + }); + text += wasChomped ? "\n" : ""; + } + if (actionArgs.repeat > 1) { + var text = Array(actionArgs.repeat + 1).join(text); + } + var linewise = register.linewise; + var blockwise = register.blockwise; + if (linewise) { + if(vim.visualMode) { + text = vim.visualLine ? text.slice(0, -1) : '\n' + text.slice(0, text.length - 1) + '\n'; + } else if (actionArgs.after) { + // Move the newline at the end to the start instead, and paste just + // before the newline character of the line we are on right now. + text = '\n' + text.slice(0, text.length - 1); + cur.ch = lineLength(cm, cur.line); + } else { + cur.ch = 0; + } + } else { + if (blockwise) { + text = text.split('\n'); + for (var i = 0; i < text.length; i++) { + text[i] = (text[i] == '') ? ' ' : text[i]; + } + } + cur.ch += actionArgs.after ? 1 : 0; + } + var curPosFinal; + var idx; + if (vim.visualMode) { + // save the pasted text for reselection if the need arises + vim.lastPastedText = text; + var lastSelectionCurEnd; + var selectedArea = getSelectedAreaRange(cm, vim); + var selectionStart = selectedArea[0]; + var selectionEnd = selectedArea[1]; + var selectedText = cm.getSelection(); + var selections = cm.listSelections(); + var emptyStrings = new Array(selections.length).join('1').split('1'); + // save the curEnd marker before it get cleared due to cm.replaceRange. + if (vim.lastSelection) { + lastSelectionCurEnd = vim.lastSelection.headMark.find(); + } + // push the previously selected text to unnamed register + vimGlobalState.registerController.unnamedRegister.setText(selectedText); + if (blockwise) { + // first delete the selected text + cm.replaceSelections(emptyStrings); + // Set new selections as per the block length of the yanked text + selectionEnd = Pos(selectionStart.line + text.length-1, selectionStart.ch); + cm.setCursor(selectionStart); + selectBlock(cm, selectionEnd); + cm.replaceSelections(text); + curPosFinal = selectionStart; + } else if (vim.visualBlock) { + cm.replaceSelections(emptyStrings); + cm.setCursor(selectionStart); + cm.replaceRange(text, selectionStart, selectionStart); + curPosFinal = selectionStart; + } else { + cm.replaceRange(text, selectionStart, selectionEnd); + curPosFinal = cm.posFromIndex(cm.indexFromPos(selectionStart) + text.length - 1); + } + // restore the the curEnd marker + if(lastSelectionCurEnd) { + vim.lastSelection.headMark = cm.setBookmark(lastSelectionCurEnd); + } + if (linewise) { + curPosFinal.ch=0; + } + } else { + if (blockwise) { + cm.setCursor(cur); + for (var i = 0; i < text.length; i++) { + var line = cur.line+i; + if (line > cm.lastLine()) { + cm.replaceRange('\n', Pos(line, 0)); + } + var lastCh = lineLength(cm, line); + if (lastCh < cur.ch) { + extendLineToColumn(cm, line, cur.ch); + } + } + cm.setCursor(cur); + selectBlock(cm, Pos(cur.line + text.length-1, cur.ch)); + cm.replaceSelections(text); + curPosFinal = cur; + } else { + cm.replaceRange(text, cur); + // Now fine tune the cursor to where we want it. + if (linewise && actionArgs.after) { + curPosFinal = Pos( + cur.line + 1, + findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line + 1))); + } else if (linewise && !actionArgs.after) { + curPosFinal = Pos( + cur.line, + findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line))); + } else if (!linewise && actionArgs.after) { + idx = cm.indexFromPos(cur); + curPosFinal = cm.posFromIndex(idx + text.length - 1); + } else { + idx = cm.indexFromPos(cur); + curPosFinal = cm.posFromIndex(idx + text.length); + } + } + } + if (vim.visualMode) { + exitVisualMode(cm, false); + } + cm.setCursor(curPosFinal); + }, + undo: function(cm, actionArgs) { + cm.operation(function() { + repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)(); + cm.setCursor(cm.getCursor('anchor')); + }); + }, + redo: function(cm, actionArgs) { + repeatFn(cm, CodeMirror.commands.redo, actionArgs.repeat)(); + }, + setRegister: function(_cm, actionArgs, vim) { + vim.inputState.registerName = actionArgs.selectedCharacter; + }, + setMark: function(cm, actionArgs, vim) { + var markName = actionArgs.selectedCharacter; + updateMark(cm, vim, markName, cm.getCursor()); + }, + replace: function(cm, actionArgs, vim) { + var replaceWith = actionArgs.selectedCharacter; + var curStart = cm.getCursor(); + var replaceTo; + var curEnd; + var selections = cm.listSelections(); + if (vim.visualMode) { + curStart = cm.getCursor('start'); + curEnd = cm.getCursor('end'); + } else { + var line = cm.getLine(curStart.line); + replaceTo = curStart.ch + actionArgs.repeat; + if (replaceTo > line.length) { + replaceTo=line.length; + } + curEnd = Pos(curStart.line, replaceTo); + } + if (replaceWith=='\n') { + if (!vim.visualMode) cm.replaceRange('', curStart, curEnd); + // special case, where vim help says to replace by just one line-break + (CodeMirror.commands.newlineAndIndentContinueComment || CodeMirror.commands.newlineAndIndent)(cm); + } else { + var replaceWithStr = cm.getRange(curStart, curEnd); + //replace all characters in range by selected, but keep linebreaks + replaceWithStr = replaceWithStr.replace(/[^\n]/g, replaceWith); + if (vim.visualBlock) { + // Tabs are split in visua block before replacing + var spaces = new Array(cm.getOption("tabSize")+1).join(' '); + replaceWithStr = cm.getSelection(); + replaceWithStr = replaceWithStr.replace(/\t/g, spaces).replace(/[^\n]/g, replaceWith).split('\n'); + cm.replaceSelections(replaceWithStr); + } else { + cm.replaceRange(replaceWithStr, curStart, curEnd); + } + if (vim.visualMode) { + curStart = cursorIsBefore(selections[0].anchor, selections[0].head) ? + selections[0].anchor : selections[0].head; + cm.setCursor(curStart); + exitVisualMode(cm, false); + } else { + cm.setCursor(offsetCursor(curEnd, 0, -1)); + } + } + }, + incrementNumberToken: function(cm, actionArgs) { + var cur = cm.getCursor(); + var lineStr = cm.getLine(cur.line); + var re = /-?\d+/g; + var match; + var start; + var end; + var numberStr; + var token; + while ((match = re.exec(lineStr)) !== null) { + token = match[0]; + start = match.index; + end = start + token.length; + if (cur.ch < end)break; + } + if (!actionArgs.backtrack && (end <= cur.ch))return; + if (token) { + var increment = actionArgs.increase ? 1 : -1; + var number = parseInt(token) + (increment * actionArgs.repeat); + var from = Pos(cur.line, start); + var to = Pos(cur.line, end); + numberStr = number.toString(); + cm.replaceRange(numberStr, from, to); + } else { + return; + } + cm.setCursor(Pos(cur.line, start + numberStr.length - 1)); + }, + repeatLastEdit: function(cm, actionArgs, vim) { + var lastEditInputState = vim.lastEditInputState; + if (!lastEditInputState) { return; } + var repeat = actionArgs.repeat; + if (repeat && actionArgs.repeatIsExplicit) { + vim.lastEditInputState.repeatOverride = repeat; + } else { + repeat = vim.lastEditInputState.repeatOverride || repeat; + } + repeatLastEdit(cm, vim, repeat, false /** repeatForInsert */); + }, + indent: function(cm, actionArgs) { + cm.indentLine(cm.getCursor().line, actionArgs.indentRight); + }, + exitInsertMode: exitInsertMode + }; + + function defineAction(name, fn) { + actions[name] = fn; + } + + /* + * Below are miscellaneous utility functions used by vim.js + */ + + /** + * Clips cursor to ensure that line is within the buffer's range + * If includeLineBreak is true, then allow cur.ch == lineLength. + */ + function clipCursorToContent(cm, cur, includeLineBreak) { + var line = Math.min(Math.max(cm.firstLine(), cur.line), cm.lastLine() ); + var maxCh = lineLength(cm, line) - 1; + maxCh = (includeLineBreak) ? maxCh + 1 : maxCh; + var ch = Math.min(Math.max(0, cur.ch), maxCh); + return Pos(line, ch); + } + function copyArgs(args) { + var ret = {}; + for (var prop in args) { + if (args.hasOwnProperty(prop)) { + ret[prop] = args[prop]; + } + } + return ret; + } + function offsetCursor(cur, offsetLine, offsetCh) { + if (typeof offsetLine === 'object') { + offsetCh = offsetLine.ch; + offsetLine = offsetLine.line; + } + return Pos(cur.line + offsetLine, cur.ch + offsetCh); + } + function getOffset(anchor, head) { + return { + line: head.line - anchor.line, + ch: head.line - anchor.line + }; + } + function commandMatches(keys, keyMap, context, inputState) { + // Partial matches are not applied. They inform the key handler + // that the current key sequence is a subsequence of a valid key + // sequence, so that the key buffer is not cleared. + var match, partial = [], full = []; + for (var i = 0; i < keyMap.length; i++) { + var command = keyMap[i]; + if (context == 'insert' && command.context != 'insert' || + command.context && command.context != context || + inputState.operator && command.type == 'action' || + !(match = commandMatch(keys, command.keys))) { continue; } + if (match == 'partial') { partial.push(command); } + if (match == 'full') { full.push(command); } + } + return { + partial: partial.length && partial, + full: full.length && full + }; + } + function commandMatch(pressed, mapped) { + if (mapped.slice(-11) == '<character>') { + // Last character matches anything. + var prefixLen = mapped.length - 11; + var pressedPrefix = pressed.slice(0, prefixLen); + var mappedPrefix = mapped.slice(0, prefixLen); + return pressedPrefix == mappedPrefix && pressed.length > prefixLen ? 'full' : + mappedPrefix.indexOf(pressedPrefix) == 0 ? 'partial' : false; + } else { + return pressed == mapped ? 'full' : + mapped.indexOf(pressed) == 0 ? 'partial' : false; + } + } + function lastChar(keys) { + var match = /^.*(<[^>]+>)$/.exec(keys); + var selectedCharacter = match ? match[1] : keys.slice(-1); + if (selectedCharacter.length > 1){ + switch(selectedCharacter){ + case '<CR>': + selectedCharacter='\n'; + break; + case '<Space>': + selectedCharacter=' '; + break; + default: + selectedCharacter=''; + break; + } + } + return selectedCharacter; + } + function repeatFn(cm, fn, repeat) { + return function() { + for (var i = 0; i < repeat; i++) { + fn(cm); + } + }; + } + function copyCursor(cur) { + return Pos(cur.line, cur.ch); + } + function cursorEqual(cur1, cur2) { + return cur1.ch == cur2.ch && cur1.line == cur2.line; + } + function cursorIsBefore(cur1, cur2) { + if (cur1.line < cur2.line) { + return true; + } + if (cur1.line == cur2.line && cur1.ch < cur2.ch) { + return true; + } + return false; + } + function cursorMin(cur1, cur2) { + if (arguments.length > 2) { + cur2 = cursorMin.apply(undefined, Array.prototype.slice.call(arguments, 1)); + } + return cursorIsBefore(cur1, cur2) ? cur1 : cur2; + } + function cursorMax(cur1, cur2) { + if (arguments.length > 2) { + cur2 = cursorMax.apply(undefined, Array.prototype.slice.call(arguments, 1)); + } + return cursorIsBefore(cur1, cur2) ? cur2 : cur1; + } + function cursorIsBetween(cur1, cur2, cur3) { + // returns true if cur2 is between cur1 and cur3. + var cur1before2 = cursorIsBefore(cur1, cur2); + var cur2before3 = cursorIsBefore(cur2, cur3); + return cur1before2 && cur2before3; + } + function lineLength(cm, lineNum) { + return cm.getLine(lineNum).length; + } + function trim(s) { + if (s.trim) { + return s.trim(); + } + return s.replace(/^\s+|\s+$/g, ''); + } + function escapeRegex(s) { + return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g, '\\$1'); + } + function extendLineToColumn(cm, lineNum, column) { + var endCh = lineLength(cm, lineNum); + var spaces = new Array(column-endCh+1).join(' '); + cm.setCursor(Pos(lineNum, endCh)); + cm.replaceRange(spaces, cm.getCursor()); + } + // This functions selects a rectangular block + // of text with selectionEnd as any of its corner + // Height of block: + // Difference in selectionEnd.line and first/last selection.line + // Width of the block: + // Distance between selectionEnd.ch and any(first considered here) selection.ch + function selectBlock(cm, selectionEnd) { + var selections = [], ranges = cm.listSelections(); + var head = copyCursor(cm.clipPos(selectionEnd)); + var isClipped = !cursorEqual(selectionEnd, head); + var curHead = cm.getCursor('head'); + var primIndex = getIndex(ranges, curHead); + var wasClipped = cursorEqual(ranges[primIndex].head, ranges[primIndex].anchor); + var max = ranges.length - 1; + var index = max - primIndex > primIndex ? max : 0; + var base = ranges[index].anchor; + + var firstLine = Math.min(base.line, head.line); + var lastLine = Math.max(base.line, head.line); + var baseCh = base.ch, headCh = head.ch; + + var dir = ranges[index].head.ch - baseCh; + var newDir = headCh - baseCh; + if (dir > 0 && newDir <= 0) { + baseCh++; + if (!isClipped) { headCh--; } + } else if (dir < 0 && newDir >= 0) { + baseCh--; + if (!wasClipped) { headCh++; } + } else if (dir < 0 && newDir == -1) { + baseCh--; + headCh++; + } + for (var line = firstLine; line <= lastLine; line++) { + var range = {anchor: new Pos(line, baseCh), head: new Pos(line, headCh)}; + selections.push(range); + } + cm.setSelections(selections); + selectionEnd.ch = headCh; + base.ch = baseCh; + return base; + } + function selectForInsert(cm, head, height) { + var sel = []; + for (var i = 0; i < height; i++) { + var lineHead = offsetCursor(head, i, 0); + sel.push({anchor: lineHead, head: lineHead}); + } + cm.setSelections(sel, 0); + } + // getIndex returns the index of the cursor in the selections. + function getIndex(ranges, cursor, end) { + for (var i = 0; i < ranges.length; i++) { + var atAnchor = end != 'head' && cursorEqual(ranges[i].anchor, cursor); + var atHead = end != 'anchor' && cursorEqual(ranges[i].head, cursor); + if (atAnchor || atHead) { + return i; + } + } + return -1; + } + function getSelectedAreaRange(cm, vim) { + var lastSelection = vim.lastSelection; + var getCurrentSelectedAreaRange = function() { + var selections = cm.listSelections(); + var start = selections[0]; + var end = selections[selections.length-1]; + var selectionStart = cursorIsBefore(start.anchor, start.head) ? start.anchor : start.head; + var selectionEnd = cursorIsBefore(end.anchor, end.head) ? end.head : end.anchor; + return [selectionStart, selectionEnd]; + }; + var getLastSelectedAreaRange = function() { + var selectionStart = cm.getCursor(); + var selectionEnd = cm.getCursor(); + var block = lastSelection.visualBlock; + if (block) { + var width = block.width; + var height = block.height; + selectionEnd = Pos(selectionStart.line + height, selectionStart.ch + width); + var selections = []; + // selectBlock creates a 'proper' rectangular block. + // We do not want that in all cases, so we manually set selections. + for (var i = selectionStart.line; i < selectionEnd.line; i++) { + var anchor = Pos(i, selectionStart.ch); + var head = Pos(i, selectionEnd.ch); + var range = {anchor: anchor, head: head}; + selections.push(range); + } + cm.setSelections(selections); + } else { + var start = lastSelection.anchorMark.find(); + var end = lastSelection.headMark.find(); + var line = end.line - start.line; + var ch = end.ch - start.ch; + selectionEnd = {line: selectionEnd.line + line, ch: line ? selectionEnd.ch : ch + selectionEnd.ch}; + if (lastSelection.visualLine) { + selectionStart = Pos(selectionStart.line, 0); + selectionEnd = Pos(selectionEnd.line, lineLength(cm, selectionEnd.line)); + } + cm.setSelection(selectionStart, selectionEnd); + } + return [selectionStart, selectionEnd]; + }; + if (!vim.visualMode) { + // In case of replaying the action. + return getLastSelectedAreaRange(); + } else { + return getCurrentSelectedAreaRange(); + } + } + // Updates the previous selection with the current selection's values. This + // should only be called in visual mode. + function updateLastSelection(cm, vim) { + var anchor = vim.sel.anchor; + var head = vim.sel.head; + // To accommodate the effect of lastPastedText in the last selection + if (vim.lastPastedText) { + head = cm.posFromIndex(cm.indexFromPos(anchor) + vim.lastPastedText.length); + vim.lastPastedText = null; + } + vim.lastSelection = {'anchorMark': cm.setBookmark(anchor), + 'headMark': cm.setBookmark(head), + 'anchor': copyCursor(anchor), + 'head': copyCursor(head), + 'visualMode': vim.visualMode, + 'visualLine': vim.visualLine, + 'visualBlock': vim.visualBlock}; + } + function expandSelection(cm, start, end) { + var sel = cm.state.vim.sel; + var head = sel.head; + var anchor = sel.anchor; + var tmp; + if (cursorIsBefore(end, start)) { + tmp = end; + end = start; + start = tmp; + } + if (cursorIsBefore(head, anchor)) { + head = cursorMin(start, head); + anchor = cursorMax(anchor, end); + } else { + anchor = cursorMin(start, anchor); + head = cursorMax(head, end); + head = offsetCursor(head, 0, -1); + if (head.ch == -1 && head.line != cm.firstLine()) { + head = Pos(head.line - 1, lineLength(cm, head.line - 1)); + } + } + return [anchor, head]; + } + /** + * Updates the CodeMirror selection to match the provided vim selection. + * If no arguments are given, it uses the current vim selection state. + */ + function updateCmSelection(cm, sel, mode) { + var vim = cm.state.vim; + sel = sel || vim.sel; + var mode = mode || + vim.visualLine ? 'line' : vim.visualBlock ? 'block' : 'char'; + var cmSel = makeCmSelection(cm, sel, mode); + cm.setSelections(cmSel.ranges, cmSel.primary); + updateFakeCursor(cm); + } + function makeCmSelection(cm, sel, mode, exclusive) { + var head = copyCursor(sel.head); + var anchor = copyCursor(sel.anchor); + if (mode == 'char') { + var headOffset = !exclusive && !cursorIsBefore(sel.head, sel.anchor) ? 1 : 0; + var anchorOffset = cursorIsBefore(sel.head, sel.anchor) ? 1 : 0; + head = offsetCursor(sel.head, 0, headOffset); + anchor = offsetCursor(sel.anchor, 0, anchorOffset); + return { + ranges: [{anchor: anchor, head: head}], + primary: 0 + }; + } else if (mode == 'line') { + if (!cursorIsBefore(sel.head, sel.anchor)) { + anchor.ch = 0; + + var lastLine = cm.lastLine(); + if (head.line > lastLine) { + head.line = lastLine; + } + head.ch = lineLength(cm, head.line); + } else { + head.ch = 0; + anchor.ch = lineLength(cm, anchor.line); + } + return { + ranges: [{anchor: anchor, head: head}], + primary: 0 + }; + } else if (mode == 'block') { + var top = Math.min(anchor.line, head.line), + left = Math.min(anchor.ch, head.ch), + bottom = Math.max(anchor.line, head.line), + right = Math.max(anchor.ch, head.ch) + 1; + var height = bottom - top + 1; + var primary = head.line == top ? 0 : height - 1; + var ranges = []; + for (var i = 0; i < height; i++) { + ranges.push({ + anchor: Pos(top + i, left), + head: Pos(top + i, right) + }); + } + return { + ranges: ranges, + primary: primary + }; + } + } + function getHead(cm) { + var cur = cm.getCursor('head'); + if (cm.getSelection().length == 1) { + // Small corner case when only 1 character is selected. The "real" + // head is the left of head and anchor. + cur = cursorMin(cur, cm.getCursor('anchor')); + } + return cur; + } + + /** + * If moveHead is set to false, the CodeMirror selection will not be + * touched. The caller assumes the responsibility of putting the cursor + * in the right place. + */ + function exitVisualMode(cm, moveHead) { + var vim = cm.state.vim; + if (moveHead !== false) { + cm.setCursor(clipCursorToContent(cm, vim.sel.head)); + } + updateLastSelection(cm, vim); + vim.visualMode = false; + vim.visualLine = false; + vim.visualBlock = false; + CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"}); + if (vim.fakeCursor) { + vim.fakeCursor.clear(); + } + } + + // Remove any trailing newlines from the selection. For + // example, with the caret at the start of the last word on the line, + // 'dw' should word, but not the newline, while 'w' should advance the + // caret to the first character of the next line. + function clipToLine(cm, curStart, curEnd) { + var selection = cm.getRange(curStart, curEnd); + // Only clip if the selection ends with trailing newline + whitespace + if (/\n\s*$/.test(selection)) { + var lines = selection.split('\n'); + // We know this is all whitespace. + lines.pop(); + + // Cases: + // 1. Last word is an empty line - do not clip the trailing '\n' + // 2. Last word is not an empty line - clip the trailing '\n' + var line; + // Find the line containing the last word, and clip all whitespace up + // to it. + for (var line = lines.pop(); lines.length > 0 && line && isWhiteSpaceString(line); line = lines.pop()) { + curEnd.line--; + curEnd.ch = 0; + } + // If the last word is not an empty line, clip an additional newline + if (line) { + curEnd.line--; + curEnd.ch = lineLength(cm, curEnd.line); + } else { + curEnd.ch = 0; + } + } + } + + // Expand the selection to line ends. + function expandSelectionToLine(_cm, curStart, curEnd) { + curStart.ch = 0; + curEnd.ch = 0; + curEnd.line++; + } + + function findFirstNonWhiteSpaceCharacter(text) { + if (!text) { + return 0; + } + var firstNonWS = text.search(/\S/); + return firstNonWS == -1 ? text.length : firstNonWS; + } + + function expandWordUnderCursor(cm, inclusive, _forward, bigWord, noSymbol) { + var cur = getHead(cm); + var line = cm.getLine(cur.line); + var idx = cur.ch; + + // Seek to first word or non-whitespace character, depending on if + // noSymbol is true. + var test = noSymbol ? wordCharTest[0] : bigWordCharTest [0]; + while (!test(line.charAt(idx))) { + idx++; + if (idx >= line.length) { return null; } + } + + if (bigWord) { + test = bigWordCharTest[0]; + } else { + test = wordCharTest[0]; + if (!test(line.charAt(idx))) { + test = wordCharTest[1]; + } + } + + var end = idx, start = idx; + while (test(line.charAt(end)) && end < line.length) { end++; } + while (test(line.charAt(start)) && start >= 0) { start--; } + start++; + + if (inclusive) { + // If present, include all whitespace after word. + // Otherwise, include all whitespace before word, except indentation. + var wordEnd = end; + while (/\s/.test(line.charAt(end)) && end < line.length) { end++; } + if (wordEnd == end) { + var wordStart = start; + while (/\s/.test(line.charAt(start - 1)) && start > 0) { start--; } + if (!start) { start = wordStart; } + } + } + return { start: Pos(cur.line, start), end: Pos(cur.line, end) }; + } + + function recordJumpPosition(cm, oldCur, newCur) { + if (!cursorEqual(oldCur, newCur)) { + vimGlobalState.jumpList.add(cm, oldCur, newCur); + } + } + + function recordLastCharacterSearch(increment, args) { + vimGlobalState.lastCharacterSearch.increment = increment; + vimGlobalState.lastCharacterSearch.forward = args.forward; + vimGlobalState.lastCharacterSearch.selectedCharacter = args.selectedCharacter; + } + + var symbolToMode = { + '(': 'bracket', ')': 'bracket', '{': 'bracket', '}': 'bracket', + '[': 'section', ']': 'section', + '*': 'comment', '/': 'comment', + 'm': 'method', 'M': 'method', + '#': 'preprocess' + }; + var findSymbolModes = { + bracket: { + isComplete: function(state) { + if (state.nextCh === state.symb) { + state.depth++; + if (state.depth >= 1)return true; + } else if (state.nextCh === state.reverseSymb) { + state.depth--; + } + return false; + } + }, + section: { + init: function(state) { + state.curMoveThrough = true; + state.symb = (state.forward ? ']' : '[') === state.symb ? '{' : '}'; + }, + isComplete: function(state) { + return state.index === 0 && state.nextCh === state.symb; + } + }, + comment: { + isComplete: function(state) { + var found = state.lastCh === '*' && state.nextCh === '/'; + state.lastCh = state.nextCh; + return found; + } + }, + // TODO: The original Vim implementation only operates on level 1 and 2. + // The current implementation doesn't check for code block level and + // therefore it operates on any levels. + method: { + init: function(state) { + state.symb = (state.symb === 'm' ? '{' : '}'); + state.reverseSymb = state.symb === '{' ? '}' : '{'; + }, + isComplete: function(state) { + if (state.nextCh === state.symb)return true; + return false; + } + }, + preprocess: { + init: function(state) { + state.index = 0; + }, + isComplete: function(state) { + if (state.nextCh === '#') { + var token = state.lineText.match(/#(\w+)/)[1]; + if (token === 'endif') { + if (state.forward && state.depth === 0) { + return true; + } + state.depth++; + } else if (token === 'if') { + if (!state.forward && state.depth === 0) { + return true; + } + state.depth--; + } + if (token === 'else' && state.depth === 0)return true; + } + return false; + } + } + }; + function findSymbol(cm, repeat, forward, symb) { + var cur = copyCursor(cm.getCursor()); + var increment = forward ? 1 : -1; + var endLine = forward ? cm.lineCount() : -1; + var curCh = cur.ch; + var line = cur.line; + var lineText = cm.getLine(line); + var state = { + lineText: lineText, + nextCh: lineText.charAt(curCh), + lastCh: null, + index: curCh, + symb: symb, + reverseSymb: (forward ? { ')': '(', '}': '{' } : { '(': ')', '{': '}' })[symb], + forward: forward, + depth: 0, + curMoveThrough: false + }; + var mode = symbolToMode[symb]; + if (!mode)return cur; + var init = findSymbolModes[mode].init; + var isComplete = findSymbolModes[mode].isComplete; + if (init) { init(state); } + while (line !== endLine && repeat) { + state.index += increment; + state.nextCh = state.lineText.charAt(state.index); + if (!state.nextCh) { + line += increment; + state.lineText = cm.getLine(line) || ''; + if (increment > 0) { + state.index = 0; + } else { + var lineLen = state.lineText.length; + state.index = (lineLen > 0) ? (lineLen-1) : 0; + } + state.nextCh = state.lineText.charAt(state.index); + } + if (isComplete(state)) { + cur.line = line; + cur.ch = state.index; + repeat--; + } + } + if (state.nextCh || state.curMoveThrough) { + return Pos(line, state.index); + } + return cur; + } + + /* + * Returns the boundaries of the next word. If the cursor in the middle of + * the word, then returns the boundaries of the current word, starting at + * the cursor. If the cursor is at the start/end of a word, and we are going + * forward/backward, respectively, find the boundaries of the next word. + * + * @param {CodeMirror} cm CodeMirror object. + * @param {Cursor} cur The cursor position. + * @param {boolean} forward True to search forward. False to search + * backward. + * @param {boolean} bigWord True if punctuation count as part of the word. + * False if only [a-zA-Z0-9] characters count as part of the word. + * @param {boolean} emptyLineIsWord True if empty lines should be treated + * as words. + * @return {Object{from:number, to:number, line: number}} The boundaries of + * the word, or null if there are no more words. + */ + function findWord(cm, cur, forward, bigWord, emptyLineIsWord) { + var lineNum = cur.line; + var pos = cur.ch; + var line = cm.getLine(lineNum); + var dir = forward ? 1 : -1; + var charTests = bigWord ? bigWordCharTest: wordCharTest; + + if (emptyLineIsWord && line == '') { + lineNum += dir; + line = cm.getLine(lineNum); + if (!isLine(cm, lineNum)) { + return null; + } + pos = (forward) ? 0 : line.length; + } + + while (true) { + if (emptyLineIsWord && line == '') { + return { from: 0, to: 0, line: lineNum }; + } + var stop = (dir > 0) ? line.length : -1; + var wordStart = stop, wordEnd = stop; + // Find bounds of next word. + while (pos != stop) { + var foundWord = false; + for (var i = 0; i < charTests.length && !foundWord; ++i) { + if (charTests[i](line.charAt(pos))) { + wordStart = pos; + // Advance to end of word. + while (pos != stop && charTests[i](line.charAt(pos))) { + pos += dir; + } + wordEnd = pos; + foundWord = wordStart != wordEnd; + if (wordStart == cur.ch && lineNum == cur.line && + wordEnd == wordStart + dir) { + // We started at the end of a word. Find the next one. + continue; + } else { + return { + from: Math.min(wordStart, wordEnd + 1), + to: Math.max(wordStart, wordEnd), + line: lineNum }; + } + } + } + if (!foundWord) { + pos += dir; + } + } + // Advance to next/prev line. + lineNum += dir; + if (!isLine(cm, lineNum)) { + return null; + } + line = cm.getLine(lineNum); + pos = (dir > 0) ? 0 : line.length; + } + } + + /** + * @param {CodeMirror} cm CodeMirror object. + * @param {Pos} cur The position to start from. + * @param {int} repeat Number of words to move past. + * @param {boolean} forward True to search forward. False to search + * backward. + * @param {boolean} wordEnd True to move to end of word. False to move to + * beginning of word. + * @param {boolean} bigWord True if punctuation count as part of the word. + * False if only alphabet characters count as part of the word. + * @return {Cursor} The position the cursor should move to. + */ + function moveToWord(cm, cur, repeat, forward, wordEnd, bigWord) { + var curStart = copyCursor(cur); + var words = []; + if (forward && !wordEnd || !forward && wordEnd) { + repeat++; + } + // For 'e', empty lines are not considered words, go figure. + var emptyLineIsWord = !(forward && wordEnd); + for (var i = 0; i < repeat; i++) { + var word = findWord(cm, cur, forward, bigWord, emptyLineIsWord); + if (!word) { + var eodCh = lineLength(cm, cm.lastLine()); + words.push(forward + ? {line: cm.lastLine(), from: eodCh, to: eodCh} + : {line: 0, from: 0, to: 0}); + break; + } + words.push(word); + cur = Pos(word.line, forward ? (word.to - 1) : word.from); + } + var shortCircuit = words.length != repeat; + var firstWord = words[0]; + var lastWord = words.pop(); + if (forward && !wordEnd) { + // w + if (!shortCircuit && (firstWord.from != curStart.ch || firstWord.line != curStart.line)) { + // We did not start in the middle of a word. Discard the extra word at the end. + lastWord = words.pop(); + } + return Pos(lastWord.line, lastWord.from); + } else if (forward && wordEnd) { + return Pos(lastWord.line, lastWord.to - 1); + } else if (!forward && wordEnd) { + // ge + if (!shortCircuit && (firstWord.to != curStart.ch || firstWord.line != curStart.line)) { + // We did not start in the middle of a word. Discard the extra word at the end. + lastWord = words.pop(); + } + return Pos(lastWord.line, lastWord.to); + } else { + // b + return Pos(lastWord.line, lastWord.from); + } + } + + function moveToCharacter(cm, repeat, forward, character) { + var cur = cm.getCursor(); + var start = cur.ch; + var idx; + for (var i = 0; i < repeat; i ++) { + var line = cm.getLine(cur.line); + idx = charIdxInLine(start, line, character, forward, true); + if (idx == -1) { + return null; + } + start = idx; + } + return Pos(cm.getCursor().line, idx); + } + + function moveToColumn(cm, repeat) { + // repeat is always >= 1, so repeat - 1 always corresponds + // to the column we want to go to. + var line = cm.getCursor().line; + return clipCursorToContent(cm, Pos(line, repeat - 1)); + } + + function updateMark(cm, vim, markName, pos) { + if (!inArray(markName, validMarks)) { + return; + } + if (vim.marks[markName]) { + vim.marks[markName].clear(); + } + vim.marks[markName] = cm.setBookmark(pos); + } + + function charIdxInLine(start, line, character, forward, includeChar) { + // Search for char in line. + // motion_options: {forward, includeChar} + // If includeChar = true, include it too. + // If forward = true, search forward, else search backwards. + // If char is not found on this line, do nothing + var idx; + if (forward) { + idx = line.indexOf(character, start + 1); + if (idx != -1 && !includeChar) { + idx -= 1; + } + } else { + idx = line.lastIndexOf(character, start - 1); + if (idx != -1 && !includeChar) { + idx += 1; + } + } + return idx; + } + + function findParagraph(cm, head, repeat, dir, inclusive) { + var line = head.line; + var min = cm.firstLine(); + var max = cm.lastLine(); + var start, end, i = line; + function isEmpty(i) { return !cm.getLine(i); } + function isBoundary(i, dir, any) { + if (any) { return isEmpty(i) != isEmpty(i + dir); } + return !isEmpty(i) && isEmpty(i + dir); + } + if (dir) { + while (min <= i && i <= max && repeat > 0) { + if (isBoundary(i, dir)) { repeat--; } + i += dir; + } + return new Pos(i, 0); + } + + var vim = cm.state.vim; + if (vim.visualLine && isBoundary(line, 1, true)) { + var anchor = vim.sel.anchor; + if (isBoundary(anchor.line, -1, true)) { + if (!inclusive || anchor.line != line) { + line += 1; + } + } + } + var startState = isEmpty(line); + for (i = line; i <= max && repeat; i++) { + if (isBoundary(i, 1, true)) { + if (!inclusive || isEmpty(i) != startState) { + repeat--; + } + } + } + end = new Pos(i, 0); + // select boundary before paragraph for the last one + if (i > max && !startState) { startState = true; } + else { inclusive = false; } + for (i = line; i > min; i--) { + if (!inclusive || isEmpty(i) == startState || i == line) { + if (isBoundary(i, -1, true)) { break; } + } + } + start = new Pos(i, 0); + return { start: start, end: end }; + } + + // TODO: perhaps this finagling of start and end positions belonds + // in codemirror/replaceRange? + function selectCompanionObject(cm, head, symb, inclusive) { + var cur = head, start, end; + + var bracketRegexp = ({ + '(': /[()]/, ')': /[()]/, + '[': /[[\]]/, ']': /[[\]]/, + '{': /[{}]/, '}': /[{}]/})[symb]; + var openSym = ({ + '(': '(', ')': '(', + '[': '[', ']': '[', + '{': '{', '}': '{'})[symb]; + var curChar = cm.getLine(cur.line).charAt(cur.ch); + // Due to the behavior of scanForBracket, we need to add an offset if the + // cursor is on a matching open bracket. + var offset = curChar === openSym ? 1 : 0; + + start = cm.scanForBracket(Pos(cur.line, cur.ch + offset), -1, null, {'bracketRegex': bracketRegexp}); + end = cm.scanForBracket(Pos(cur.line, cur.ch + offset), 1, null, {'bracketRegex': bracketRegexp}); + + if (!start || !end) { + return { start: cur, end: cur }; + } + + start = start.pos; + end = end.pos; + + if ((start.line == end.line && start.ch > end.ch) + || (start.line > end.line)) { + var tmp = start; + start = end; + end = tmp; + } + + if (inclusive) { + end.ch += 1; + } else { + start.ch += 1; + } + + return { start: start, end: end }; + } + + // Takes in a symbol and a cursor and tries to simulate text objects that + // have identical opening and closing symbols + // TODO support across multiple lines + function findBeginningAndEnd(cm, head, symb, inclusive) { + var cur = copyCursor(head); + var line = cm.getLine(cur.line); + var chars = line.split(''); + var start, end, i, len; + var firstIndex = chars.indexOf(symb); + + // the decision tree is to always look backwards for the beginning first, + // but if the cursor is in front of the first instance of the symb, + // then move the cursor forward + if (cur.ch < firstIndex) { + cur.ch = firstIndex; + // Why is this line even here??? + // cm.setCursor(cur.line, firstIndex+1); + } + // otherwise if the cursor is currently on the closing symbol + else if (firstIndex < cur.ch && chars[cur.ch] == symb) { + end = cur.ch; // assign end to the current cursor + --cur.ch; // make sure to look backwards + } + + // if we're currently on the symbol, we've got a start + if (chars[cur.ch] == symb && !end) { + start = cur.ch + 1; // assign start to ahead of the cursor + } else { + // go backwards to find the start + for (i = cur.ch; i > -1 && !start; i--) { + if (chars[i] == symb) { + start = i + 1; + } + } + } + + // look forwards for the end symbol + if (start && !end) { + for (i = start, len = chars.length; i < len && !end; i++) { + if (chars[i] == symb) { + end = i; + } + } + } + + // nothing found + if (!start || !end) { + return { start: cur, end: cur }; + } + + // include the symbols + if (inclusive) { + --start; ++end; + } + + return { + start: Pos(cur.line, start), + end: Pos(cur.line, end) + }; + } + + // Search functions + defineOption('pcre', true, 'boolean'); + function SearchState() {} + SearchState.prototype = { + getQuery: function() { + return vimGlobalState.query; + }, + setQuery: function(query) { + vimGlobalState.query = query; + }, + getOverlay: function() { + return this.searchOverlay; + }, + setOverlay: function(overlay) { + this.searchOverlay = overlay; + }, + isReversed: function() { + return vimGlobalState.isReversed; + }, + setReversed: function(reversed) { + vimGlobalState.isReversed = reversed; + }, + getScrollbarAnnotate: function() { + return this.annotate; + }, + setScrollbarAnnotate: function(annotate) { + this.annotate = annotate; + } + }; + function getSearchState(cm) { + var vim = cm.state.vim; + return vim.searchState_ || (vim.searchState_ = new SearchState()); + } + function dialog(cm, template, shortText, onClose, options) { + if (cm.openDialog) { + cm.openDialog(template, onClose, { bottom: true, value: options.value, + onKeyDown: options.onKeyDown, onKeyUp: options.onKeyUp, + selectValueOnOpen: false}); + } + else { + onClose(prompt(shortText, '')); + } + } + function splitBySlash(argString) { + var slashes = findUnescapedSlashes(argString) || []; + if (!slashes.length) return []; + var tokens = []; + // in case of strings like foo/bar + if (slashes[0] !== 0) return; + for (var i = 0; i < slashes.length; i++) { + if (typeof slashes[i] == 'number') + tokens.push(argString.substring(slashes[i] + 1, slashes[i+1])); + } + return tokens; + } + + function findUnescapedSlashes(str) { + var escapeNextChar = false; + var slashes = []; + for (var i = 0; i < str.length; i++) { + var c = str.charAt(i); + if (!escapeNextChar && c == '/') { + slashes.push(i); + } + escapeNextChar = !escapeNextChar && (c == '\\'); + } + return slashes; + } + + // Translates a search string from ex (vim) syntax into javascript form. + function translateRegex(str) { + // When these match, add a '\' if unescaped or remove one if escaped. + var specials = '|(){'; + // Remove, but never add, a '\' for these. + var unescape = '}'; + var escapeNextChar = false; + var out = []; + for (var i = -1; i < str.length; i++) { + var c = str.charAt(i) || ''; + var n = str.charAt(i+1) || ''; + var specialComesNext = (n && specials.indexOf(n) != -1); + if (escapeNextChar) { + if (c !== '\\' || !specialComesNext) { + out.push(c); + } + escapeNextChar = false; + } else { + if (c === '\\') { + escapeNextChar = true; + // Treat the unescape list as special for removing, but not adding '\'. + if (n && unescape.indexOf(n) != -1) { + specialComesNext = true; + } + // Not passing this test means removing a '\'. + if (!specialComesNext || n === '\\') { + out.push(c); + } + } else { + out.push(c); + if (specialComesNext && n !== '\\') { + out.push('\\'); + } + } + } + } + return out.join(''); + } + + // Translates the replace part of a search and replace from ex (vim) syntax into + // javascript form. Similar to translateRegex, but additionally fixes back references + // (translates '\[0..9]' to '$[0..9]') and follows different rules for escaping '$'. + var charUnescapes = {'\\n': '\n', '\\r': '\r', '\\t': '\t'}; + function translateRegexReplace(str) { + var escapeNextChar = false; + var out = []; + for (var i = -1; i < str.length; i++) { + var c = str.charAt(i) || ''; + var n = str.charAt(i+1) || ''; + if (charUnescapes[c + n]) { + out.push(charUnescapes[c+n]); + i++; + } else if (escapeNextChar) { + // At any point in the loop, escapeNextChar is true if the previous + // character was a '\' and was not escaped. + out.push(c); + escapeNextChar = false; + } else { + if (c === '\\') { + escapeNextChar = true; + if ((isNumber(n) || n === '$')) { + out.push('$'); + } else if (n !== '/' && n !== '\\') { + out.push('\\'); + } + } else { + if (c === '$') { + out.push('$'); + } + out.push(c); + if (n === '/') { + out.push('\\'); + } + } + } + } + return out.join(''); + } + + // Unescape \ and / in the replace part, for PCRE mode. + var unescapes = {'\\/': '/', '\\\\': '\\', '\\n': '\n', '\\r': '\r', '\\t': '\t'}; + function unescapeRegexReplace(str) { + var stream = new CodeMirror.StringStream(str); + var output = []; + while (!stream.eol()) { + // Search for \. + while (stream.peek() && stream.peek() != '\\') { + output.push(stream.next()); + } + var matched = false; + for (var matcher in unescapes) { + if (stream.match(matcher, true)) { + matched = true; + output.push(unescapes[matcher]); + break; + } + } + if (!matched) { + // Don't change anything + output.push(stream.next()); + } + } + return output.join(''); + } + + /** + * Extract the regular expression from the query and return a Regexp object. + * Returns null if the query is blank. + * If ignoreCase is passed in, the Regexp object will have the 'i' flag set. + * If smartCase is passed in, and the query contains upper case letters, + * then ignoreCase is overridden, and the 'i' flag will not be set. + * If the query contains the /i in the flag part of the regular expression, + * then both ignoreCase and smartCase are ignored, and 'i' will be passed + * through to the Regex object. + */ + function parseQuery(query, ignoreCase, smartCase) { + // First update the last search register + var lastSearchRegister = vimGlobalState.registerController.getRegister('/'); + lastSearchRegister.setText(query); + // Check if the query is already a regex. + if (query instanceof RegExp) { return query; } + // First try to extract regex + flags from the input. If no flags found, + // extract just the regex. IE does not accept flags directly defined in + // the regex string in the form /regex/flags + var slashes = findUnescapedSlashes(query); + var regexPart; + var forceIgnoreCase; + if (!slashes.length) { + // Query looks like 'regexp' + regexPart = query; + } else { + // Query looks like 'regexp/...' + regexPart = query.substring(0, slashes[0]); + var flagsPart = query.substring(slashes[0]); + forceIgnoreCase = (flagsPart.indexOf('i') != -1); + } + if (!regexPart) { + return null; + } + if (!getOption('pcre')) { + regexPart = translateRegex(regexPart); + } + if (smartCase) { + ignoreCase = (/^[^A-Z]*$/).test(regexPart); + } + var regexp = new RegExp(regexPart, + (ignoreCase || forceIgnoreCase) ? 'i' : undefined); + return regexp; + } + function showConfirm(cm, text) { + if (cm.openNotification) { + cm.openNotification('<span style="color: red">' + text + '</span>', + {bottom: true, duration: 5000}); + } else { + alert(text); + } + } + function makePrompt(prefix, desc) { + var raw = '<span style="font-family: monospace; white-space: pre">' + + (prefix || "") + '<input type="text"></span>'; + if (desc) + raw += ' <span style="color: #888">' + desc + '</span>'; + return raw; + } + var searchPromptDesc = '(Javascript regexp)'; + function showPrompt(cm, options) { + var shortText = (options.prefix || '') + ' ' + (options.desc || ''); + var prompt = makePrompt(options.prefix, options.desc); + dialog(cm, prompt, shortText, options.onClose, options); + } + function regexEqual(r1, r2) { + if (r1 instanceof RegExp && r2 instanceof RegExp) { + var props = ['global', 'multiline', 'ignoreCase', 'source']; + for (var i = 0; i < props.length; i++) { + var prop = props[i]; + if (r1[prop] !== r2[prop]) { + return false; + } + } + return true; + } + return false; + } + // Returns true if the query is valid. + function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) { + if (!rawQuery) { + return; + } + var state = getSearchState(cm); + var query = parseQuery(rawQuery, !!ignoreCase, !!smartCase); + if (!query) { + return; + } + highlightSearchMatches(cm, query); + if (regexEqual(query, state.getQuery())) { + return query; + } + state.setQuery(query); + return query; + } + function searchOverlay(query) { + if (query.source.charAt(0) == '^') { + var matchSol = true; + } + return { + token: function(stream) { + if (matchSol && !stream.sol()) { + stream.skipToEnd(); + return; + } + var match = stream.match(query, false); + if (match) { + if (match[0].length == 0) { + // Matched empty string, skip to next. + stream.next(); + return 'searching'; + } + if (!stream.sol()) { + // Backtrack 1 to match \b + stream.backUp(1); + if (!query.exec(stream.next() + match[0])) { + stream.next(); + return null; + } + } + stream.match(query); + return 'searching'; + } + while (!stream.eol()) { + stream.next(); + if (stream.match(query, false)) break; + } + }, + query: query + }; + } + function highlightSearchMatches(cm, query) { + var searchState = getSearchState(cm); + var overlay = searchState.getOverlay(); + if (!overlay || query != overlay.query) { + if (overlay) { + cm.removeOverlay(overlay); + } + overlay = searchOverlay(query); + cm.addOverlay(overlay); + if (cm.showMatchesOnScrollbar) { + if (searchState.getScrollbarAnnotate()) { + searchState.getScrollbarAnnotate().clear(); + } + searchState.setScrollbarAnnotate(cm.showMatchesOnScrollbar(query)); + } + searchState.setOverlay(overlay); + } + } + function findNext(cm, prev, query, repeat) { + if (repeat === undefined) { repeat = 1; } + return cm.operation(function() { + var pos = cm.getCursor(); + var cursor = cm.getSearchCursor(query, pos); + for (var i = 0; i < repeat; i++) { + var found = cursor.find(prev); + if (i == 0 && found && cursorEqual(cursor.from(), pos)) { found = cursor.find(prev); } + if (!found) { + // SearchCursor may have returned null because it hit EOF, wrap + // around and try again. + cursor = cm.getSearchCursor(query, + (prev) ? Pos(cm.lastLine()) : Pos(cm.firstLine(), 0) ); + if (!cursor.find(prev)) { + return; + } + } + } + return cursor.from(); + }); + } + function clearSearchHighlight(cm) { + var state = getSearchState(cm); + cm.removeOverlay(getSearchState(cm).getOverlay()); + state.setOverlay(null); + if (state.getScrollbarAnnotate()) { + state.getScrollbarAnnotate().clear(); + state.setScrollbarAnnotate(null); + } + } + /** + * Check if pos is in the specified range, INCLUSIVE. + * Range can be specified with 1 or 2 arguments. + * If the first range argument is an array, treat it as an array of line + * numbers. Match pos against any of the lines. + * If the first range argument is a number, + * if there is only 1 range argument, check if pos has the same line + * number + * if there are 2 range arguments, then check if pos is in between the two + * range arguments. + */ + function isInRange(pos, start, end) { + if (typeof pos != 'number') { + // Assume it is a cursor position. Get the line number. + pos = pos.line; + } + if (start instanceof Array) { + return inArray(pos, start); + } else { + if (end) { + return (pos >= start && pos <= end); + } else { + return pos == start; + } + } + } + function getUserVisibleLines(cm) { + var scrollInfo = cm.getScrollInfo(); + var occludeToleranceTop = 6; + var occludeToleranceBottom = 10; + var from = cm.coordsChar({left:0, top: occludeToleranceTop + scrollInfo.top}, 'local'); + var bottomY = scrollInfo.clientHeight - occludeToleranceBottom + scrollInfo.top; + var to = cm.coordsChar({left:0, top: bottomY}, 'local'); + return {top: from.line, bottom: to.line}; + } + + function getMarkPos(cm, vim, markName) { + if (markName == '\'') { + var history = cm.doc.history.done; + var event = history[history.length - 2]; + return event && event.ranges && event.ranges[0].head; + } else if (markName == '.') { + if (cm.doc.history.lastModTime == 0) { + return // If no changes, bail out; don't bother to copy or reverse history array. + } else { + var changeHistory = cm.doc.history.done.filter(function(el){ if (el.changes !== undefined) { return el } }); + changeHistory.reverse(); + var lastEditPos = changeHistory[0].changes[0].to; + } + return lastEditPos; + } + + var mark = vim.marks[markName]; + return mark && mark.find(); + } + + var ExCommandDispatcher = function() { + this.buildCommandMap_(); + }; + ExCommandDispatcher.prototype = { + processCommand: function(cm, input, opt_params) { + var that = this; + cm.operation(function () { + cm.curOp.isVimOp = true; + that._processCommand(cm, input, opt_params); + }); + }, + _processCommand: function(cm, input, opt_params) { + var vim = cm.state.vim; + var commandHistoryRegister = vimGlobalState.registerController.getRegister(':'); + var previousCommand = commandHistoryRegister.toString(); + if (vim.visualMode) { + exitVisualMode(cm); + } + var inputStream = new CodeMirror.StringStream(input); + // update ": with the latest command whether valid or invalid + commandHistoryRegister.setText(input); + var params = opt_params || {}; + params.input = input; + try { + this.parseInput_(cm, inputStream, params); + } catch(e) { + showConfirm(cm, e); + throw e; + } + var command; + var commandName; + if (!params.commandName) { + // If only a line range is defined, move to the line. + if (params.line !== undefined) { + commandName = 'move'; + } + } else { + command = this.matchCommand_(params.commandName); + if (command) { + commandName = command.name; + if (command.excludeFromCommandHistory) { + commandHistoryRegister.setText(previousCommand); + } + this.parseCommandArgs_(inputStream, params, command); + if (command.type == 'exToKey') { + // Handle Ex to Key mapping. + for (var i = 0; i < command.toKeys.length; i++) { + CodeMirror.Vim.handleKey(cm, command.toKeys[i], 'mapping'); + } + return; + } else if (command.type == 'exToEx') { + // Handle Ex to Ex mapping. + this.processCommand(cm, command.toInput); + return; + } + } + } + if (!commandName) { + showConfirm(cm, 'Not an editor command ":' + input + '"'); + return; + } + try { + exCommands[commandName](cm, params); + // Possibly asynchronous commands (e.g. substitute, which might have a + // user confirmation), are responsible for calling the callback when + // done. All others have it taken care of for them here. + if ((!command || !command.possiblyAsync) && params.callback) { + params.callback(); + } + } catch(e) { + showConfirm(cm, e); + throw e; + } + }, + parseInput_: function(cm, inputStream, result) { + inputStream.eatWhile(':'); + // Parse range. + if (inputStream.eat('%')) { + result.line = cm.firstLine(); + result.lineEnd = cm.lastLine(); + } else { + result.line = this.parseLineSpec_(cm, inputStream); + if (result.line !== undefined && inputStream.eat(',')) { + result.lineEnd = this.parseLineSpec_(cm, inputStream); + } + } + + // Parse command name. + var commandMatch = inputStream.match(/^(\w+)/); + if (commandMatch) { + result.commandName = commandMatch[1]; + } else { + result.commandName = inputStream.match(/.*/)[0]; + } + + return result; + }, + parseLineSpec_: function(cm, inputStream) { + var numberMatch = inputStream.match(/^(\d+)/); + if (numberMatch) { + // Absolute line number plus offset (N+M or N-M) is probably a typo, + // not something the user actually wanted. (NB: vim does allow this.) + return parseInt(numberMatch[1], 10) - 1; + } + switch (inputStream.next()) { + case '.': + return this.parseLineSpecOffset_(inputStream, cm.getCursor().line); + case '$': + return this.parseLineSpecOffset_(inputStream, cm.lastLine()); + case '\'': + var markName = inputStream.next(); + var markPos = getMarkPos(cm, cm.state.vim, markName); + if (!markPos) throw new Error('Mark not set'); + return this.parseLineSpecOffset_(inputStream, markPos.line); + case '-': + case '+': + inputStream.backUp(1); + // Offset is relative to current line if not otherwise specified. + return this.parseLineSpecOffset_(inputStream, cm.getCursor().line); + default: + inputStream.backUp(1); + return undefined; + } + }, + parseLineSpecOffset_: function(inputStream, line) { + var offsetMatch = inputStream.match(/^([+-])?(\d+)/); + if (offsetMatch) { + var offset = parseInt(offsetMatch[2], 10); + if (offsetMatch[1] == "-") { + line -= offset; + } else { + line += offset; + } + } + return line; + }, + parseCommandArgs_: function(inputStream, params, command) { + if (inputStream.eol()) { + return; + } + params.argString = inputStream.match(/.*/)[0]; + // Parse command-line arguments + var delim = command.argDelimiter || /\s+/; + var args = trim(params.argString).split(delim); + if (args.length && args[0]) { + params.args = args; + } + }, + matchCommand_: function(commandName) { + // Return the command in the command map that matches the shortest + // prefix of the passed in command name. The match is guaranteed to be + // unambiguous if the defaultExCommandMap's shortNames are set up + // correctly. (see @code{defaultExCommandMap}). + for (var i = commandName.length; i > 0; i--) { + var prefix = commandName.substring(0, i); + if (this.commandMap_[prefix]) { + var command = this.commandMap_[prefix]; + if (command.name.indexOf(commandName) === 0) { + return command; + } + } + } + return null; + }, + buildCommandMap_: function() { + this.commandMap_ = {}; + for (var i = 0; i < defaultExCommandMap.length; i++) { + var command = defaultExCommandMap[i]; + var key = command.shortName || command.name; + this.commandMap_[key] = command; + } + }, + map: function(lhs, rhs, ctx) { + if (lhs != ':' && lhs.charAt(0) == ':') { + if (ctx) { throw Error('Mode not supported for ex mappings'); } + var commandName = lhs.substring(1); + if (rhs != ':' && rhs.charAt(0) == ':') { + // Ex to Ex mapping + this.commandMap_[commandName] = { + name: commandName, + type: 'exToEx', + toInput: rhs.substring(1), + user: true + }; + } else { + // Ex to key mapping + this.commandMap_[commandName] = { + name: commandName, + type: 'exToKey', + toKeys: rhs, + user: true + }; + } + } else { + if (rhs != ':' && rhs.charAt(0) == ':') { + // Key to Ex mapping. + var mapping = { + keys: lhs, + type: 'keyToEx', + exArgs: { input: rhs.substring(1) } + }; + if (ctx) { mapping.context = ctx; } + defaultKeymap.unshift(mapping); + } else { + // Key to key mapping + var mapping = { + keys: lhs, + type: 'keyToKey', + toKeys: rhs + }; + if (ctx) { mapping.context = ctx; } + defaultKeymap.unshift(mapping); + } + } + }, + unmap: function(lhs, ctx) { + if (lhs != ':' && lhs.charAt(0) == ':') { + // Ex to Ex or Ex to key mapping + if (ctx) { throw Error('Mode not supported for ex mappings'); } + var commandName = lhs.substring(1); + if (this.commandMap_[commandName] && this.commandMap_[commandName].user) { + delete this.commandMap_[commandName]; + return; + } + } else { + // Key to Ex or key to key mapping + var keys = lhs; + for (var i = 0; i < defaultKeymap.length; i++) { + if (keys == defaultKeymap[i].keys + && defaultKeymap[i].context === ctx) { + defaultKeymap.splice(i, 1); + return; + } + } + } + throw Error('No such mapping.'); + } + }; + + var exCommands = { + colorscheme: function(cm, params) { + if (!params.args || params.args.length < 1) { + showConfirm(cm, cm.getOption('theme')); + return; + } + cm.setOption('theme', params.args[0]); + }, + map: function(cm, params, ctx) { + var mapArgs = params.args; + if (!mapArgs || mapArgs.length < 2) { + if (cm) { + showConfirm(cm, 'Invalid mapping: ' + params.input); + } + return; + } + exCommandDispatcher.map(mapArgs[0], mapArgs[1], ctx); + }, + imap: function(cm, params) { this.map(cm, params, 'insert'); }, + nmap: function(cm, params) { this.map(cm, params, 'normal'); }, + vmap: function(cm, params) { this.map(cm, params, 'visual'); }, + unmap: function(cm, params, ctx) { + var mapArgs = params.args; + if (!mapArgs || mapArgs.length < 1) { + if (cm) { + showConfirm(cm, 'No such mapping: ' + params.input); + } + return; + } + exCommandDispatcher.unmap(mapArgs[0], ctx); + }, + move: function(cm, params) { + commandDispatcher.processCommand(cm, cm.state.vim, { + type: 'motion', + motion: 'moveToLineOrEdgeOfDocument', + motionArgs: { forward: false, explicitRepeat: true, + linewise: true }, + repeatOverride: params.line+1}); + }, + set: function(cm, params) { + var setArgs = params.args; + // Options passed through to the setOption/getOption calls. May be passed in by the + // local/global versions of the set command + var setCfg = params.setCfg || {}; + if (!setArgs || setArgs.length < 1) { + if (cm) { + showConfirm(cm, 'Invalid mapping: ' + params.input); + } + return; + } + var expr = setArgs[0].split('='); + var optionName = expr[0]; + var value = expr[1]; + var forceGet = false; + + if (optionName.charAt(optionName.length - 1) == '?') { + // If post-fixed with ?, then the set is actually a get. + if (value) { throw Error('Trailing characters: ' + params.argString); } + optionName = optionName.substring(0, optionName.length - 1); + forceGet = true; + } + if (value === undefined && optionName.substring(0, 2) == 'no') { + // To set boolean options to false, the option name is prefixed with + // 'no'. + optionName = optionName.substring(2); + value = false; + } + + var optionIsBoolean = options[optionName] && options[optionName].type == 'boolean'; + if (optionIsBoolean && value == undefined) { + // Calling set with a boolean option sets it to true. + value = true; + } + // If no value is provided, then we assume this is a get. + if (!optionIsBoolean && value === undefined || forceGet) { + var oldValue = getOption(optionName, cm, setCfg); + if (oldValue instanceof Error) { + showConfirm(cm, oldValue.message); + } else if (oldValue === true || oldValue === false) { + showConfirm(cm, ' ' + (oldValue ? '' : 'no') + optionName); + } else { + showConfirm(cm, ' ' + optionName + '=' + oldValue); + } + } else { + var setOptionReturn = setOption(optionName, value, cm, setCfg); + if (setOptionReturn instanceof Error) { + showConfirm(cm, setOptionReturn.message); + } + } + }, + setlocal: function (cm, params) { + // setCfg is passed through to setOption + params.setCfg = {scope: 'local'}; + this.set(cm, params); + }, + setglobal: function (cm, params) { + // setCfg is passed through to setOption + params.setCfg = {scope: 'global'}; + this.set(cm, params); + }, + registers: function(cm, params) { + var regArgs = params.args; + var registers = vimGlobalState.registerController.registers; + var regInfo = '----------Registers----------<br><br>'; + if (!regArgs) { + for (var registerName in registers) { + var text = registers[registerName].toString(); + if (text.length) { + regInfo += '"' + registerName + ' ' + text + '<br>'; + } + } + } else { + var registerName; + regArgs = regArgs.join(''); + for (var i = 0; i < regArgs.length; i++) { + registerName = regArgs.charAt(i); + if (!vimGlobalState.registerController.isValidRegister(registerName)) { + continue; + } + var register = registers[registerName] || new Register(); + regInfo += '"' + registerName + ' ' + register.toString() + '<br>'; + } + } + showConfirm(cm, regInfo); + }, + sort: function(cm, params) { + var reverse, ignoreCase, unique, number, pattern; + function parseArgs() { + if (params.argString) { + var args = new CodeMirror.StringStream(params.argString); + if (args.eat('!')) { reverse = true; } + if (args.eol()) { return; } + if (!args.eatSpace()) { return 'Invalid arguments'; } + var opts = args.match(/([dinuox]+)?\s*(\/.+\/)?\s*/); + if (!opts && !args.eol()) { return 'Invalid arguments'; } + if (opts[1]) { + ignoreCase = opts[1].indexOf('i') != -1; + unique = opts[1].indexOf('u') != -1; + var decimal = opts[1].indexOf('d') != -1 || opts[1].indexOf('n') != -1 && 1; + var hex = opts[1].indexOf('x') != -1 && 1; + var octal = opts[1].indexOf('o') != -1 && 1; + if (decimal + hex + octal > 1) { return 'Invalid arguments'; } + number = decimal && 'decimal' || hex && 'hex' || octal && 'octal'; + } + if (opts[2]) { + pattern = new RegExp(opts[2].substr(1, opts[2].length - 2), ignoreCase ? 'i' : ''); + } + } + } + var err = parseArgs(); + if (err) { + showConfirm(cm, err + ': ' + params.argString); + return; + } + var lineStart = params.line || cm.firstLine(); + var lineEnd = params.lineEnd || params.line || cm.lastLine(); + if (lineStart == lineEnd) { return; } + var curStart = Pos(lineStart, 0); + var curEnd = Pos(lineEnd, lineLength(cm, lineEnd)); + var text = cm.getRange(curStart, curEnd).split('\n'); + var numberRegex = pattern ? pattern : + (number == 'decimal') ? /(-?)([\d]+)/ : + (number == 'hex') ? /(-?)(?:0x)?([0-9a-f]+)/i : + (number == 'octal') ? /([0-7]+)/ : null; + var radix = (number == 'decimal') ? 10 : (number == 'hex') ? 16 : (number == 'octal') ? 8 : null; + var numPart = [], textPart = []; + if (number || pattern) { + for (var i = 0; i < text.length; i++) { + var matchPart = pattern ? text[i].match(pattern) : null; + if (matchPart && matchPart[0] != '') { + numPart.push(matchPart); + } else if (!pattern && numberRegex.exec(text[i])) { + numPart.push(text[i]); + } else { + textPart.push(text[i]); + } + } + } else { + textPart = text; + } + function compareFn(a, b) { + if (reverse) { var tmp; tmp = a; a = b; b = tmp; } + if (ignoreCase) { a = a.toLowerCase(); b = b.toLowerCase(); } + var anum = number && numberRegex.exec(a); + var bnum = number && numberRegex.exec(b); + if (!anum) { return a < b ? -1 : 1; } + anum = parseInt((anum[1] + anum[2]).toLowerCase(), radix); + bnum = parseInt((bnum[1] + bnum[2]).toLowerCase(), radix); + return anum - bnum; + } + function comparePatternFn(a, b) { + if (reverse) { var tmp; tmp = a; a = b; b = tmp; } + if (ignoreCase) { a[0] = a[0].toLowerCase(); b[0] = b[0].toLowerCase(); } + return (a[0] < b[0]) ? -1 : 1; + } + numPart.sort(pattern ? comparePatternFn : compareFn); + if (pattern) { + for (var i = 0; i < numPart.length; i++) { + numPart[i] = numPart[i].input; + } + } else if (!number) { textPart.sort(compareFn); } + text = (!reverse) ? textPart.concat(numPart) : numPart.concat(textPart); + if (unique) { // Remove duplicate lines + var textOld = text; + var lastLine; + text = []; + for (var i = 0; i < textOld.length; i++) { + if (textOld[i] != lastLine) { + text.push(textOld[i]); + } + lastLine = textOld[i]; + } + } + cm.replaceRange(text.join('\n'), curStart, curEnd); + }, + global: function(cm, params) { + // a global command is of the form + // :[range]g/pattern/[cmd] + // argString holds the string /pattern/[cmd] + var argString = params.argString; + if (!argString) { + showConfirm(cm, 'Regular Expression missing from global'); + return; + } + // range is specified here + var lineStart = (params.line !== undefined) ? params.line : cm.firstLine(); + var lineEnd = params.lineEnd || params.line || cm.lastLine(); + // get the tokens from argString + var tokens = splitBySlash(argString); + var regexPart = argString, cmd; + if (tokens.length) { + regexPart = tokens[0]; + cmd = tokens.slice(1, tokens.length).join('/'); + } + if (regexPart) { + // If regex part is empty, then use the previous query. Otherwise + // use the regex part as the new query. + try { + updateSearchQuery(cm, regexPart, true /** ignoreCase */, + true /** smartCase */); + } catch (e) { + showConfirm(cm, 'Invalid regex: ' + regexPart); + return; + } + } + // now that we have the regexPart, search for regex matches in the + // specified range of lines + var query = getSearchState(cm).getQuery(); + var matchedLines = [], content = ''; + for (var i = lineStart; i <= lineEnd; i++) { + var matched = query.test(cm.getLine(i)); + if (matched) { + matchedLines.push(i+1); + content+= cm.getLine(i) + '<br>'; + } + } + // if there is no [cmd], just display the list of matched lines + if (!cmd) { + showConfirm(cm, content); + return; + } + var index = 0; + var nextCommand = function() { + if (index < matchedLines.length) { + var command = matchedLines[index] + cmd; + exCommandDispatcher.processCommand(cm, command, { + callback: nextCommand + }); + } + index++; + }; + nextCommand(); + }, + substitute: function(cm, params) { + if (!cm.getSearchCursor) { + throw new Error('Search feature not available. Requires searchcursor.js or ' + + 'any other getSearchCursor implementation.'); + } + var argString = params.argString; + var tokens = argString ? splitBySlash(argString) : []; + var regexPart, replacePart = '', trailing, flagsPart, count; + var confirm = false; // Whether to confirm each replace. + var global = false; // True to replace all instances on a line, false to replace only 1. + if (tokens.length) { + regexPart = tokens[0]; + replacePart = tokens[1]; + if (regexPart && regexPart[regexPart.length - 1] === '$') { + regexPart = regexPart.slice(0, regexPart.length - 1) + '\\n'; + replacePart = replacePart ? replacePart + '\n' : '\n'; + } + if (replacePart !== undefined) { + if (getOption('pcre')) { + replacePart = unescapeRegexReplace(replacePart); + } else { + replacePart = translateRegexReplace(replacePart); + } + vimGlobalState.lastSubstituteReplacePart = replacePart; + } + trailing = tokens[2] ? tokens[2].split(' ') : []; + } else { + // either the argString is empty or its of the form ' hello/world' + // actually splitBySlash returns a list of tokens + // only if the string starts with a '/' + if (argString && argString.length) { + showConfirm(cm, 'Substitutions should be of the form ' + + ':s/pattern/replace/'); + return; + } + } + // After the 3rd slash, we can have flags followed by a space followed + // by count. + if (trailing) { + flagsPart = trailing[0]; + count = parseInt(trailing[1]); + if (flagsPart) { + if (flagsPart.indexOf('c') != -1) { + confirm = true; + flagsPart.replace('c', ''); + } + if (flagsPart.indexOf('g') != -1) { + global = true; + flagsPart.replace('g', ''); + } + regexPart = regexPart + '/' + flagsPart; + } + } + if (regexPart) { + // If regex part is empty, then use the previous query. Otherwise use + // the regex part as the new query. + try { + updateSearchQuery(cm, regexPart, true /** ignoreCase */, + true /** smartCase */); + } catch (e) { + showConfirm(cm, 'Invalid regex: ' + regexPart); + return; + } + } + replacePart = replacePart || vimGlobalState.lastSubstituteReplacePart; + if (replacePart === undefined) { + showConfirm(cm, 'No previous substitute regular expression'); + return; + } + var state = getSearchState(cm); + var query = state.getQuery(); + var lineStart = (params.line !== undefined) ? params.line : cm.getCursor().line; + var lineEnd = params.lineEnd || lineStart; + if (lineStart == cm.firstLine() && lineEnd == cm.lastLine()) { + lineEnd = Infinity; + } + if (count) { + lineStart = lineEnd; + lineEnd = lineStart + count - 1; + } + var startPos = clipCursorToContent(cm, Pos(lineStart, 0)); + var cursor = cm.getSearchCursor(query, startPos); + doReplace(cm, confirm, global, lineStart, lineEnd, cursor, query, replacePart, params.callback); + }, + redo: CodeMirror.commands.redo, + undo: CodeMirror.commands.undo, + write: function(cm) { + if (CodeMirror.commands.save) { + // If a save command is defined, call it. + CodeMirror.commands.save(cm); + } else if (cm.save) { + // Saves to text area if no save command is defined and cm.save() is available. + cm.save(); + } + }, + nohlsearch: function(cm) { + clearSearchHighlight(cm); + }, + yank: function (cm) { + var cur = copyCursor(cm.getCursor()); + var line = cur.line; + var lineText = cm.getLine(line); + vimGlobalState.registerController.pushText( + '0', 'yank', lineText, true, true); + }, + delmarks: function(cm, params) { + if (!params.argString || !trim(params.argString)) { + showConfirm(cm, 'Argument required'); + return; + } + + var state = cm.state.vim; + var stream = new CodeMirror.StringStream(trim(params.argString)); + while (!stream.eol()) { + stream.eatSpace(); + + // Record the streams position at the beginning of the loop for use + // in error messages. + var count = stream.pos; + + if (!stream.match(/[a-zA-Z]/, false)) { + showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count)); + return; + } + + var sym = stream.next(); + // Check if this symbol is part of a range + if (stream.match('-', true)) { + // This symbol is part of a range. + + // The range must terminate at an alphabetic character. + if (!stream.match(/[a-zA-Z]/, false)) { + showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count)); + return; + } + + var startMark = sym; + var finishMark = stream.next(); + // The range must terminate at an alphabetic character which + // shares the same case as the start of the range. + if (isLowerCase(startMark) && isLowerCase(finishMark) || + isUpperCase(startMark) && isUpperCase(finishMark)) { + var start = startMark.charCodeAt(0); + var finish = finishMark.charCodeAt(0); + if (start >= finish) { + showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count)); + return; + } + + // Because marks are always ASCII values, and we have + // determined that they are the same case, we can use + // their char codes to iterate through the defined range. + for (var j = 0; j <= finish - start; j++) { + var mark = String.fromCharCode(start + j); + delete state.marks[mark]; + } + } else { + showConfirm(cm, 'Invalid argument: ' + startMark + '-'); + return; + } + } else { + // This symbol is a valid mark, and is not part of a range. + delete state.marks[sym]; + } + } + } + }; + + var exCommandDispatcher = new ExCommandDispatcher(); + + /** + * @param {CodeMirror} cm CodeMirror instance we are in. + * @param {boolean} confirm Whether to confirm each replace. + * @param {Cursor} lineStart Line to start replacing from. + * @param {Cursor} lineEnd Line to stop replacing at. + * @param {RegExp} query Query for performing matches with. + * @param {string} replaceWith Text to replace matches with. May contain $1, + * $2, etc for replacing captured groups using Javascript replace. + * @param {function()} callback A callback for when the replace is done. + */ + function doReplace(cm, confirm, global, lineStart, lineEnd, searchCursor, query, + replaceWith, callback) { + // Set up all the functions. + cm.state.vim.exMode = true; + var done = false; + var lastPos = searchCursor.from(); + function replaceAll() { + cm.operation(function() { + while (!done) { + replace(); + next(); + } + stop(); + }); + } + function replace() { + var text = cm.getRange(searchCursor.from(), searchCursor.to()); + var newText = text.replace(query, replaceWith); + searchCursor.replace(newText); + } + function next() { + // The below only loops to skip over multiple occurrences on the same + // line when 'global' is not true. + while(searchCursor.findNext() && + isInRange(searchCursor.from(), lineStart, lineEnd)) { + if (!global && lastPos && searchCursor.from().line == lastPos.line) { + continue; + } + cm.scrollIntoView(searchCursor.from(), 30); + cm.setSelection(searchCursor.from(), searchCursor.to()); + lastPos = searchCursor.from(); + done = false; + return; + } + done = true; + } + function stop(close) { + if (close) { close(); } + cm.focus(); + if (lastPos) { + cm.setCursor(lastPos); + var vim = cm.state.vim; + vim.exMode = false; + vim.lastHPos = vim.lastHSPos = lastPos.ch; + } + if (callback) { callback(); } + } + function onPromptKeyDown(e, _value, close) { + // Swallow all keys. + CodeMirror.e_stop(e); + var keyName = CodeMirror.keyName(e); + switch (keyName) { + case 'Y': + replace(); next(); break; + case 'N': + next(); break; + case 'A': + // replaceAll contains a call to close of its own. We don't want it + // to fire too early or multiple times. + var savedCallback = callback; + callback = undefined; + cm.operation(replaceAll); + callback = savedCallback; + break; + case 'L': + replace(); + // fall through and exit. + case 'Q': + case 'Esc': + case 'Ctrl-C': + case 'Ctrl-[': + stop(close); + break; + } + if (done) { stop(close); } + return true; + } + + // Actually do replace. + next(); + if (done) { + showConfirm(cm, 'No matches for ' + query.source); + return; + } + if (!confirm) { + replaceAll(); + if (callback) { callback(); }; + return; + } + showPrompt(cm, { + prefix: 'replace with <strong>' + replaceWith + '</strong> (y/n/a/q/l)', + onKeyDown: onPromptKeyDown + }); + } + + CodeMirror.keyMap.vim = { + attach: attachVimMap, + detach: detachVimMap, + call: cmKey + }; + + function exitInsertMode(cm) { + var vim = cm.state.vim; + var macroModeState = vimGlobalState.macroModeState; + var insertModeChangeRegister = vimGlobalState.registerController.getRegister('.'); + var isPlaying = macroModeState.isPlaying; + var lastChange = macroModeState.lastInsertModeChanges; + // In case of visual block, the insertModeChanges are not saved as a + // single word, so we convert them to a single word + // so as to update the ". register as expected in real vim. + var text = []; + if (!isPlaying) { + var selLength = lastChange.inVisualBlock && vim.lastSelection ? + vim.lastSelection.visualBlock.height : 1; + var changes = lastChange.changes; + var text = []; + var i = 0; + // In case of multiple selections in blockwise visual, + // the inserted text, for example: 'f<Backspace>oo', is stored as + // 'f', 'f', InsertModeKey 'o', 'o', 'o', 'o'. (if you have a block with 2 lines). + // We push the contents of the changes array as per the following: + // 1. In case of InsertModeKey, just increment by 1. + // 2. In case of a character, jump by selLength (2 in the example). + while (i < changes.length) { + // This loop will convert 'ff<bs>oooo' to 'f<bs>oo'. + text.push(changes[i]); + if (changes[i] instanceof InsertModeKey) { + i++; + } else { + i+= selLength; + } + } + lastChange.changes = text; + cm.off('change', onChange); + CodeMirror.off(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown); + } + if (!isPlaying && vim.insertModeRepeat > 1) { + // Perform insert mode repeat for commands like 3,a and 3,o. + repeatLastEdit(cm, vim, vim.insertModeRepeat - 1, + true /** repeatForInsert */); + vim.lastEditInputState.repeatOverride = vim.insertModeRepeat; + } + delete vim.insertModeRepeat; + vim.insertMode = false; + cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1); + cm.setOption('keyMap', 'vim'); + cm.setOption('disableInput', true); + cm.toggleOverwrite(false); // exit replace mode if we were in it. + // update the ". register before exiting insert mode + insertModeChangeRegister.setText(lastChange.changes.join('')); + CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"}); + if (macroModeState.isRecording) { + logInsertModeChange(macroModeState); + } + } + + function _mapCommand(command) { + defaultKeymap.unshift(command); + } + + function mapCommand(keys, type, name, args, extra) { + var command = {keys: keys, type: type}; + command[type] = name; + command[type + "Args"] = args; + for (var key in extra) + command[key] = extra[key]; + _mapCommand(command); + } + + // The timeout in milliseconds for the two-character ESC keymap should be + // adjusted according to your typing speed to prevent false positives. + defineOption('insertModeEscKeysTimeout', 200, 'number'); + + CodeMirror.keyMap['vim-insert'] = { + // TODO: override navigation keys so that Esc will cancel automatic + // indentation from o, O, i_<CR> + fallthrough: ['default'], + attach: attachVimMap, + detach: detachVimMap, + call: cmKey + }; + + CodeMirror.keyMap['vim-replace'] = { + 'Backspace': 'goCharLeft', + fallthrough: ['vim-insert'], + attach: attachVimMap, + detach: detachVimMap, + call: cmKey + }; + + function executeMacroRegister(cm, vim, macroModeState, registerName) { + var register = vimGlobalState.registerController.getRegister(registerName); + if (registerName == ':') { + // Read-only register containing last Ex command. + if (register.keyBuffer[0]) { + exCommandDispatcher.processCommand(cm, register.keyBuffer[0]); + } + macroModeState.isPlaying = false; + return; + } + var keyBuffer = register.keyBuffer; + var imc = 0; + macroModeState.isPlaying = true; + macroModeState.replaySearchQueries = register.searchQueries.slice(0); + for (var i = 0; i < keyBuffer.length; i++) { + var text = keyBuffer[i]; + var match, key; + while (text) { + // Pull off one command key, which is either a single character + // or a special sequence wrapped in '<' and '>', e.g. '<Space>'. + match = (/<\w+-.+?>|<\w+>|./).exec(text); + key = match[0]; + text = text.substring(match.index + key.length); + CodeMirror.Vim.handleKey(cm, key, 'macro'); + if (vim.insertMode) { + var changes = register.insertModeChanges[imc++].changes; + vimGlobalState.macroModeState.lastInsertModeChanges.changes = + changes; + repeatInsertModeChanges(cm, changes, 1); + exitInsertMode(cm); + } + } + }; + macroModeState.isPlaying = false; + } + + function logKey(macroModeState, key) { + if (macroModeState.isPlaying) { return; } + var registerName = macroModeState.latestRegister; + var register = vimGlobalState.registerController.getRegister(registerName); + if (register) { + register.pushText(key); + } + } + + function logInsertModeChange(macroModeState) { + if (macroModeState.isPlaying) { return; } + var registerName = macroModeState.latestRegister; + var register = vimGlobalState.registerController.getRegister(registerName); + if (register && register.pushInsertModeChanges) { + register.pushInsertModeChanges(macroModeState.lastInsertModeChanges); + } + } + + function logSearchQuery(macroModeState, query) { + if (macroModeState.isPlaying) { return; } + var registerName = macroModeState.latestRegister; + var register = vimGlobalState.registerController.getRegister(registerName); + if (register && register.pushSearchQuery) { + register.pushSearchQuery(query); + } + } + + /** + * Listens for changes made in insert mode. + * Should only be active in insert mode. + */ + function onChange(cm, changeObj) { + var macroModeState = vimGlobalState.macroModeState; + var lastChange = macroModeState.lastInsertModeChanges; + if (!macroModeState.isPlaying) { + while(changeObj) { + lastChange.expectCursorActivityForChange = true; + if (changeObj.origin == '+input' || changeObj.origin == 'paste' + || changeObj.origin === undefined /* only in testing */) { + var text = changeObj.text.join('\n'); + if (lastChange.maybeReset) { + lastChange.changes = []; + lastChange.maybeReset = false; + } + if (cm.state.overwrite && !/\n/.test(text)) { + lastChange.changes.push([text]); + } else { + lastChange.changes.push(text); + } + } + // Change objects may be chained with next. + changeObj = changeObj.next; + } + } + } + + /** + * Listens for any kind of cursor activity on CodeMirror. + */ + function onCursorActivity(cm) { + var vim = cm.state.vim; + if (vim.insertMode) { + // Tracking cursor activity in insert mode (for macro support). + var macroModeState = vimGlobalState.macroModeState; + if (macroModeState.isPlaying) { return; } + var lastChange = macroModeState.lastInsertModeChanges; + if (lastChange.expectCursorActivityForChange) { + lastChange.expectCursorActivityForChange = false; + } else { + // Cursor moved outside the context of an edit. Reset the change. + lastChange.maybeReset = true; + } + } else if (!cm.curOp.isVimOp) { + handleExternalSelection(cm, vim); + } + if (vim.visualMode) { + updateFakeCursor(cm); + } + } + function updateFakeCursor(cm) { + var vim = cm.state.vim; + var from = clipCursorToContent(cm, copyCursor(vim.sel.head)); + var to = offsetCursor(from, 0, 1); + if (vim.fakeCursor) { + vim.fakeCursor.clear(); + } + vim.fakeCursor = cm.markText(from, to, {className: 'cm-animate-fat-cursor'}); + } + function handleExternalSelection(cm, vim) { + var anchor = cm.getCursor('anchor'); + var head = cm.getCursor('head'); + // Enter or exit visual mode to match mouse selection. + if (vim.visualMode && !cm.somethingSelected()) { + exitVisualMode(cm, false); + } else if (!vim.visualMode && !vim.insertMode && cm.somethingSelected()) { + vim.visualMode = true; + vim.visualLine = false; + CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"}); + } + if (vim.visualMode) { + // Bind CodeMirror selection model to vim selection model. + // Mouse selections are considered visual characterwise. + var headOffset = !cursorIsBefore(head, anchor) ? -1 : 0; + var anchorOffset = cursorIsBefore(head, anchor) ? -1 : 0; + head = offsetCursor(head, 0, headOffset); + anchor = offsetCursor(anchor, 0, anchorOffset); + vim.sel = { + anchor: anchor, + head: head + }; + updateMark(cm, vim, '<', cursorMin(head, anchor)); + updateMark(cm, vim, '>', cursorMax(head, anchor)); + } else if (!vim.insertMode) { + // Reset lastHPos if selection was modified by something outside of vim mode e.g. by mouse. + vim.lastHPos = cm.getCursor().ch; + } + } + + /** Wrapper for special keys pressed in insert mode */ + function InsertModeKey(keyName) { + this.keyName = keyName; + } + + /** + * Handles raw key down events from the text area. + * - Should only be active in insert mode. + * - For recording deletes in insert mode. + */ + function onKeyEventTargetKeyDown(e) { + var macroModeState = vimGlobalState.macroModeState; + var lastChange = macroModeState.lastInsertModeChanges; + var keyName = CodeMirror.keyName(e); + if (!keyName) { return; } + function onKeyFound() { + if (lastChange.maybeReset) { + lastChange.changes = []; + lastChange.maybeReset = false; + } + lastChange.changes.push(new InsertModeKey(keyName)); + return true; + } + if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) { + CodeMirror.lookupKey(keyName, 'vim-insert', onKeyFound); + } + } + + /** + * Repeats the last edit, which includes exactly 1 command and at most 1 + * insert. Operator and motion commands are read from lastEditInputState, + * while action commands are read from lastEditActionCommand. + * + * If repeatForInsert is true, then the function was called by + * exitInsertMode to repeat the insert mode changes the user just made. The + * corresponding enterInsertMode call was made with a count. + */ + function repeatLastEdit(cm, vim, repeat, repeatForInsert) { + var macroModeState = vimGlobalState.macroModeState; + macroModeState.isPlaying = true; + var isAction = !!vim.lastEditActionCommand; + var cachedInputState = vim.inputState; + function repeatCommand() { + if (isAction) { + commandDispatcher.processAction(cm, vim, vim.lastEditActionCommand); + } else { + commandDispatcher.evalInput(cm, vim); + } + } + function repeatInsert(repeat) { + if (macroModeState.lastInsertModeChanges.changes.length > 0) { + // For some reason, repeat cw in desktop VIM does not repeat + // insert mode changes. Will conform to that behavior. + repeat = !vim.lastEditActionCommand ? 1 : repeat; + var changeObject = macroModeState.lastInsertModeChanges; + repeatInsertModeChanges(cm, changeObject.changes, repeat); + } + } + vim.inputState = vim.lastEditInputState; + if (isAction && vim.lastEditActionCommand.interlaceInsertRepeat) { + // o and O repeat have to be interlaced with insert repeats so that the + // insertions appear on separate lines instead of the last line. + for (var i = 0; i < repeat; i++) { + repeatCommand(); + repeatInsert(1); + } + } else { + if (!repeatForInsert) { + // Hack to get the cursor to end up at the right place. If I is + // repeated in insert mode repeat, cursor will be 1 insert + // change set left of where it should be. + repeatCommand(); + } + repeatInsert(repeat); + } + vim.inputState = cachedInputState; + if (vim.insertMode && !repeatForInsert) { + // Don't exit insert mode twice. If repeatForInsert is set, then we + // were called by an exitInsertMode call lower on the stack. + exitInsertMode(cm); + } + macroModeState.isPlaying = false; + }; + + function repeatInsertModeChanges(cm, changes, repeat) { + function keyHandler(binding) { + if (typeof binding == 'string') { + CodeMirror.commands[binding](cm); + } else { + binding(cm); + } + return true; + } + var head = cm.getCursor('head'); + var inVisualBlock = vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock; + if (inVisualBlock) { + // Set up block selection again for repeating the changes. + var vim = cm.state.vim; + var lastSel = vim.lastSelection; + var offset = getOffset(lastSel.anchor, lastSel.head); + selectForInsert(cm, head, offset.line + 1); + repeat = cm.listSelections().length; + cm.setCursor(head); + } + for (var i = 0; i < repeat; i++) { + if (inVisualBlock) { + cm.setCursor(offsetCursor(head, i, 0)); + } + for (var j = 0; j < changes.length; j++) { + var change = changes[j]; + if (change instanceof InsertModeKey) { + CodeMirror.lookupKey(change.keyName, 'vim-insert', keyHandler); + } else if (typeof change == "string") { + var cur = cm.getCursor(); + cm.replaceRange(change, cur, cur); + } else { + var start = cm.getCursor(); + var end = offsetCursor(start, 0, change[0].length); + cm.replaceRange(change[0], start, end); + } + } + } + if (inVisualBlock) { + cm.setCursor(offsetCursor(head, 0, 1)); + } + } + + resetVimGlobalState(); + return vimApi; + }; + // Initialize Vim and make it available as an API. + CodeMirror.Vim = Vim(); +}); diff --git a/modules/editor/codemirror/mode/asn.1/asn.1.min.js b/modules/editor/codemirror/mode/asn.1/asn.1.min.js @@ -0,0 +1,204 @@ +// 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("asn.1", function(config, parserConfig) { + var indentUnit = config.indentUnit, + keywords = parserConfig.keywords || {}, + cmipVerbs = parserConfig.cmipVerbs || {}, + compareTypes = parserConfig.compareTypes || {}, + status = parserConfig.status || {}, + tags = parserConfig.tags || {}, + storage = parserConfig.storage || {}, + modifier = parserConfig.modifier || {}, + accessTypes = parserConfig.accessTypes|| {}, + multiLineStrings = parserConfig.multiLineStrings, + indentStatements = parserConfig.indentStatements !== false; + var isOperatorChar = /[\|\^]/; + var curPunc; + + function tokenBase(stream, state) { + var ch = stream.next(); + if (ch == '"' || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } + if (/[\[\]\(\){}:=,;]/.test(ch)) { + curPunc = ch; + return "punctuation"; + } + if (ch == "-"){ + if (stream.eat("-")) { + stream.skipToEnd(); + return "comment"; + } + } + if (/\d/.test(ch)) { + stream.eatWhile(/[\w\.]/); + return "number"; + } + if (isOperatorChar.test(ch)) { + stream.eatWhile(isOperatorChar); + return "operator"; + } + + stream.eatWhile(/[\w\-]/); + var cur = stream.current(); + if (keywords.propertyIsEnumerable(cur)) return "keyword"; + if (cmipVerbs.propertyIsEnumerable(cur)) return "variable cmipVerbs"; + if (compareTypes.propertyIsEnumerable(cur)) return "atom compareTypes"; + if (status.propertyIsEnumerable(cur)) return "comment status"; + if (tags.propertyIsEnumerable(cur)) return "variable-3 tags"; + if (storage.propertyIsEnumerable(cur)) return "builtin storage"; + if (modifier.propertyIsEnumerable(cur)) return "string-2 modifier"; + if (accessTypes.propertyIsEnumerable(cur)) return "atom accessTypes"; + + return "variable"; + } + + function tokenString(quote) { + return function(stream, state) { + var escaped = false, next, end = false; + while ((next = stream.next()) != null) { + if (next == quote && !escaped){ + var afterNext = stream.peek(); + //look if the character if the quote is like the B in '10100010'B + if (afterNext){ + afterNext = afterNext.toLowerCase(); + if(afterNext == "b" || afterNext == "h" || afterNext == "o") + stream.next(); + } + end = true; break; + } + escaped = !escaped && next == "\\"; + } + if (end || !(escaped || multiLineStrings)) + state.tokenize = null; + return "string"; + }; + } + + function Context(indented, column, type, align, prev) { + this.indented = indented; + this.column = column; + this.type = type; + this.align = align; + this.prev = prev; + } + function pushContext(state, col, type) { + var indent = state.indented; + if (state.context && state.context.type == "statement") + indent = state.context.indented; + return state.context = new Context(indent, col, type, null, state.context); + } + function popContext(state) { + var t = state.context.type; + if (t == ")" || t == "]" || t == "}") + state.indented = state.context.indented; + return state.context = state.context.prev; + } + + //Interface + return { + startState: function(basecolumn) { + return { + tokenize: null, + context: new Context((basecolumn || 0) - indentUnit, 0, "top", false), + indented: 0, + startOfLine: true + }; + }, + + token: function(stream, state) { + var ctx = state.context; + if (stream.sol()) { + if (ctx.align == null) ctx.align = false; + state.indented = stream.indentation(); + state.startOfLine = true; + } + if (stream.eatSpace()) return null; + curPunc = null; + var style = (state.tokenize || tokenBase)(stream, state); + if (style == "comment") return style; + if (ctx.align == null) ctx.align = true; + + if ((curPunc == ";" || curPunc == ":" || curPunc == ",") + && ctx.type == "statement"){ + popContext(state); + } + else if (curPunc == "{") pushContext(state, stream.column(), "}"); + else if (curPunc == "[") pushContext(state, stream.column(), "]"); + else if (curPunc == "(") pushContext(state, stream.column(), ")"); + else if (curPunc == "}") { + while (ctx.type == "statement") ctx = popContext(state); + if (ctx.type == "}") ctx = popContext(state); + while (ctx.type == "statement") ctx = popContext(state); + } + else if (curPunc == ctx.type) popContext(state); + else if (indentStatements && (((ctx.type == "}" || ctx.type == "top") + && curPunc != ';') || (ctx.type == "statement" + && curPunc == "newstatement"))) + pushContext(state, stream.column(), "statement"); + + state.startOfLine = false; + return style; + }, + + electricChars: "{}", + lineComment: "--", + fold: "brace" + }; + }); + + function words(str) { + var obj = {}, words = str.split(" "); + for (var i = 0; i < words.length; ++i) obj[words[i]] = true; + return obj; + } + + CodeMirror.defineMIME("text/x-ttcn-asn", { + name: "asn.1", + keywords: words("DEFINITIONS OBJECTS IF DERIVED INFORMATION ACTION" + + " REPLY ANY NAMED CHARACTERIZED BEHAVIOUR REGISTERED" + + " WITH AS IDENTIFIED CONSTRAINED BY PRESENT BEGIN" + + " IMPORTS FROM UNITS SYNTAX MIN-ACCESS MAX-ACCESS" + + " MINACCESS MAXACCESS REVISION STATUS DESCRIPTION" + + " SEQUENCE SET COMPONENTS OF CHOICE DistinguishedName" + + " ENUMERATED SIZE MODULE END INDEX AUGMENTS EXTENSIBILITY" + + " IMPLIED EXPORTS"), + cmipVerbs: words("ACTIONS ADD GET NOTIFICATIONS REPLACE REMOVE"), + compareTypes: words("OPTIONAL DEFAULT MANAGED MODULE-TYPE MODULE_IDENTITY" + + " MODULE-COMPLIANCE OBJECT-TYPE OBJECT-IDENTITY" + + " OBJECT-COMPLIANCE MODE CONFIRMED CONDITIONAL" + + " SUBORDINATE SUPERIOR CLASS TRUE FALSE NULL" + + " TEXTUAL-CONVENTION"), + status: words("current deprecated mandatory obsolete"), + tags: words("APPLICATION AUTOMATIC EXPLICIT IMPLICIT PRIVATE TAGS" + + " UNIVERSAL"), + storage: words("BOOLEAN INTEGER OBJECT IDENTIFIER BIT OCTET STRING" + + " UTCTime InterfaceIndex IANAifType CMIP-Attribute" + + " REAL PACKAGE PACKAGES IpAddress PhysAddress" + + " NetworkAddress BITS BMPString TimeStamp TimeTicks" + + " TruthValue RowStatus DisplayString GeneralString" + + " GraphicString IA5String NumericString" + + " PrintableString SnmpAdminAtring TeletexString" + + " UTF8String VideotexString VisibleString StringStore" + + " ISO646String T61String UniversalString Unsigned32" + + " Integer32 Gauge Gauge32 Counter Counter32 Counter64"), + modifier: words("ATTRIBUTE ATTRIBUTES MANDATORY-GROUP MANDATORY-GROUPS" + + " GROUP GROUPS ELEMENTS EQUALITY ORDERING SUBSTRINGS" + + " DEFINED"), + accessTypes: words("not-accessible accessible-for-notify read-only" + + " read-create read-write"), + multiLineStrings: true + }); +}); diff --git a/modules/editor/codemirror/mode/cobol/cobol.min.js b/modules/editor/codemirror/mode/cobol/cobol.min.js @@ -0,0 +1,255 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +/** + * Author: Gautam Mehta + * Branched from CodeMirror's Scheme mode + */ +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode("cobol", function () { + var BUILTIN = "builtin", COMMENT = "comment", STRING = "string", + ATOM = "atom", NUMBER = "number", KEYWORD = "keyword", MODTAG = "header", + COBOLLINENUM = "def", PERIOD = "link"; + function makeKeywords(str) { + var obj = {}, words = str.split(" "); + for (var i = 0; i < words.length; ++i) obj[words[i]] = true; + return obj; + } + var atoms = makeKeywords("TRUE FALSE ZEROES ZEROS ZERO SPACES SPACE LOW-VALUE LOW-VALUES "); + var keywords = makeKeywords( + "ACCEPT ACCESS ACQUIRE ADD ADDRESS " + + "ADVANCING AFTER ALIAS ALL ALPHABET " + + "ALPHABETIC ALPHABETIC-LOWER ALPHABETIC-UPPER ALPHANUMERIC ALPHANUMERIC-EDITED " + + "ALSO ALTER ALTERNATE AND ANY " + + "ARE AREA AREAS ARITHMETIC ASCENDING " + + "ASSIGN AT ATTRIBUTE AUTHOR AUTO " + + "AUTO-SKIP AUTOMATIC B-AND B-EXOR B-LESS " + + "B-NOT B-OR BACKGROUND-COLOR BACKGROUND-COLOUR BEEP " + + "BEFORE BELL BINARY BIT BITS " + + "BLANK BLINK BLOCK BOOLEAN BOTTOM " + + "BY CALL CANCEL CD CF " + + "CH CHARACTER CHARACTERS CLASS CLOCK-UNITS " + + "CLOSE COBOL CODE CODE-SET COL " + + "COLLATING COLUMN COMMA COMMIT COMMITMENT " + + "COMMON COMMUNICATION COMP COMP-0 COMP-1 " + + "COMP-2 COMP-3 COMP-4 COMP-5 COMP-6 " + + "COMP-7 COMP-8 COMP-9 COMPUTATIONAL COMPUTATIONAL-0 " + + "COMPUTATIONAL-1 COMPUTATIONAL-2 COMPUTATIONAL-3 COMPUTATIONAL-4 COMPUTATIONAL-5 " + + "COMPUTATIONAL-6 COMPUTATIONAL-7 COMPUTATIONAL-8 COMPUTATIONAL-9 COMPUTE " + + "CONFIGURATION CONNECT CONSOLE CONTAINED CONTAINS " + + "CONTENT CONTINUE CONTROL CONTROL-AREA CONTROLS " + + "CONVERTING COPY CORR CORRESPONDING COUNT " + + "CRT CRT-UNDER CURRENCY CURRENT CURSOR " + + "DATA DATE DATE-COMPILED DATE-WRITTEN DAY " + + "DAY-OF-WEEK DB DB-ACCESS-CONTROL-KEY DB-DATA-NAME DB-EXCEPTION " + + "DB-FORMAT-NAME DB-RECORD-NAME DB-SET-NAME DB-STATUS DBCS " + + "DBCS-EDITED DE DEBUG-CONTENTS DEBUG-ITEM DEBUG-LINE " + + "DEBUG-NAME DEBUG-SUB-1 DEBUG-SUB-2 DEBUG-SUB-3 DEBUGGING " + + "DECIMAL-POINT DECLARATIVES DEFAULT DELETE DELIMITED " + + "DELIMITER DEPENDING DESCENDING DESCRIBED DESTINATION " + + "DETAIL DISABLE DISCONNECT DISPLAY DISPLAY-1 " + + "DISPLAY-2 DISPLAY-3 DISPLAY-4 DISPLAY-5 DISPLAY-6 " + + "DISPLAY-7 DISPLAY-8 DISPLAY-9 DIVIDE DIVISION " + + "DOWN DROP DUPLICATE DUPLICATES DYNAMIC " + + "EBCDIC EGI EJECT ELSE EMI " + + "EMPTY EMPTY-CHECK ENABLE END END. END-ACCEPT END-ACCEPT. " + + "END-ADD END-CALL END-COMPUTE END-DELETE END-DISPLAY " + + "END-DIVIDE END-EVALUATE END-IF END-INVOKE END-MULTIPLY " + + "END-OF-PAGE END-PERFORM END-READ END-RECEIVE END-RETURN " + + "END-REWRITE END-SEARCH END-START END-STRING END-SUBTRACT " + + "END-UNSTRING END-WRITE END-XML ENTER ENTRY " + + "ENVIRONMENT EOP EQUAL EQUALS ERASE " + + "ERROR ESI EVALUATE EVERY EXCEEDS " + + "EXCEPTION EXCLUSIVE EXIT EXTEND EXTERNAL " + + "EXTERNALLY-DESCRIBED-KEY FD FETCH FILE FILE-CONTROL " + + "FILE-STREAM FILES FILLER FINAL FIND " + + "FINISH FIRST FOOTING FOR FOREGROUND-COLOR " + + "FOREGROUND-COLOUR FORMAT FREE FROM FULL " + + "FUNCTION GENERATE GET GIVING GLOBAL " + + "GO GOBACK GREATER GROUP HEADING " + + "HIGH-VALUE HIGH-VALUES HIGHLIGHT I-O I-O-CONTROL " + + "ID IDENTIFICATION IF IN INDEX " + + "INDEX-1 INDEX-2 INDEX-3 INDEX-4 INDEX-5 " + + "INDEX-6 INDEX-7 INDEX-8 INDEX-9 INDEXED " + + "INDIC INDICATE INDICATOR INDICATORS INITIAL " + + "INITIALIZE INITIATE INPUT INPUT-OUTPUT INSPECT " + + "INSTALLATION INTO INVALID INVOKE IS " + + "JUST JUSTIFIED KANJI KEEP KEY " + + "LABEL LAST LD LEADING LEFT " + + "LEFT-JUSTIFY LENGTH LENGTH-CHECK LESS LIBRARY " + + "LIKE LIMIT LIMITS LINAGE LINAGE-COUNTER " + + "LINE LINE-COUNTER LINES LINKAGE LOCAL-STORAGE " + + "LOCALE LOCALLY LOCK " + + "MEMBER MEMORY MERGE MESSAGE METACLASS " + + "MODE MODIFIED MODIFY MODULES MOVE " + + "MULTIPLE MULTIPLY NATIONAL NATIVE NEGATIVE " + + "NEXT NO NO-ECHO NONE NOT " + + "NULL NULL-KEY-MAP NULL-MAP NULLS NUMBER " + + "NUMERIC NUMERIC-EDITED OBJECT OBJECT-COMPUTER OCCURS " + + "OF OFF OMITTED ON ONLY " + + "OPEN OPTIONAL OR ORDER ORGANIZATION " + + "OTHER OUTPUT OVERFLOW OWNER PACKED-DECIMAL " + + "PADDING PAGE PAGE-COUNTER PARSE PERFORM " + + "PF PH PIC PICTURE PLUS " + + "POINTER POSITION POSITIVE PREFIX PRESENT " + + "PRINTING PRIOR PROCEDURE PROCEDURE-POINTER PROCEDURES " + + "PROCEED PROCESS PROCESSING PROGRAM PROGRAM-ID " + + "PROMPT PROTECTED PURGE QUEUE QUOTE " + + "QUOTES RANDOM RD READ READY " + + "REALM RECEIVE RECONNECT RECORD RECORD-NAME " + + "RECORDS RECURSIVE REDEFINES REEL REFERENCE " + + "REFERENCE-MONITOR REFERENCES RELATION RELATIVE RELEASE " + + "REMAINDER REMOVAL RENAMES REPEATED REPLACE " + + "REPLACING REPORT REPORTING REPORTS REPOSITORY " + + "REQUIRED RERUN RESERVE RESET RETAINING " + + "RETRIEVAL RETURN RETURN-CODE RETURNING REVERSE-VIDEO " + + "REVERSED REWIND REWRITE RF RH " + + "RIGHT RIGHT-JUSTIFY ROLLBACK ROLLING ROUNDED " + + "RUN SAME SCREEN SD SEARCH " + + "SECTION SECURE SECURITY SEGMENT SEGMENT-LIMIT " + + "SELECT SEND SENTENCE SEPARATE SEQUENCE " + + "SEQUENTIAL SET SHARED SIGN SIZE " + + "SKIP1 SKIP2 SKIP3 SORT SORT-MERGE " + + "SORT-RETURN SOURCE SOURCE-COMPUTER SPACE-FILL " + + "SPECIAL-NAMES STANDARD STANDARD-1 STANDARD-2 " + + "START STARTING STATUS STOP STORE " + + "STRING SUB-QUEUE-1 SUB-QUEUE-2 SUB-QUEUE-3 SUB-SCHEMA " + + "SUBFILE SUBSTITUTE SUBTRACT SUM SUPPRESS " + + "SYMBOLIC SYNC SYNCHRONIZED SYSIN SYSOUT " + + "TABLE TALLYING TAPE TENANT TERMINAL " + + "TERMINATE TEST TEXT THAN THEN " + + "THROUGH THRU TIME TIMES TITLE " + + "TO TOP TRAILING TRAILING-SIGN TRANSACTION " + + "TYPE TYPEDEF UNDERLINE UNEQUAL UNIT " + + "UNSTRING UNTIL UP UPDATE UPON " + + "USAGE USAGE-MODE USE USING VALID " + + "VALIDATE VALUE VALUES VARYING VLR " + + "WAIT WHEN WHEN-COMPILED WITH WITHIN " + + "WORDS WORKING-STORAGE WRITE XML XML-CODE " + + "XML-EVENT XML-NTEXT XML-TEXT ZERO ZERO-FILL " ); + + var builtins = makeKeywords("- * ** / + < <= = > >= "); + var tests = { + digit: /\d/, + digit_or_colon: /[\d:]/, + hex: /[0-9a-f]/i, + sign: /[+-]/, + exponent: /e/i, + keyword_char: /[^\s\(\[\;\)\]]/, + symbol: /[\w*+\-]/ + }; + function isNumber(ch, stream){ + // hex + if ( ch === '0' && stream.eat(/x/i) ) { + stream.eatWhile(tests.hex); + return true; + } + // leading sign + if ( ( ch == '+' || ch == '-' ) && ( tests.digit.test(stream.peek()) ) ) { + stream.eat(tests.sign); + ch = stream.next(); + } + if ( tests.digit.test(ch) ) { + stream.eat(ch); + stream.eatWhile(tests.digit); + if ( '.' == stream.peek()) { + stream.eat('.'); + stream.eatWhile(tests.digit); + } + if ( stream.eat(tests.exponent) ) { + stream.eat(tests.sign); + stream.eatWhile(tests.digit); + } + return true; + } + return false; + } + return { + startState: function () { + return { + indentStack: null, + indentation: 0, + mode: false + }; + }, + token: function (stream, state) { + if (state.indentStack == null && stream.sol()) { + // update indentation, but only if indentStack is empty + state.indentation = 6 ; //stream.indentation(); + } + // skip spaces + if (stream.eatSpace()) { + return null; + } + var returnType = null; + switch(state.mode){ + case "string": // multi-line string parsing mode + var next = false; + while ((next = stream.next()) != null) { + if (next == "\"" || next == "\'") { + state.mode = false; + break; + } + } + returnType = STRING; // continue on in string mode + break; + default: // default parsing mode + var ch = stream.next(); + var col = stream.column(); + if (col >= 0 && col <= 5) { + returnType = COBOLLINENUM; + } else if (col >= 72 && col <= 79) { + stream.skipToEnd(); + returnType = MODTAG; + } else if (ch == "*" && col == 6) { // comment + stream.skipToEnd(); // rest of the line is a comment + returnType = COMMENT; + } else if (ch == "\"" || ch == "\'") { + state.mode = "string"; + returnType = STRING; + } else if (ch == "'" && !( tests.digit_or_colon.test(stream.peek()) )) { + returnType = ATOM; + } else if (ch == ".") { + returnType = PERIOD; + } else if (isNumber(ch,stream)){ + returnType = NUMBER; + } else { + if (stream.current().match(tests.symbol)) { + while (col < 71) { + if (stream.eat(tests.symbol) === undefined) { + break; + } else { + col++; + } + } + } + if (keywords && keywords.propertyIsEnumerable(stream.current().toUpperCase())) { + returnType = KEYWORD; + } else if (builtins && builtins.propertyIsEnumerable(stream.current().toUpperCase())) { + returnType = BUILTIN; + } else if (atoms && atoms.propertyIsEnumerable(stream.current().toUpperCase())) { + returnType = ATOM; + } else returnType = null; + } + } + return returnType; + }, + indent: function (state) { + if (state.indentStack == null) return state.indentation; + return state.indentStack.indent; + } + }; +}); + +CodeMirror.defineMIME("text/x-cobol", "cobol"); + +}); diff --git a/modules/editor/codemirror/mode/dockerfile/dockerfile.min.js b/modules/editor/codemirror/mode/dockerfile/dockerfile.min.js @@ -0,0 +1,79 @@ +// 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("../../addon/mode/simple")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror", "../../addon/mode/simple"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + // Collect all Dockerfile directives + var instructions = ["from", "maintainer", "run", "cmd", "expose", "env", + "add", "copy", "entrypoint", "volume", "user", + "workdir", "onbuild"], + instructionRegex = "(" + instructions.join('|') + ")", + instructionOnlyLine = new RegExp(instructionRegex + "\\s*$", "i"), + instructionWithArguments = new RegExp(instructionRegex + "(\\s+)", "i"); + + CodeMirror.defineSimpleMode("dockerfile", { + start: [ + // Block comment: This is a line starting with a comment + { + regex: /#.*$/, + token: "comment" + }, + // Highlight an instruction without any arguments (for convenience) + { + regex: instructionOnlyLine, + token: "variable-2" + }, + // Highlight an instruction followed by arguments + { + regex: instructionWithArguments, + token: ["variable-2", null], + next: "arguments" + }, + { + regex: /./, + token: null + } + ], + arguments: [ + { + // Line comment without instruction arguments is an error + regex: /#.*$/, + token: "error", + next: "start" + }, + { + regex: /[^#]+\\$/, + token: null + }, + { + // Match everything except for the inline comment + regex: /[^#]+/, + token: null, + next: "start" + }, + { + regex: /$/, + token: null, + next: "start" + }, + // Fail safe return to start + { + token: null, + next: "start" + } + ], + meta: { + lineComment: "#" + } + }); + + CodeMirror.defineMIME("text/x-dockerfile", "dockerfile"); +}); diff --git a/modules/editor/codemirror/mode/dylan/dylan.min.js b/modules/editor/codemirror/mode/dylan/dylan.min.js @@ -0,0 +1,352 @@ +// 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 forEach(arr, f) { + for (var i = 0; i < arr.length; i++) f(arr[i], i) +} +function some(arr, f) { + for (var i = 0; i < arr.length; i++) if (f(arr[i], i)) return true + return false +} + +CodeMirror.defineMode("dylan", function(_config) { + // Words + var words = { + // Words that introduce unnamed definitions like "define interface" + unnamedDefinition: ["interface"], + + // Words that introduce simple named definitions like "define library" + namedDefinition: ["module", "library", "macro", + "C-struct", "C-union", + "C-function", "C-callable-wrapper" + ], + + // Words that introduce type definitions like "define class". + // These are also parameterized like "define method" and are + // appended to otherParameterizedDefinitionWords + typeParameterizedDefinition: ["class", "C-subtype", "C-mapped-subtype"], + + // Words that introduce trickier definitions like "define method". + // These require special definitions to be added to startExpressions + otherParameterizedDefinition: ["method", "function", + "C-variable", "C-address" + ], + + // Words that introduce module constant definitions. + // These must also be simple definitions and are + // appended to otherSimpleDefinitionWords + constantSimpleDefinition: ["constant"], + + // Words that introduce module variable definitions. + // These must also be simple definitions and are + // appended to otherSimpleDefinitionWords + variableSimpleDefinition: ["variable"], + + // Other words that introduce simple definitions + // (without implicit bodies). + otherSimpleDefinition: ["generic", "domain", + "C-pointer-type", + "table" + ], + + // Words that begin statements with implicit bodies. + statement: ["if", "block", "begin", "method", "case", + "for", "select", "when", "unless", "until", + "while", "iterate", "profiling", "dynamic-bind" + ], + + // Patterns that act as separators in compound statements. + // This may include any general pattern that must be indented + // specially. + separator: ["finally", "exception", "cleanup", "else", + "elseif", "afterwards" + ], + + // Keywords that do not require special indentation handling, + // but which should be highlighted + other: ["above", "below", "by", "from", "handler", "in", + "instance", "let", "local", "otherwise", "slot", + "subclass", "then", "to", "keyed-by", "virtual" + ], + + // Condition signaling function calls + signalingCalls: ["signal", "error", "cerror", + "break", "check-type", "abort" + ] + }; + + words["otherDefinition"] = + words["unnamedDefinition"] + .concat(words["namedDefinition"]) + .concat(words["otherParameterizedDefinition"]); + + words["definition"] = + words["typeParameterizedDefinition"] + .concat(words["otherDefinition"]); + + words["parameterizedDefinition"] = + words["typeParameterizedDefinition"] + .concat(words["otherParameterizedDefinition"]); + + words["simpleDefinition"] = + words["constantSimpleDefinition"] + .concat(words["variableSimpleDefinition"]) + .concat(words["otherSimpleDefinition"]); + + words["keyword"] = + words["statement"] + .concat(words["separator"]) + .concat(words["other"]); + + // Patterns + var symbolPattern = "[-_a-zA-Z?!*@<>$%]+"; + var symbol = new RegExp("^" + symbolPattern); + var patterns = { + // Symbols with special syntax + symbolKeyword: symbolPattern + ":", + symbolClass: "<" + symbolPattern + ">", + symbolGlobal: "\\*" + symbolPattern + "\\*", + symbolConstant: "\\$" + symbolPattern + }; + var patternStyles = { + symbolKeyword: "atom", + symbolClass: "tag", + symbolGlobal: "variable-2", + symbolConstant: "variable-3" + }; + + // Compile all patterns to regular expressions + for (var patternName in patterns) + if (patterns.hasOwnProperty(patternName)) + patterns[patternName] = new RegExp("^" + patterns[patternName]); + + // Names beginning "with-" and "without-" are commonly + // used as statement macro + patterns["keyword"] = [/^with(?:out)?-[-_a-zA-Z?!*@<>$%]+/]; + + var styles = {}; + styles["keyword"] = "keyword"; + styles["definition"] = "def"; + styles["simpleDefinition"] = "def"; + styles["signalingCalls"] = "builtin"; + + // protected words lookup table + var wordLookup = {}; + var styleLookup = {}; + + forEach([ + "keyword", + "definition", + "simpleDefinition", + "signalingCalls" + ], function(type) { + forEach(words[type], function(word) { + wordLookup[word] = type; + styleLookup[word] = styles[type]; + }); + }); + + + function chain(stream, state, f) { + state.tokenize = f; + return f(stream, state); + } + + function tokenBase(stream, state) { + // String + var ch = stream.peek(); + if (ch == "'" || ch == '"') { + stream.next(); + return chain(stream, state, tokenString(ch, "string")); + } + // Comment + else if (ch == "/") { + stream.next(); + if (stream.eat("*")) { + return chain(stream, state, tokenComment); + } else if (stream.eat("/")) { + stream.skipToEnd(); + return "comment"; + } + stream.backUp(1); + } + // Decimal + else if (/[+\-\d\.]/.test(ch)) { + if (stream.match(/^[+-]?[0-9]*\.[0-9]*([esdx][+-]?[0-9]+)?/i) || + stream.match(/^[+-]?[0-9]+([esdx][+-]?[0-9]+)/i) || + stream.match(/^[+-]?\d+/)) { + return "number"; + } + } + // Hash + else if (ch == "#") { + stream.next(); + // Symbol with string syntax + ch = stream.peek(); + if (ch == '"') { + stream.next(); + return chain(stream, state, tokenString('"', "string")); + } + // Binary number + else if (ch == "b") { + stream.next(); + stream.eatWhile(/[01]/); + return "number"; + } + // Hex number + else if (ch == "x") { + stream.next(); + stream.eatWhile(/[\da-f]/i); + return "number"; + } + // Octal number + else if (ch == "o") { + stream.next(); + stream.eatWhile(/[0-7]/); + return "number"; + } + // Token concatenation in macros + else if (ch == '#') { + stream.next(); + return "punctuation"; + } + // Sequence literals + else if ((ch == '[') || (ch == '(')) { + stream.next(); + return "bracket"; + // Hash symbol + } else if (stream.match(/f|t|all-keys|include|key|next|rest/i)) { + return "atom"; + } else { + stream.eatWhile(/[-a-zA-Z]/); + return "error"; + } + } else if (ch == "~") { + stream.next(); + ch = stream.peek(); + if (ch == "=") { + stream.next(); + ch = stream.peek(); + if (ch == "=") { + stream.next(); + return "operator"; + } + return "operator"; + } + return "operator"; + } else if (ch == ":") { + stream.next(); + ch = stream.peek(); + if (ch == "=") { + stream.next(); + return "operator"; + } else if (ch == ":") { + stream.next(); + return "punctuation"; + } + } else if ("[](){}".indexOf(ch) != -1) { + stream.next(); + return "bracket"; + } else if (".,".indexOf(ch) != -1) { + stream.next(); + return "punctuation"; + } else if (stream.match("end")) { + return "keyword"; + } + for (var name in patterns) { + if (patterns.hasOwnProperty(name)) { + var pattern = patterns[name]; + if ((pattern instanceof Array && some(pattern, function(p) { + return stream.match(p); + })) || stream.match(pattern)) + return patternStyles[name]; + } + } + if (/[+\-*\/^=<>&|]/.test(ch)) { + stream.next(); + return "operator"; + } + if (stream.match("define")) { + return "def"; + } else { + stream.eatWhile(/[\w\-]/); + // Keyword + if (wordLookup.hasOwnProperty(stream.current())) { + return styleLookup[stream.current()]; + } else if (stream.current().match(symbol)) { + return "variable"; + } else { + stream.next(); + return "variable-2"; + } + } + } + + function tokenComment(stream, state) { + var maybeEnd = false, maybeNested = false, nestedCount = 0, ch; + while ((ch = stream.next())) { + if (ch == "/" && maybeEnd) { + if (nestedCount > 0) { + nestedCount--; + } else { + state.tokenize = tokenBase; + break; + } + } else if (ch == "*" && maybeNested) { + nestedCount++; + } + maybeEnd = (ch == "*"); + maybeNested = (ch == "/"); + } + return "comment"; + } + + function tokenString(quote, style) { + return function(stream, state) { + var escaped = false, next, end = false; + while ((next = stream.next()) != null) { + if (next == quote && !escaped) { + end = true; + break; + } + escaped = !escaped && next == "\\"; + } + if (end || !escaped) { + state.tokenize = tokenBase; + } + return style; + }; + } + + // Interface + return { + startState: function() { + return { + tokenize: tokenBase, + currentIndent: 0 + }; + }, + token: function(stream, state) { + if (stream.eatSpace()) + return null; + var style = state.tokenize(stream, state); + return style; + }, + blockCommentStart: "/*", + blockCommentEnd: "*/" + }; +}); + +CodeMirror.defineMIME("text/x-dylan", "dylan"); + +}); diff --git a/modules/editor/codemirror/mode/fcl/fcl.min.js b/modules/editor/codemirror/mode/fcl/fcl.min.js @@ -0,0 +1,173 @@ +// 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("fcl", function(config) { + var indentUnit = config.indentUnit; + + var keywords = { + "term": true, + "method": true, "accu": true, + "rule": true, "then": true, "is": true, "and": true, "or": true, + "if": true, "default": true + }; + + var start_blocks = { + "var_input": true, + "var_output": true, + "fuzzify": true, + "defuzzify": true, + "function_block": true, + "ruleblock": true + }; + + var end_blocks = { + "end_ruleblock": true, + "end_defuzzify": true, + "end_function_block": true, + "end_fuzzify": true, + "end_var": true + }; + + var atoms = { + "true": true, "false": true, "nan": true, + "real": true, "min": true, "max": true, "cog": true, "cogs": true + }; + + var isOperatorChar = /[+\-*&^%:=<>!|\/]/; + + function tokenBase(stream, state) { + var ch = stream.next(); + + if (/[\d\.]/.test(ch)) { + if (ch == ".") { + stream.match(/^[0-9]+([eE][\-+]?[0-9]+)?/); + } else if (ch == "0") { + stream.match(/^[xX][0-9a-fA-F]+/) || stream.match(/^0[0-7]+/); + } else { + stream.match(/^[0-9]*\.?[0-9]*([eE][\-+]?[0-9]+)?/); + } + return "number"; + } + + if (ch == "/" || ch == "(") { + if (stream.eat("*")) { + state.tokenize = tokenComment; + return tokenComment(stream, state); + } + if (stream.eat("/")) { + stream.skipToEnd(); + return "comment"; + } + } + if (isOperatorChar.test(ch)) { + stream.eatWhile(isOperatorChar); + return "operator"; + } + stream.eatWhile(/[\w\$_\xa1-\uffff]/); + + var cur = stream.current().toLowerCase(); + if (keywords.propertyIsEnumerable(cur) || + start_blocks.propertyIsEnumerable(cur) || + end_blocks.propertyIsEnumerable(cur)) { + return "keyword"; + } + if (atoms.propertyIsEnumerable(cur)) return "atom"; + return "variable"; + } + + + function tokenComment(stream, state) { + var maybeEnd = false, ch; + while (ch = stream.next()) { + if ((ch == "/" || ch == ")") && maybeEnd) { + state.tokenize = tokenBase; + break; + } + maybeEnd = (ch == "*"); + } + return "comment"; + } + + function Context(indented, column, type, align, prev) { + this.indented = indented; + this.column = column; + this.type = type; + this.align = align; + this.prev = prev; + } + + function pushContext(state, col, type) { + return state.context = new Context(state.indented, col, type, null, state.context); + } + + function popContext(state) { + if (!state.context.prev) return; + var t = state.context.type; + if (t == "end_block") + state.indented = state.context.indented; + return state.context = state.context.prev; + } + + // Interface + + return { + startState: function(basecolumn) { + return { + tokenize: null, + context: new Context((basecolumn || 0) - indentUnit, 0, "top", false), + indented: 0, + startOfLine: true + }; + }, + + token: function(stream, state) { + var ctx = state.context; + if (stream.sol()) { + if (ctx.align == null) ctx.align = false; + state.indented = stream.indentation(); + state.startOfLine = true; + } + if (stream.eatSpace()) return null; + + var style = (state.tokenize || tokenBase)(stream, state); + if (style == "comment") return style; + if (ctx.align == null) ctx.align = true; + + var cur = stream.current().toLowerCase(); + + if (start_blocks.propertyIsEnumerable(cur)) pushContext(state, stream.column(), "end_block"); + else if (end_blocks.propertyIsEnumerable(cur)) popContext(state); + + state.startOfLine = false; + return style; + }, + + indent: function(state, textAfter) { + if (state.tokenize != tokenBase && state.tokenize != null) return 0; + var ctx = state.context; + + var closing = end_blocks.propertyIsEnumerable(textAfter); + if (ctx.align) return ctx.column + (closing ? 0 : 1); + else return ctx.indented + (closing ? 0 : indentUnit); + }, + + electricChars: "ryk", + fold: "brace", + blockCommentStart: "(*", + blockCommentEnd: "*)", + lineComment: "//" + }; +}); + +CodeMirror.defineMIME("text/x-fcl", "fcl"); +}); diff --git a/modules/editor/codemirror/mode/http/http.min.js b/modules/editor/codemirror/mode/http/http.min.js @@ -0,0 +1,113 @@ +// 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("http", function() { + function failFirstLine(stream, state) { + stream.skipToEnd(); + state.cur = header; + return "error"; + } + + function start(stream, state) { + if (stream.match(/^HTTP\/\d\.\d/)) { + state.cur = responseStatusCode; + return "keyword"; + } else if (stream.match(/^[A-Z]+/) && /[ \t]/.test(stream.peek())) { + state.cur = requestPath; + return "keyword"; + } else { + return failFirstLine(stream, state); + } + } + + function responseStatusCode(stream, state) { + var code = stream.match(/^\d+/); + if (!code) return failFirstLine(stream, state); + + state.cur = responseStatusText; + var status = Number(code[0]); + if (status >= 100 && status < 200) { + return "positive informational"; + } else if (status >= 200 && status < 300) { + return "positive success"; + } else if (status >= 300 && status < 400) { + return "positive redirect"; + } else if (status >= 400 && status < 500) { + return "negative client-error"; + } else if (status >= 500 && status < 600) { + return "negative server-error"; + } else { + return "error"; + } + } + + function responseStatusText(stream, state) { + stream.skipToEnd(); + state.cur = header; + return null; + } + + function requestPath(stream, state) { + stream.eatWhile(/\S/); + state.cur = requestProtocol; + return "string-2"; + } + + function requestProtocol(stream, state) { + if (stream.match(/^HTTP\/\d\.\d$/)) { + state.cur = header; + return "keyword"; + } else { + return failFirstLine(stream, state); + } + } + + function header(stream) { + if (stream.sol() && !stream.eat(/[ \t]/)) { + if (stream.match(/^.*?:/)) { + return "atom"; + } else { + stream.skipToEnd(); + return "error"; + } + } else { + stream.skipToEnd(); + return "string"; + } + } + + function body(stream) { + stream.skipToEnd(); + return null; + } + + return { + token: function(stream, state) { + var cur = state.cur; + if (cur != header && cur != body && stream.eatSpace()) return null; + return cur(stream, state); + }, + + blankLine: function(state) { + state.cur = body; + }, + + startState: function() { + return {cur: start}; + } + }; +}); + +CodeMirror.defineMIME("message/http", "http"); + +}); diff --git a/modules/editor/codemirror/mode/idl/idl.min.js b/modules/editor/codemirror/mode/idl/idl.min.js @@ -0,0 +1,290 @@ +// 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 wordRegexp(words) { + return new RegExp('^((' + words.join(')|(') + '))\\b', 'i'); + }; + + var builtinArray = [ + 'a_correlate', 'abs', 'acos', 'adapt_hist_equal', 'alog', + 'alog2', 'alog10', 'amoeba', 'annotate', 'app_user_dir', + 'app_user_dir_query', 'arg_present', 'array_equal', 'array_indices', + 'arrow', 'ascii_template', 'asin', 'assoc', 'atan', + 'axis', 'axis', 'bandpass_filter', 'bandreject_filter', 'barplot', + 'bar_plot', 'beseli', 'beselj', 'beselk', 'besely', + 'beta', 'biginteger', 'bilinear', 'bin_date', 'binary_template', + 'bindgen', 'binomial', 'bit_ffs', 'bit_population', 'blas_axpy', + 'blk_con', 'boolarr', 'boolean', 'boxplot', 'box_cursor', + 'breakpoint', 'broyden', 'bubbleplot', 'butterworth', 'bytarr', + 'byte', 'byteorder', 'bytscl', 'c_correlate', 'calendar', + 'caldat', 'call_external', 'call_function', 'call_method', + 'call_procedure', 'canny', 'catch', 'cd', 'cdf', 'ceil', + 'chebyshev', 'check_math', 'chisqr_cvf', 'chisqr_pdf', 'choldc', + 'cholsol', 'cindgen', 'cir_3pnt', 'clipboard', 'close', + 'clust_wts', 'cluster', 'cluster_tree', 'cmyk_convert', 'code_coverage', + 'color_convert', 'color_exchange', 'color_quan', 'color_range_map', + 'colorbar', 'colorize_sample', 'colormap_applicable', + 'colormap_gradient', 'colormap_rotation', 'colortable', + 'comfit', 'command_line_args', 'common', 'compile_opt', 'complex', + 'complexarr', 'complexround', 'compute_mesh_normals', 'cond', 'congrid', + 'conj', 'constrained_min', 'contour', 'contour', 'convert_coord', + 'convol', 'convol_fft', 'coord2to3', 'copy_lun', 'correlate', + 'cos', 'cosh', 'cpu', 'cramer', 'createboxplotdata', + 'create_cursor', 'create_struct', 'create_view', 'crossp', 'crvlength', + 'ct_luminance', 'cti_test', 'cursor', 'curvefit', 'cv_coord', + 'cvttobm', 'cw_animate', 'cw_animate_getp', 'cw_animate_load', + 'cw_animate_run', 'cw_arcball', 'cw_bgroup', 'cw_clr_index', + 'cw_colorsel', 'cw_defroi', 'cw_field', 'cw_filesel', 'cw_form', + 'cw_fslider', 'cw_light_editor', 'cw_light_editor_get', + 'cw_light_editor_set', 'cw_orient', 'cw_palette_editor', + 'cw_palette_editor_get', 'cw_palette_editor_set', 'cw_pdmenu', + 'cw_rgbslider', 'cw_tmpl', 'cw_zoom', 'db_exists', + 'dblarr', 'dcindgen', 'dcomplex', 'dcomplexarr', 'define_key', + 'define_msgblk', 'define_msgblk_from_file', 'defroi', 'defsysv', + 'delvar', 'dendro_plot', 'dendrogram', 'deriv', 'derivsig', + 'determ', 'device', 'dfpmin', 'diag_matrix', 'dialog_dbconnect', + 'dialog_message', 'dialog_pickfile', 'dialog_printersetup', + 'dialog_printjob', 'dialog_read_image', + 'dialog_write_image', 'dictionary', 'digital_filter', 'dilate', 'dindgen', + 'dissolve', 'dist', 'distance_measure', 'dlm_load', 'dlm_register', + 'doc_library', 'double', 'draw_roi', 'edge_dog', 'efont', + 'eigenql', 'eigenvec', 'ellipse', 'elmhes', 'emboss', + 'empty', 'enable_sysrtn', 'eof', 'eos', 'erase', + 'erf', 'erfc', 'erfcx', 'erode', 'errorplot', + 'errplot', 'estimator_filter', 'execute', 'exit', 'exp', + 'expand', 'expand_path', 'expint', 'extrac', 'extract_slice', + 'f_cvf', 'f_pdf', 'factorial', 'fft', 'file_basename', + 'file_chmod', 'file_copy', 'file_delete', 'file_dirname', + 'file_expand_path', 'file_gunzip', 'file_gzip', 'file_info', + 'file_lines', 'file_link', 'file_mkdir', 'file_move', + 'file_poll_input', 'file_readlink', 'file_same', + 'file_search', 'file_tar', 'file_test', 'file_untar', 'file_unzip', + 'file_which', 'file_zip', 'filepath', 'findgen', 'finite', + 'fix', 'flick', 'float', 'floor', 'flow3', + 'fltarr', 'flush', 'format_axis_values', 'forward_function', 'free_lun', + 'fstat', 'fulstr', 'funct', 'function', 'fv_test', + 'fx_root', 'fz_roots', 'gamma', 'gamma_ct', 'gauss_cvf', + 'gauss_pdf', 'gauss_smooth', 'gauss2dfit', 'gaussfit', + 'gaussian_function', 'gaussint', 'get_drive_list', 'get_dxf_objects', + 'get_kbrd', 'get_login_info', + 'get_lun', 'get_screen_size', 'getenv', 'getwindows', 'greg2jul', + 'grib', 'grid_input', 'grid_tps', 'grid3', 'griddata', + 'gs_iter', 'h_eq_ct', 'h_eq_int', 'hanning', 'hash', + 'hdf', 'hdf5', 'heap_free', 'heap_gc', 'heap_nosave', + 'heap_refcount', 'heap_save', 'help', 'hilbert', 'hist_2d', + 'hist_equal', 'histogram', 'hls', 'hough', 'hqr', + 'hsv', 'i18n_multibytetoutf8', + 'i18n_multibytetowidechar', 'i18n_utf8tomultibyte', + 'i18n_widechartomultibyte', + 'ibeta', 'icontour', 'iconvertcoord', 'idelete', 'identity', + 'idl_base64', 'idl_container', 'idl_validname', + 'idlexbr_assistant', 'idlitsys_createtool', + 'idlunit', 'iellipse', 'igamma', 'igetcurrent', 'igetdata', + 'igetid', 'igetproperty', 'iimage', 'image', 'image_cont', + 'image_statistics', 'image_threshold', 'imaginary', 'imap', 'indgen', + 'int_2d', 'int_3d', 'int_tabulated', 'intarr', 'interpol', + 'interpolate', 'interval_volume', 'invert', 'ioctl', 'iopen', + 'ir_filter', 'iplot', 'ipolygon', 'ipolyline', 'iputdata', + 'iregister', 'ireset', 'iresolve', 'irotate', 'isa', + 'isave', 'iscale', 'isetcurrent', 'isetproperty', 'ishft', + 'isocontour', 'isosurface', 'isurface', 'itext', 'itranslate', + 'ivector', 'ivolume', 'izoom', 'journal', 'json_parse', + 'json_serialize', 'jul2greg', 'julday', 'keyword_set', 'krig2d', + 'kurtosis', 'kw_test', 'l64indgen', 'la_choldc', 'la_cholmprove', + 'la_cholsol', 'la_determ', 'la_eigenproblem', 'la_eigenql', 'la_eigenvec', + 'la_elmhes', 'la_gm_linear_model', 'la_hqr', 'la_invert', + 'la_least_square_equality', 'la_least_squares', 'la_linear_equation', + 'la_ludc', 'la_lumprove', 'la_lusol', + 'la_svd', 'la_tridc', 'la_trimprove', 'la_triql', 'la_trired', + 'la_trisol', 'label_date', 'label_region', 'ladfit', 'laguerre', + 'lambda', 'lambdap', 'lambertw', 'laplacian', 'least_squares_filter', + 'leefilt', 'legend', 'legendre', 'linbcg', 'lindgen', + 'linfit', 'linkimage', 'list', 'll_arc_distance', 'lmfit', + 'lmgr', 'lngamma', 'lnp_test', 'loadct', 'locale_get', + 'logical_and', 'logical_or', 'logical_true', 'lon64arr', 'lonarr', + 'long', 'long64', 'lsode', 'lu_complex', 'ludc', + 'lumprove', 'lusol', 'm_correlate', 'machar', 'make_array', + 'make_dll', 'make_rt', 'map', 'mapcontinents', 'mapgrid', + 'map_2points', 'map_continents', 'map_grid', 'map_image', 'map_patch', + 'map_proj_forward', 'map_proj_image', 'map_proj_info', + 'map_proj_init', 'map_proj_inverse', + 'map_set', 'matrix_multiply', 'matrix_power', 'max', 'md_test', + 'mean', 'meanabsdev', 'mean_filter', 'median', 'memory', + 'mesh_clip', 'mesh_decimate', 'mesh_issolid', + 'mesh_merge', 'mesh_numtriangles', + 'mesh_obj', 'mesh_smooth', 'mesh_surfacearea', + 'mesh_validate', 'mesh_volume', + 'message', 'min', 'min_curve_surf', 'mk_html_help', 'modifyct', + 'moment', 'morph_close', 'morph_distance', + 'morph_gradient', 'morph_hitormiss', + 'morph_open', 'morph_thin', 'morph_tophat', 'multi', 'n_elements', + 'n_params', 'n_tags', 'ncdf', 'newton', 'noise_hurl', + 'noise_pick', 'noise_scatter', 'noise_slur', 'norm', 'obj_class', + 'obj_destroy', 'obj_hasmethod', 'obj_isa', 'obj_new', 'obj_valid', + 'objarr', 'on_error', 'on_ioerror', 'online_help', 'openr', + 'openu', 'openw', 'oplot', 'oploterr', 'orderedhash', + 'p_correlate', 'parse_url', 'particle_trace', 'path_cache', 'path_sep', + 'pcomp', 'plot', 'plot3d', 'plot', 'plot_3dbox', + 'plot_field', 'ploterr', 'plots', 'polar_contour', 'polar_surface', + 'polyfill', 'polyshade', 'pnt_line', 'point_lun', 'polarplot', + 'poly', 'poly_2d', 'poly_area', 'poly_fit', 'polyfillv', + 'polygon', 'polyline', 'polywarp', 'popd', 'powell', + 'pref_commit', 'pref_get', 'pref_set', 'prewitt', 'primes', + 'print', 'printf', 'printd', 'pro', 'product', + 'profile', 'profiler', 'profiles', 'project_vol', 'ps_show_fonts', + 'psafm', 'pseudo', 'ptr_free', 'ptr_new', 'ptr_valid', + 'ptrarr', 'pushd', 'qgrid3', 'qhull', 'qromb', + 'qromo', 'qsimp', 'query_*', 'query_ascii', 'query_bmp', + 'query_csv', 'query_dicom', 'query_gif', 'query_image', 'query_jpeg', + 'query_jpeg2000', 'query_mrsid', 'query_pict', 'query_png', 'query_ppm', + 'query_srf', 'query_tiff', 'query_video', 'query_wav', 'r_correlate', + 'r_test', 'radon', 'randomn', 'randomu', 'ranks', + 'rdpix', 'read', 'readf', 'read_ascii', 'read_binary', + 'read_bmp', 'read_csv', 'read_dicom', 'read_gif', 'read_image', + 'read_interfile', 'read_jpeg', 'read_jpeg2000', 'read_mrsid', 'read_pict', + 'read_png', 'read_ppm', 'read_spr', 'read_srf', 'read_sylk', + 'read_tiff', 'read_video', 'read_wav', 'read_wave', 'read_x11_bitmap', + 'read_xwd', 'reads', 'readu', 'real_part', 'rebin', + 'recall_commands', 'recon3', 'reduce_colors', 'reform', 'region_grow', + 'register_cursor', 'regress', 'replicate', + 'replicate_inplace', 'resolve_all', + 'resolve_routine', 'restore', 'retall', 'return', 'reverse', + 'rk4', 'roberts', 'rot', 'rotate', 'round', + 'routine_filepath', 'routine_info', 'rs_test', 's_test', 'save', + 'savgol', 'scale3', 'scale3d', 'scatterplot', 'scatterplot3d', + 'scope_level', 'scope_traceback', 'scope_varfetch', + 'scope_varname', 'search2d', + 'search3d', 'sem_create', 'sem_delete', 'sem_lock', 'sem_release', + 'set_plot', 'set_shading', 'setenv', 'sfit', 'shade_surf', + 'shade_surf_irr', 'shade_volume', 'shift', 'shift_diff', 'shmdebug', + 'shmmap', 'shmunmap', 'shmvar', 'show3', 'showfont', + 'signum', 'simplex', 'sin', 'sindgen', 'sinh', + 'size', 'skewness', 'skip_lun', 'slicer3', 'slide_image', + 'smooth', 'sobel', 'socket', 'sort', 'spawn', + 'sph_4pnt', 'sph_scat', 'spher_harm', 'spl_init', 'spl_interp', + 'spline', 'spline_p', 'sprsab', 'sprsax', 'sprsin', + 'sprstp', 'sqrt', 'standardize', 'stddev', 'stop', + 'strarr', 'strcmp', 'strcompress', 'streamline', 'streamline', + 'stregex', 'stretch', 'string', 'strjoin', 'strlen', + 'strlowcase', 'strmatch', 'strmessage', 'strmid', 'strpos', + 'strput', 'strsplit', 'strtrim', 'struct_assign', 'struct_hide', + 'strupcase', 'surface', 'surface', 'surfr', 'svdc', + 'svdfit', 'svsol', 'swap_endian', 'swap_endian_inplace', 'symbol', + 'systime', 't_cvf', 't_pdf', 't3d', 'tag_names', + 'tan', 'tanh', 'tek_color', 'temporary', 'terminal_size', + 'tetra_clip', 'tetra_surface', 'tetra_volume', 'text', 'thin', + 'thread', 'threed', 'tic', 'time_test2', 'timegen', + 'timer', 'timestamp', 'timestamptovalues', 'tm_test', 'toc', + 'total', 'trace', 'transpose', 'tri_surf', 'triangulate', + 'trigrid', 'triql', 'trired', 'trisol', 'truncate_lun', + 'ts_coef', 'ts_diff', 'ts_fcast', 'ts_smooth', 'tv', + 'tvcrs', 'tvlct', 'tvrd', 'tvscl', 'typename', + 'uindgen', 'uint', 'uintarr', 'ul64indgen', 'ulindgen', + 'ulon64arr', 'ulonarr', 'ulong', 'ulong64', 'uniq', + 'unsharp_mask', 'usersym', 'value_locate', 'variance', 'vector', + 'vector_field', 'vel', 'velovect', 'vert_t3d', 'voigt', + 'volume', 'voronoi', 'voxel_proj', 'wait', 'warp_tri', + 'watershed', 'wdelete', 'wf_draw', 'where', 'widget_base', + 'widget_button', 'widget_combobox', 'widget_control', + 'widget_displaycontextmenu', 'widget_draw', + 'widget_droplist', 'widget_event', 'widget_info', + 'widget_label', 'widget_list', + 'widget_propertysheet', 'widget_slider', 'widget_tab', + 'widget_table', 'widget_text', + 'widget_tree', 'widget_tree_move', 'widget_window', + 'wiener_filter', 'window', + 'window', 'write_bmp', 'write_csv', 'write_gif', 'write_image', + 'write_jpeg', 'write_jpeg2000', 'write_nrif', 'write_pict', 'write_png', + 'write_ppm', 'write_spr', 'write_srf', 'write_sylk', 'write_tiff', + 'write_video', 'write_wav', 'write_wave', 'writeu', 'wset', + 'wshow', 'wtn', 'wv_applet', 'wv_cwt', 'wv_cw_wavelet', + 'wv_denoise', 'wv_dwt', 'wv_fn_coiflet', + 'wv_fn_daubechies', 'wv_fn_gaussian', + 'wv_fn_haar', 'wv_fn_morlet', 'wv_fn_paul', + 'wv_fn_symlet', 'wv_import_data', + 'wv_import_wavelet', 'wv_plot3d_wps', 'wv_plot_multires', + 'wv_pwt', 'wv_tool_denoise', + 'xbm_edit', 'xdisplayfile', 'xdxf', 'xfont', 'xinteranimate', + 'xloadct', 'xmanager', 'xmng_tmpl', 'xmtool', 'xobjview', + 'xobjview_rotate', 'xobjview_write_image', + 'xpalette', 'xpcolor', 'xplot3d', + 'xregistered', 'xroi', 'xsq_test', 'xsurface', 'xvaredit', + 'xvolume', 'xvolume_rotate', 'xvolume_write_image', + 'xyouts', 'zlib_compress', 'zlib_uncompress', 'zoom', 'zoom_24' + ]; + var builtins = wordRegexp(builtinArray); + + var keywordArray = [ + 'begin', 'end', 'endcase', 'endfor', + 'endwhile', 'endif', 'endrep', 'endforeach', + 'break', 'case', 'continue', 'for', + 'foreach', 'goto', 'if', 'then', 'else', + 'repeat', 'until', 'switch', 'while', + 'do', 'pro', 'function' + ]; + var keywords = wordRegexp(keywordArray); + + CodeMirror.registerHelper("hintWords", "idl", builtinArray.concat(keywordArray)); + + var identifiers = new RegExp('^[_a-z\xa1-\uffff][_a-z0-9\xa1-\uffff]*', 'i'); + + var singleOperators = /[+\-*&=<>\/@#~$]/; + var boolOperators = new RegExp('(and|or|eq|lt|le|gt|ge|ne|not)', 'i'); + + function tokenBase(stream) { + // whitespaces + if (stream.eatSpace()) return null; + + // Handle one line Comments + if (stream.match(';')) { + stream.skipToEnd(); + return 'comment'; + } + + // Handle Number Literals + if (stream.match(/^[0-9\.+-]/, false)) { + if (stream.match(/^[+-]?0x[0-9a-fA-F]+/)) + return 'number'; + if (stream.match(/^[+-]?\d*\.\d+([EeDd][+-]?\d+)?/)) + return 'number'; + if (stream.match(/^[+-]?\d+([EeDd][+-]?\d+)?/)) + return 'number'; + } + + // Handle Strings + if (stream.match(/^"([^"]|(""))*"/)) { return 'string'; } + if (stream.match(/^'([^']|(''))*'/)) { return 'string'; } + + // Handle words + if (stream.match(keywords)) { return 'keyword'; } + if (stream.match(builtins)) { return 'builtin'; } + if (stream.match(identifiers)) { return 'variable'; } + + if (stream.match(singleOperators) || stream.match(boolOperators)) { + return 'operator'; } + + // Handle non-detected items + stream.next(); + return null; + }; + + CodeMirror.defineMode('idl', function() { + return { + token: function(stream) { + return tokenBase(stream); + } + }; + }); + + CodeMirror.defineMIME('text/x-idl', 'idl'); +}); diff --git a/modules/editor/codemirror/mode/javascript/test.min.js b/modules/editor/codemirror/mode/javascript/test.min.js @@ -0,0 +1,423 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function() { + var mode = CodeMirror.getMode({indentUnit: 2}, "javascript"); + function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } + + MT("locals", + "[keyword function] [def foo]([def a], [def b]) { [keyword var] [def c] [operator =] [number 10]; [keyword return] [variable-2 a] [operator +] [variable-2 c] [operator +] [variable d]; }"); + + MT("comma-and-binop", + "[keyword function](){ [keyword var] [def x] [operator =] [number 1] [operator +] [number 2], [def y]; }"); + + MT("destructuring", + "([keyword function]([def a], [[[def b], [def c] ]]) {", + " [keyword let] {[def d], [property foo]: [def c][operator =][number 10], [def x]} [operator =] [variable foo]([variable-2 a]);", + " [[[variable-2 c], [variable y] ]] [operator =] [variable-2 c];", + "})();"); + + MT("destructure_trailing_comma", + "[keyword let] {[def a], [def b],} [operator =] [variable foo];", + "[keyword let] [def c];"); // Parser still in good state? + + MT("class_body", + "[keyword class] [def Foo] {", + " [property constructor]() {}", + " [property sayName]() {", + " [keyword return] [string-2 `foo${][variable foo][string-2 }oo`];", + " }", + "}"); + + MT("class", + "[keyword class] [def Point] [keyword extends] [variable SuperThing] {", + " [keyword get] [property prop]() { [keyword return] [number 24]; }", + " [property constructor]([def x], [def y]) {", + " [keyword super]([string 'something']);", + " [keyword this].[property x] [operator =] [variable-2 x];", + " }", + "}"); + + MT("anonymous_class_expression", + "[keyword const] [def Adder] [operator =] [keyword class] [keyword extends] [variable Arithmetic] {", + " [property add]([def a], [def b]) {}", + "};"); + + MT("named_class_expression", + "[keyword const] [def Subber] [operator =] [keyword class] [def Subtract] {", + " [property sub]([def a], [def b]) {}", + "};"); + + MT("class_async_method", + "[keyword class] [def Foo] {", + " [property sayName1]() {}", + " [keyword async] [property sayName2]() {}", + "}"); + + MT("import", + "[keyword function] [def foo]() {", + " [keyword import] [def $] [keyword from] [string 'jquery'];", + " [keyword import] { [def encrypt], [def decrypt] } [keyword from] [string 'crypto'];", + "}"); + + MT("import_trailing_comma", + "[keyword import] {[def foo], [def bar],} [keyword from] [string 'baz']") + + MT("const", + "[keyword function] [def f]() {", + " [keyword const] [[ [def a], [def b] ]] [operator =] [[ [number 1], [number 2] ]];", + "}"); + + MT("for/of", + "[keyword for]([keyword let] [def of] [keyword of] [variable something]) {}"); + + MT("generator", + "[keyword function*] [def repeat]([def n]) {", + " [keyword for]([keyword var] [def i] [operator =] [number 0]; [variable-2 i] [operator <] [variable-2 n]; [operator ++][variable-2 i])", + " [keyword yield] [variable-2 i];", + "}"); + + MT("quotedStringAddition", + "[keyword let] [def f] [operator =] [variable a] [operator +] [string 'fatarrow'] [operator +] [variable c];"); + + MT("quotedFatArrow", + "[keyword let] [def f] [operator =] [variable a] [operator +] [string '=>'] [operator +] [variable c];"); + + MT("fatArrow", + "[variable array].[property filter]([def a] [operator =>] [variable-2 a] [operator +] [number 1]);", + "[variable a];", // No longer in scope + "[keyword let] [def f] [operator =] ([[ [def a], [def b] ]], [def c]) [operator =>] [variable-2 a] [operator +] [variable-2 c];", + "[variable c];"); + + MT("spread", + "[keyword function] [def f]([def a], [meta ...][def b]) {", + " [variable something]([variable-2 a], [meta ...][variable-2 b]);", + "}"); + + MT("quasi", + "[variable re][string-2 `fofdlakj${][variable x] [operator +] ([variable re][string-2 `foo`]) [operator +] [number 1][string-2 }fdsa`] [operator +] [number 2]"); + + MT("quasi_no_function", + "[variable x] [operator =] [string-2 `fofdlakj${][variable x] [operator +] [string-2 `foo`] [operator +] [number 1][string-2 }fdsa`] [operator +] [number 2]"); + + MT("indent_statement", + "[keyword var] [def x] [operator =] [number 10]", + "[variable x] [operator +=] [variable y] [operator +]", + " [atom Infinity]", + "[keyword debugger];"); + + MT("indent_if", + "[keyword if] ([number 1])", + " [keyword break];", + "[keyword else] [keyword if] ([number 2])", + " [keyword continue];", + "[keyword else]", + " [number 10];", + "[keyword if] ([number 1]) {", + " [keyword break];", + "} [keyword else] [keyword if] ([number 2]) {", + " [keyword continue];", + "} [keyword else] {", + " [number 10];", + "}"); + + MT("indent_for", + "[keyword for] ([keyword var] [def i] [operator =] [number 0];", + " [variable i] [operator <] [number 100];", + " [variable i][operator ++])", + " [variable doSomething]([variable i]);", + "[keyword debugger];"); + + MT("indent_c_style", + "[keyword function] [def foo]()", + "{", + " [keyword debugger];", + "}"); + + MT("indent_else", + "[keyword for] (;;)", + " [keyword if] ([variable foo])", + " [keyword if] ([variable bar])", + " [number 1];", + " [keyword else]", + " [number 2];", + " [keyword else]", + " [number 3];"); + + MT("indent_funarg", + "[variable foo]([number 10000],", + " [keyword function]([def a]) {", + " [keyword debugger];", + "};"); + + MT("indent_below_if", + "[keyword for] (;;)", + " [keyword if] ([variable foo])", + " [number 1];", + "[number 2];"); + + MT("indent_semicolonless_if", + "[keyword function] [def foo]() {", + " [keyword if] ([variable x])", + " [variable foo]()", + "}") + + MT("indent_semicolonless_if_with_statement", + "[keyword function] [def foo]() {", + " [keyword if] ([variable x])", + " [variable foo]()", + " [variable bar]()", + "}") + + MT("multilinestring", + "[keyword var] [def x] [operator =] [string 'foo\\]", + "[string bar'];"); + + MT("scary_regexp", + "[string-2 /foo[[/]]bar/];"); + + MT("indent_strange_array", + "[keyword var] [def x] [operator =] [[", + " [number 1],,", + " [number 2],", + "]];", + "[number 10];"); + + MT("param_default", + "[keyword function] [def foo]([def x] [operator =] [string-2 `foo${][number 10][string-2 }bar`]) {", + " [keyword return] [variable-2 x];", + "}"); + + MT("new_target", + "[keyword function] [def F]([def target]) {", + " [keyword if] ([variable-2 target] [operator &&] [keyword new].[keyword target].[property name]) {", + " [keyword return] [keyword new]", + " .[keyword target];", + " }", + "}"); + + MT("async", + "[keyword async] [keyword function] [def foo]([def args]) { [keyword return] [atom true]; }"); + + MT("async_assignment", + "[keyword const] [def foo] [operator =] [keyword async] [keyword function] ([def args]) { [keyword return] [atom true]; };"); + + MT("async_object", + "[keyword let] [def obj] [operator =] { [property async]: [atom false] };"); + + // async be highlighet as keyword and foo as def, but it requires potentially expensive look-ahead. See #4173 + MT("async_object_function", + "[keyword let] [def obj] [operator =] { [property async] [property foo]([def args]) { [keyword return] [atom true]; } };"); + + MT("async_object_properties", + "[keyword let] [def obj] [operator =] {", + " [property prop1]: [keyword async] [keyword function] ([def args]) { [keyword return] [atom true]; },", + " [property prop2]: [keyword async] [keyword function] ([def args]) { [keyword return] [atom true]; },", + " [property prop3]: [keyword async] [keyword function] [def prop3]([def args]) { [keyword return] [atom true]; },", + "};"); + + MT("async_arrow", + "[keyword const] [def foo] [operator =] [keyword async] ([def args]) [operator =>] { [keyword return] [atom true]; };"); + + MT("async_jquery", + "[variable $].[property ajax]({", + " [property url]: [variable url],", + " [property async]: [atom true],", + " [property method]: [string 'GET']", + "});"); + + MT("async_variable", + "[keyword const] [def async] [operator =] {[property a]: [number 1]};", + "[keyword const] [def foo] [operator =] [string-2 `bar ${][variable async].[property a][string-2 }`];") + + MT("async_comment", + "[keyword async] [comment /**/] [keyword function] [def foo]([def args]) { [keyword return] [atom true]; }"); + + MT("indent_switch", + "[keyword switch] ([variable x]) {", + " [keyword default]:", + " [keyword return] [number 2]", + "}") + + MT("regexp_corner_case", + "[operator +]{} [operator /] [atom undefined];", + "[[[meta ...][string-2 /\\//] ]];", + "[keyword void] [string-2 /\\//];", + "[keyword do] [string-2 /\\//]; [keyword while] ([number 0]);", + "[keyword if] ([number 0]) {} [keyword else] [string-2 /\\//];", + "[string-2 `${][variable async][operator ++][string-2 }//`];", + "[string-2 `${]{} [operator /] [string-2 /\\//}`];") + + MT("return_eol", + "[keyword return]", + "{} [string-2 /5/]") + + var ts_mode = CodeMirror.getMode({indentUnit: 2}, "application/typescript") + function TS(name) { + test.mode(name, ts_mode, Array.prototype.slice.call(arguments, 1)) + } + + TS("typescript_extend_type", + "[keyword class] [def Foo] [keyword extends] [type Some][operator <][type Type][operator >] {}") + + TS("typescript_arrow_type", + "[keyword let] [def x]: ([variable arg]: [type Type]) [operator =>] [type ReturnType]") + + TS("typescript_class", + "[keyword class] [def Foo] {", + " [keyword public] [keyword static] [property main]() {}", + " [keyword private] [property _foo]: [type string];", + "}") + + TS("typescript_literal_types", + "[keyword import] [keyword *] [keyword as] [def Sequelize] [keyword from] [string 'sequelize'];", + "[keyword interface] [def MyAttributes] {", + " [property truthy]: [string 'true'] [operator |] [number 1] [operator |] [atom true];", + " [property falsy]: [string 'false'] [operator |] [number 0] [operator |] [atom false];", + "}", + "[keyword interface] [def MyInstance] [keyword extends] [type Sequelize].[type Instance] [operator <] [type MyAttributes] [operator >] {", + " [property rawAttributes]: [type MyAttributes];", + " [property truthy]: [string 'true'] [operator |] [number 1] [operator |] [atom true];", + " [property falsy]: [string 'false'] [operator |] [number 0] [operator |] [atom false];", + "}") + + TS("typescript_extend_operators", + "[keyword export] [keyword interface] [def UserModel] [keyword extends]", + " [type Sequelize].[type Model] [operator <] [type UserInstance], [type UserAttributes] [operator >] {", + " [property findById]: (", + " [variable userId]: [type number]", + " ) [operator =>] [type Promise] [operator <] [type Array] [operator <] { [property id], [property name] } [operator >>];", + " [property updateById]: (", + " [variable userId]: [type number],", + " [variable isActive]: [type boolean]", + " ) [operator =>] [type Promise] [operator <] [type AccountHolderNotificationPreferenceInstance] [operator >];", + " }") + + TS("typescript_interface_with_const", + "[keyword const] [def hello]: {", + " [property prop1][operator ?]: [type string];", + " [property prop2][operator ?]: [type string];", + "} [operator =] {};") + + TS("typescript_double_extend", + "[keyword export] [keyword interface] [def UserAttributes] {", + " [property id][operator ?]: [type number];", + " [property createdAt][operator ?]: [type Date];", + "}", + "[keyword export] [keyword interface] [def UserInstance] [keyword extends] [type Sequelize].[type Instance][operator <][type UserAttributes][operator >], [type UserAttributes] {", + " [property id]: [type number];", + " [property createdAt]: [type Date];", + "}"); + + TS("typescript_index_signature", + "[keyword interface] [def A] {", + " [[ [variable prop]: [type string] ]]: [type any];", + " [property prop1]: [type any];", + "}"); + + TS("typescript_generic_class", + "[keyword class] [def Foo][operator <][type T][operator >] {", + " [property bar]() {}", + " [property foo](): [type Foo] {}", + "}") + + TS("typescript_type_when_keyword", + "[keyword export] [keyword type] [type AB] [operator =] [type A] [operator |] [type B];", + "[keyword type] [type Flags] [operator =] {", + " [property p1]: [type string];", + " [property p2]: [type boolean];", + "};") + + TS("typescript_type_when_not_keyword", + "[keyword class] [def HasType] {", + " [property type]: [type string];", + " [property constructor]([def type]: [type string]) {", + " [keyword this].[property type] [operator =] [variable-2 type];", + " }", + " [property setType]({ [def type] }: { [property type]: [type string]; }) {", + " [keyword this].[property type] [operator =] [variable-2 type];", + " }", + "}") + + TS("typescript_function_generics", + "[keyword function] [def a]() {}", + "[keyword function] [def b][operator <][type IA] [keyword extends] [type object], [type IB] [keyword extends] [type object][operator >]() {}", + "[keyword function] [def c]() {}") + + TS("typescript_complex_return_type", + "[keyword function] [def A]() {", + " [keyword return] [keyword this].[property property];", + "}", + "[keyword function] [def B](): [type Promise][operator <]{ [[ [variable key]: [type string] ]]: [type any] } [operator |] [atom null][operator >] {", + " [keyword return] [keyword this].[property property];", + "}") + + TS("typescript_complex_type_casting", + "[keyword const] [def giftpay] [operator =] [variable config].[property get]([string 'giftpay']) [keyword as] { [[ [variable platformUuid]: [type string] ]]: { [property version]: [type number]; [property apiCode]: [type string]; } };") + + TS("typescript_keyof", + "[keyword function] [def x][operator <][type T] [keyword extends] [keyword keyof] [type X][operator >]([def a]: [type T]) {", + " [keyword return]") + + TS("typescript_new_typeargs", + "[keyword let] [def x] [operator =] [keyword new] [variable Map][operator <][type string], [type Date][operator >]([string-2 `foo${][variable bar][string-2 }`])") + + TS("modifiers", + "[keyword class] [def Foo] {", + " [keyword public] [keyword abstract] [property bar]() {}", + " [property constructor]([keyword readonly] [keyword private] [def x]) {}", + "}") + + TS("arrow prop", + "({[property a]: [def p] [operator =>] [variable-2 p]})") + + TS("generic in function call", + "[keyword this].[property a][operator <][type Type][operator >]([variable foo]);", + "[keyword this].[property a][operator <][variable Type][operator >][variable foo];") + + TS("type guard", + "[keyword class] [def Appler] {", + " [keyword static] [property assertApple]([def fruit]: [type Fruit]): [variable-2 fruit] [keyword is] [type Apple] {", + " [keyword if] ([operator !]([variable-2 fruit] [keyword instanceof] [variable Apple]))", + " [keyword throw] [keyword new] [variable Error]();", + " }", + "}") + + var jsonld_mode = CodeMirror.getMode( + {indentUnit: 2}, + {name: "javascript", jsonld: true} + ); + function LD(name) { + test.mode(name, jsonld_mode, Array.prototype.slice.call(arguments, 1)); + } + + LD("json_ld_keywords", + '{', + ' [meta "@context"]: {', + ' [meta "@base"]: [string "http://example.com"],', + ' [meta "@vocab"]: [string "http://xmlns.com/foaf/0.1/"],', + ' [property "likesFlavor"]: {', + ' [meta "@container"]: [meta "@list"]', + ' [meta "@reverse"]: [string "@beFavoriteOf"]', + ' },', + ' [property "nick"]: { [meta "@container"]: [meta "@set"] },', + ' [property "nick"]: { [meta "@container"]: [meta "@index"] }', + ' },', + ' [meta "@graph"]: [[ {', + ' [meta "@id"]: [string "http://dbpedia.org/resource/John_Lennon"],', + ' [property "name"]: [string "John Lennon"],', + ' [property "modified"]: {', + ' [meta "@value"]: [string "2010-05-29T14:17:39+02:00"],', + ' [meta "@type"]: [string "http://www.w3.org/2001/XMLSchema#dateTime"]', + ' }', + ' } ]]', + '}'); + + LD("json_ld_fake", + '{', + ' [property "@fake"]: [string "@fake"],', + ' [property "@contextual"]: [string "@identifier"],', + ' [property "user@domain.com"]: [string "@graphical"],', + ' [property "@ID"]: [string "@@ID"]', + '}'); +})(); diff --git a/modules/editor/codemirror/mode/mbox/mbox.min.js b/modules/editor/codemirror/mode/mbox/mbox.min.js @@ -0,0 +1,129 @@ +// 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 rfc2822 = [ + "From", "Sender", "Reply-To", "To", "Cc", "Bcc", "Message-ID", + "In-Reply-To", "References", "Resent-From", "Resent-Sender", "Resent-To", + "Resent-Cc", "Resent-Bcc", "Resent-Message-ID", "Return-Path", "Received" +]; +var rfc2822NoEmail = [ + "Date", "Subject", "Comments", "Keywords", "Resent-Date" +]; + +CodeMirror.registerHelper("hintWords", "mbox", rfc2822.concat(rfc2822NoEmail)); + +var whitespace = /^[ \t]/; +var separator = /^From /; // See RFC 4155 +var rfc2822Header = new RegExp("^(" + rfc2822.join("|") + "): "); +var rfc2822HeaderNoEmail = new RegExp("^(" + rfc2822NoEmail.join("|") + "): "); +var header = /^[^:]+:/; // Optional fields defined in RFC 2822 +var email = /^[^ ]+@[^ ]+/; +var untilEmail = /^.*?(?=[^ ]+?@[^ ]+)/; +var bracketedEmail = /^<.*?>/; +var untilBracketedEmail = /^.*?(?=<.*>)/; + +function styleForHeader(header) { + if (header === "Subject") return "header"; + return "string"; +} + +function readToken(stream, state) { + if (stream.sol()) { + // From last line + state.inSeparator = false; + if (state.inHeader && stream.match(whitespace)) { + // Header folding + return null; + } else { + state.inHeader = false; + state.header = null; + } + + if (stream.match(separator)) { + state.inHeaders = true; + state.inSeparator = true; + return "atom"; + } + + var match; + var emailPermitted = false; + if ((match = stream.match(rfc2822HeaderNoEmail)) || + (emailPermitted = true) && (match = stream.match(rfc2822Header))) { + state.inHeaders = true; + state.inHeader = true; + state.emailPermitted = emailPermitted; + state.header = match[1]; + return "atom"; + } + + // Use vim's heuristics: recognize custom headers only if the line is in a + // block of legitimate headers. + if (state.inHeaders && (match = stream.match(header))) { + state.inHeader = true; + state.emailPermitted = true; + state.header = match[1]; + return "atom"; + } + + state.inHeaders = false; + stream.skipToEnd(); + return null; + } + + if (state.inSeparator) { + if (stream.match(email)) return "link"; + if (stream.match(untilEmail)) return "atom"; + stream.skipToEnd(); + return "atom"; + } + + if (state.inHeader) { + var style = styleForHeader(state.header); + + if (state.emailPermitted) { + if (stream.match(bracketedEmail)) return style + " link"; + if (stream.match(untilBracketedEmail)) return style; + } + stream.skipToEnd(); + return style; + } + + stream.skipToEnd(); + return null; +}; + +CodeMirror.defineMode("mbox", function() { + return { + startState: function() { + return { + // Is in a mbox separator + inSeparator: false, + // Is in a mail header + inHeader: false, + // If bracketed email is permitted. Only applicable when inHeader + emailPermitted: false, + // Name of current header + header: null, + // Is in a region of mail headers + inHeaders: false + }; + }, + token: readToken, + blankLine: function(state) { + state.inHeaders = state.inSeparator = state.inHeader = false; + } + }; +}); + +CodeMirror.defineMIME("application/mbox", "mbox"); +}); diff --git a/modules/editor/codemirror/mode/mscgen/xu_test.min.js b/modules/editor/codemirror/mode/mscgen/xu_test.min.js @@ -0,0 +1,86 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function() { + var mode = CodeMirror.getMode({indentUnit: 2}, "text/x-xu"); + function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1), "xu"); } + + MT("empty chart", + "[keyword msc][bracket {]", + "[base ]", + "[bracket }]" + ); + + MT("empty chart", + "[keyword xu][bracket {]", + "[base ]", + "[bracket }]" + ); + + MT("comments", + "[comment // a single line comment]", + "[comment # another single line comment /* and */ ignored here]", + "[comment /* A multi-line comment even though it contains]", + "[comment msc keywords and \"quoted text\"*/]"); + + MT("strings", + "[string \"// a string\"]", + "[string \"a string running over]", + "[string two lines\"]", + "[string \"with \\\"escaped quote\"]" + ); + + MT("xù/ msgenny keywords classify as 'keyword'", + "[keyword watermark]", + "[keyword alt]","[keyword loop]","[keyword opt]","[keyword ref]","[keyword else]","[keyword break]","[keyword par]","[keyword seq]","[keyword assert]" + ); + + MT("xù/ msgenny constants classify as 'variable'", + "[variable auto]", + "[variable true]", "[variable false]", "[variable on]", "[variable off]" + ); + + MT("mscgen options classify as keyword", + "[keyword hscale]", "[keyword width]", "[keyword arcgradient]", "[keyword wordwraparcs]" + ); + + MT("mscgen arcs classify as keyword", + "[keyword note]","[keyword abox]","[keyword rbox]","[keyword box]", + "[keyword |||...---]", "[keyword ..--==::]", + "[keyword ->]", "[keyword <-]", "[keyword <->]", + "[keyword =>]", "[keyword <=]", "[keyword <=>]", + "[keyword =>>]", "[keyword <<=]", "[keyword <<=>>]", + "[keyword >>]", "[keyword <<]", "[keyword <<>>]", + "[keyword -x]", "[keyword x-]", "[keyword -X]", "[keyword X-]", + "[keyword :>]", "[keyword <:]", "[keyword <:>]" + ); + + MT("within an attribute list, attributes classify as attribute", + "[bracket [[][attribute label]", + "[attribute id]","[attribute url]","[attribute idurl]", + "[attribute linecolor]","[attribute linecolour]","[attribute textcolor]","[attribute textcolour]","[attribute textbgcolor]","[attribute textbgcolour]", + "[attribute arclinecolor]","[attribute arclinecolour]","[attribute arctextcolor]","[attribute arctextcolour]","[attribute arctextbgcolor]","[attribute arctextbgcolour]", + "[attribute arcskip][bracket ]]]" + ); + + MT("outside an attribute list, attributes classify as base", + "[base label]", + "[base id]","[base url]","[base idurl]", + "[base linecolor]","[base linecolour]","[base textcolor]","[base textcolour]","[base textbgcolor]","[base textbgcolour]", + "[base arclinecolor]","[base arclinecolour]","[base arctextcolor]","[base arctextcolour]","[base arctextbgcolor]","[base arctextbgcolour]", + "[base arcskip]" + ); + + MT("a typical program", + "[comment # typical xu program]", + "[keyword xu][base ][bracket {]", + "[keyword wordwraparcs][operator =][string \"true\"][base , ][keyword hscale][operator =][string \"0.8\"][base , ][keyword arcgradient][operator =][base 30, ][keyword width][operator =][variable auto][base ;]", + "[base a][bracket [[][attribute label][operator =][string \"Entity A\"][bracket ]]][base ,]", + "[base b][bracket [[][attribute label][operator =][string \"Entity B\"][bracket ]]][base ,]", + "[base c][bracket [[][attribute label][operator =][string \"Entity C\"][bracket ]]][base ;]", + "[base a ][keyword =>>][base b][bracket [[][attribute label][operator =][string \"Hello entity B\"][bracket ]]][base ;]", + "[base a ][keyword <<][base b][bracket [[][attribute label][operator =][string \"Here's an answer dude!\"][bracket ]]][base ;]", + "[base c ][keyword :>][base *][bracket [[][attribute label][operator =][string \"What about me?\"][base , ][attribute textcolor][operator =][base red][bracket ]]][base ;]", + "[bracket }]" + ); +})(); diff --git a/modules/editor/codemirror/mode/nginx/nginx.min.js b/modules/editor/codemirror/mode/nginx/nginx.min.js @@ -0,0 +1,178 @@ +// 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("nginx", function(config) { + + function words(str) { + var obj = {}, words = str.split(" "); + for (var i = 0; i < words.length; ++i) obj[words[i]] = true; + return obj; + } + + var keywords = words( + /* ngxDirectiveControl */ "break return rewrite set" + + /* ngxDirective */ " accept_mutex accept_mutex_delay access_log add_after_body add_before_body add_header addition_types aio alias allow ancient_browser ancient_browser_value auth_basic auth_basic_user_file auth_http auth_http_header auth_http_timeout autoindex autoindex_exact_size autoindex_localtime charset charset_types client_body_buffer_size client_body_in_file_only client_body_in_single_buffer client_body_temp_path client_body_timeout client_header_buffer_size client_header_timeout client_max_body_size connection_pool_size create_full_put_path daemon dav_access dav_methods debug_connection debug_points default_type degradation degrade deny devpoll_changes devpoll_events directio directio_alignment empty_gif env epoll_events error_log eventport_events expires fastcgi_bind fastcgi_buffer_size fastcgi_buffers fastcgi_busy_buffers_size fastcgi_cache fastcgi_cache_key fastcgi_cache_methods fastcgi_cache_min_uses fastcgi_cache_path fastcgi_cache_use_stale fastcgi_cache_valid fastcgi_catch_stderr fastcgi_connect_timeout fastcgi_hide_header fastcgi_ignore_client_abort fastcgi_ignore_headers fastcgi_index fastcgi_intercept_errors fastcgi_max_temp_file_size fastcgi_next_upstream fastcgi_param fastcgi_pass_header fastcgi_pass_request_body fastcgi_pass_request_headers fastcgi_read_timeout fastcgi_send_lowat fastcgi_send_timeout fastcgi_split_path_info fastcgi_store fastcgi_store_access fastcgi_temp_file_write_size fastcgi_temp_path fastcgi_upstream_fail_timeout fastcgi_upstream_max_fails flv geoip_city geoip_country google_perftools_profiles gzip gzip_buffers gzip_comp_level gzip_disable gzip_hash gzip_http_version gzip_min_length gzip_no_buffer gzip_proxied gzip_static gzip_types gzip_vary gzip_window if_modified_since ignore_invalid_headers image_filter image_filter_buffer image_filter_jpeg_quality image_filter_transparency imap_auth imap_capabilities imap_client_buffer index ip_hash keepalive_requests keepalive_timeout kqueue_changes kqueue_events large_client_header_buffers limit_conn limit_conn_log_level limit_rate limit_rate_after limit_req limit_req_log_level limit_req_zone limit_zone lingering_time lingering_timeout lock_file log_format log_not_found log_subrequest map_hash_bucket_size map_hash_max_size master_process memcached_bind memcached_buffer_size memcached_connect_timeout memcached_next_upstream memcached_read_timeout memcached_send_timeout memcached_upstream_fail_timeout memcached_upstream_max_fails merge_slashes min_delete_depth modern_browser modern_browser_value msie_padding msie_refresh multi_accept open_file_cache open_file_cache_errors open_file_cache_events open_file_cache_min_uses open_file_cache_valid open_log_file_cache output_buffers override_charset perl perl_modules perl_require perl_set pid pop3_auth pop3_capabilities port_in_redirect postpone_gzipping postpone_output protocol proxy proxy_bind proxy_buffer proxy_buffer_size proxy_buffering proxy_buffers proxy_busy_buffers_size proxy_cache proxy_cache_key proxy_cache_methods proxy_cache_min_uses proxy_cache_path proxy_cache_use_stale proxy_cache_valid proxy_connect_timeout proxy_headers_hash_bucket_size proxy_headers_hash_max_size proxy_hide_header proxy_ignore_client_abort proxy_ignore_headers proxy_intercept_errors proxy_max_temp_file_size proxy_method proxy_next_upstream proxy_pass_error_message proxy_pass_header proxy_pass_request_body proxy_pass_request_headers proxy_read_timeout proxy_redirect proxy_send_lowat proxy_send_timeout proxy_set_body proxy_set_header proxy_ssl_session_reuse proxy_store proxy_store_access proxy_temp_file_write_size proxy_temp_path proxy_timeout proxy_upstream_fail_timeout proxy_upstream_max_fails random_index read_ahead real_ip_header recursive_error_pages request_pool_size reset_timedout_connection resolver resolver_timeout rewrite_log rtsig_overflow_events rtsig_overflow_test rtsig_overflow_threshold rtsig_signo satisfy secure_link_secret send_lowat send_timeout sendfile sendfile_max_chunk server_name_in_redirect server_names_hash_bucket_size server_names_hash_max_size server_tokens set_real_ip_from smtp_auth smtp_capabilities smtp_client_buffer smtp_greeting_delay so_keepalive source_charset ssi ssi_ignore_recycled_buffers ssi_min_file_chunk ssi_silent_errors ssi_types ssi_value_length ssl ssl_certificate ssl_certificate_key ssl_ciphers ssl_client_certificate ssl_crl ssl_dhparam ssl_engine ssl_prefer_server_ciphers ssl_protocols ssl_session_cache ssl_session_timeout ssl_verify_client ssl_verify_depth starttls stub_status sub_filter sub_filter_once sub_filter_types tcp_nodelay tcp_nopush thread_stack_size timeout timer_resolution types_hash_bucket_size types_hash_max_size underscores_in_headers uninitialized_variable_warn use user userid userid_domain userid_expires userid_mark userid_name userid_p3p userid_path userid_service valid_referers variables_hash_bucket_size variables_hash_max_size worker_connections worker_cpu_affinity worker_priority worker_processes worker_rlimit_core worker_rlimit_nofile worker_rlimit_sigpending worker_threads working_directory xclient xml_entities xslt_stylesheet xslt_typesdrew@li229-23" + ); + + var keywords_block = words( + /* ngxDirectiveBlock */ "http mail events server types location upstream charset_map limit_except if geo map" + ); + + var keywords_important = words( + /* ngxDirectiveImportant */ "include root server server_name listen internal proxy_pass memcached_pass fastcgi_pass try_files" + ); + + var indentUnit = config.indentUnit, type; + function ret(style, tp) {type = tp; return style;} + + function tokenBase(stream, state) { + + + stream.eatWhile(/[\w\$_]/); + + var cur = stream.current(); + + + if (keywords.propertyIsEnumerable(cur)) { + return "keyword"; + } + else if (keywords_block.propertyIsEnumerable(cur)) { + return "variable-2"; + } + else if (keywords_important.propertyIsEnumerable(cur)) { + return "string-2"; + } + /**/ + + var ch = stream.next(); + if (ch == "@") {stream.eatWhile(/[\w\\\-]/); return ret("meta", stream.current());} + else if (ch == "/" && stream.eat("*")) { + state.tokenize = tokenCComment; + return tokenCComment(stream, state); + } + else if (ch == "<" && stream.eat("!")) { + state.tokenize = tokenSGMLComment; + return tokenSGMLComment(stream, state); + } + else if (ch == "=") ret(null, "compare"); + else if ((ch == "~" || ch == "|") && stream.eat("=")) return ret(null, "compare"); + else if (ch == "\"" || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } + else if (ch == "#") { + stream.skipToEnd(); + return ret("comment", "comment"); + } + else if (ch == "!") { + stream.match(/^\s*\w*/); + return ret("keyword", "important"); + } + else if (/\d/.test(ch)) { + stream.eatWhile(/[\w.%]/); + return ret("number", "unit"); + } + else if (/[,.+>*\/]/.test(ch)) { + return ret(null, "select-op"); + } + else if (/[;{}:\[\]]/.test(ch)) { + return ret(null, ch); + } + else { + stream.eatWhile(/[\w\\\-]/); + return ret("variable", "variable"); + } + } + + function tokenCComment(stream, state) { + var maybeEnd = false, ch; + while ((ch = stream.next()) != null) { + if (maybeEnd && ch == "/") { + state.tokenize = tokenBase; + break; + } + maybeEnd = (ch == "*"); + } + return ret("comment", "comment"); + } + + function tokenSGMLComment(stream, state) { + var dashes = 0, ch; + while ((ch = stream.next()) != null) { + if (dashes >= 2 && ch == ">") { + state.tokenize = tokenBase; + break; + } + dashes = (ch == "-") ? dashes + 1 : 0; + } + return ret("comment", "comment"); + } + + function tokenString(quote) { + return function(stream, state) { + var escaped = false, ch; + while ((ch = stream.next()) != null) { + if (ch == quote && !escaped) + break; + escaped = !escaped && ch == "\\"; + } + if (!escaped) state.tokenize = tokenBase; + return ret("string", "string"); + }; + } + + return { + startState: function(base) { + return {tokenize: tokenBase, + baseIndent: base || 0, + stack: []}; + }, + + token: function(stream, state) { + if (stream.eatSpace()) return null; + type = null; + var style = state.tokenize(stream, state); + + var context = state.stack[state.stack.length-1]; + if (type == "hash" && context == "rule") style = "atom"; + else if (style == "variable") { + if (context == "rule") style = "number"; + else if (!context || context == "@media{") style = "tag"; + } + + if (context == "rule" && /^[\{\};]$/.test(type)) + state.stack.pop(); + if (type == "{") { + if (context == "@media") state.stack[state.stack.length-1] = "@media{"; + else state.stack.push("{"); + } + else if (type == "}") state.stack.pop(); + else if (type == "@media") state.stack.push("@media"); + else if (context == "{" && type != "comment") state.stack.push("rule"); + return style; + }, + + indent: function(state, textAfter) { + var n = state.stack.length; + if (/^\}/.test(textAfter)) + n -= state.stack[state.stack.length-1] == "rule" ? 2 : 1; + return state.baseIndent + n * indentUnit; + }, + + electricChars: "}" + }; +}); + +CodeMirror.defineMIME("text/x-nginx-conf", "nginx"); + +}); diff --git a/modules/editor/codemirror/mode/oz/oz.min.js b/modules/editor/codemirror/mode/oz/oz.min.js @@ -0,0 +1,252 @@ +// 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("oz", function (conf) { + + function wordRegexp(words) { + return new RegExp("^((" + words.join(")|(") + "))\\b"); + } + + var singleOperators = /[\^@!\|<>#~\.\*\-\+\\/,=]/; + var doubleOperators = /(<-)|(:=)|(=<)|(>=)|(<=)|(<:)|(>:)|(=:)|(\\=)|(\\=:)|(!!)|(==)|(::)/; + var tripleOperators = /(:::)|(\.\.\.)|(=<:)|(>=:)/; + + var middle = ["in", "then", "else", "of", "elseof", "elsecase", "elseif", "catch", + "finally", "with", "require", "prepare", "import", "export", "define", "do"]; + var end = ["end"]; + + var atoms = wordRegexp(["true", "false", "nil", "unit"]); + var commonKeywords = wordRegexp(["andthen", "at", "attr", "declare", "feat", "from", "lex", + "mod", "div", "mode", "orelse", "parser", "prod", "prop", "scanner", "self", "syn", "token"]); + var openingKeywords = wordRegexp(["local", "proc", "fun", "case", "class", "if", "cond", "or", "dis", + "choice", "not", "thread", "try", "raise", "lock", "for", "suchthat", "meth", "functor"]); + var middleKeywords = wordRegexp(middle); + var endKeywords = wordRegexp(end); + + // Tokenizers + function tokenBase(stream, state) { + if (stream.eatSpace()) { + return null; + } + + // Brackets + if(stream.match(/[{}]/)) { + return "bracket"; + } + + // Special [] keyword + if (stream.match(/(\[])/)) { + return "keyword" + } + + // Operators + if (stream.match(tripleOperators) || stream.match(doubleOperators)) { + return "operator"; + } + + // Atoms + if(stream.match(atoms)) { + return 'atom'; + } + + // Opening keywords + var matched = stream.match(openingKeywords); + if (matched) { + if (!state.doInCurrentLine) + state.currentIndent++; + else + state.doInCurrentLine = false; + + // Special matching for signatures + if(matched[0] == "proc" || matched[0] == "fun") + state.tokenize = tokenFunProc; + else if(matched[0] == "class") + state.tokenize = tokenClass; + else if(matched[0] == "meth") + state.tokenize = tokenMeth; + + return 'keyword'; + } + + // Middle and other keywords + if (stream.match(middleKeywords) || stream.match(commonKeywords)) { + return "keyword" + } + + // End keywords + if (stream.match(endKeywords)) { + state.currentIndent--; + return 'keyword'; + } + + // Eat the next char for next comparisons + var ch = stream.next(); + + // Strings + if (ch == '"' || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } + + // Numbers + if (/[~\d]/.test(ch)) { + if (ch == "~") { + if(! /^[0-9]/.test(stream.peek())) + return null; + else if (( stream.next() == "0" && stream.match(/^[xX][0-9a-fA-F]+/)) || stream.match(/^[0-9]*(\.[0-9]+)?([eE][~+]?[0-9]+)?/)) + return "number"; + } + + if ((ch == "0" && stream.match(/^[xX][0-9a-fA-F]+/)) || stream.match(/^[0-9]*(\.[0-9]+)?([eE][~+]?[0-9]+)?/)) + return "number"; + + return null; + } + + // Comments + if (ch == "%") { + stream.skipToEnd(); + return 'comment'; + } + else if (ch == "/") { + if (stream.eat("*")) { + state.tokenize = tokenComment; + return tokenComment(stream, state); + } + } + + // Single operators + if(singleOperators.test(ch)) { + return "operator"; + } + + // If nothing match, we skip the entire alphanumerical block + stream.eatWhile(/\w/); + + return "variable"; + } + + function tokenClass(stream, state) { + if (stream.eatSpace()) { + return null; + } + stream.match(/([A-Z][A-Za-z0-9_]*)|(`.+`)/); + state.tokenize = tokenBase; + return "variable-3" + } + + function tokenMeth(stream, state) { + if (stream.eatSpace()) { + return null; + } + stream.match(/([a-zA-Z][A-Za-z0-9_]*)|(`.+`)/); + state.tokenize = tokenBase; + return "def" + } + + function tokenFunProc(stream, state) { + if (stream.eatSpace()) { + return null; + } + + if(!state.hasPassedFirstStage && stream.eat("{")) { + state.hasPassedFirstStage = true; + return "bracket"; + } + else if(state.hasPassedFirstStage) { + stream.match(/([A-Z][A-Za-z0-9_]*)|(`.+`)|\$/); + state.hasPassedFirstStage = false; + state.tokenize = tokenBase; + return "def" + } + else { + state.tokenize = tokenBase; + return null; + } + } + + function tokenComment(stream, state) { + var maybeEnd = false, ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize = tokenBase; + break; + } + maybeEnd = (ch == "*"); + } + return "comment"; + } + + function tokenString(quote) { + return function (stream, state) { + var escaped = false, next, end = false; + while ((next = stream.next()) != null) { + if (next == quote && !escaped) { + end = true; + break; + } + escaped = !escaped && next == "\\"; + } + if (end || !escaped) + state.tokenize = tokenBase; + return "string"; + }; + } + + function buildElectricInputRegEx() { + // Reindentation should occur on [] or on a match of any of + // the block closing keywords, at the end of a line. + var allClosings = middle.concat(end); + return new RegExp("[\\[\\]]|(" + allClosings.join("|") + ")$"); + } + + return { + + startState: function () { + return { + tokenize: tokenBase, + currentIndent: 0, + doInCurrentLine: false, + hasPassedFirstStage: false + }; + }, + + token: function (stream, state) { + if (stream.sol()) + state.doInCurrentLine = 0; + + return state.tokenize(stream, state); + }, + + indent: function (state, textAfter) { + var trueText = textAfter.replace(/^\s+|\s+$/g, ''); + + if (trueText.match(endKeywords) || trueText.match(middleKeywords) || trueText.match(/(\[])/)) + return conf.indentUnit * (state.currentIndent - 1); + + if (state.currentIndent < 0) + return 0; + + return state.currentIndent * conf.indentUnit; + }, + fold: "indent", + electricInput: buildElectricInputRegEx(), + lineComment: "%", + blockCommentStart: "/*", + blockCommentEnd: "*/" + }; +}); + +CodeMirror.defineMIME("text/x-oz", "oz"); + +}); diff --git a/modules/editor/codemirror/mode/pascal/pascal.min.js b/modules/editor/codemirror/mode/pascal/pascal.min.js @@ -0,0 +1,109 @@ +// 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("pascal", function() { + function words(str) { + var obj = {}, words = str.split(" "); + for (var i = 0; i < words.length; ++i) obj[words[i]] = true; + return obj; + } + var keywords = words("and array begin case const div do downto else end file for forward integer " + + "boolean char function goto if in label mod nil not of or packed procedure " + + "program record repeat set string then to type until var while with"); + var atoms = {"null": true}; + + var isOperatorChar = /[+\-*&%=<>!?|\/]/; + + function tokenBase(stream, state) { + var ch = stream.next(); + if (ch == "#" && state.startOfLine) { + stream.skipToEnd(); + return "meta"; + } + if (ch == '"' || ch == "'") { + state.tokenize = tokenString(ch); + return state.tokenize(stream, state); + } + if (ch == "(" && stream.eat("*")) { + state.tokenize = tokenComment; + return tokenComment(stream, state); + } + if (/[\[\]{}\(\),;\:\.]/.test(ch)) { + return null; + } + if (/\d/.test(ch)) { + stream.eatWhile(/[\w\.]/); + return "number"; + } + if (ch == "/") { + if (stream.eat("/")) { + stream.skipToEnd(); + return "comment"; + } + } + if (isOperatorChar.test(ch)) { + stream.eatWhile(isOperatorChar); + return "operator"; + } + stream.eatWhile(/[\w\$_]/); + var cur = stream.current(); + if (keywords.propertyIsEnumerable(cur)) return "keyword"; + if (atoms.propertyIsEnumerable(cur)) return "atom"; + return "variable"; + } + + function tokenString(quote) { + return function(stream, state) { + var escaped = false, next, end = false; + while ((next = stream.next()) != null) { + if (next == quote && !escaped) {end = true; break;} + escaped = !escaped && next == "\\"; + } + if (end || !escaped) state.tokenize = null; + return "string"; + }; + } + + function tokenComment(stream, state) { + var maybeEnd = false, ch; + while (ch = stream.next()) { + if (ch == ")" && maybeEnd) { + state.tokenize = null; + break; + } + maybeEnd = (ch == "*"); + } + return "comment"; + } + + // Interface + + return { + startState: function() { + return {tokenize: null}; + }, + + token: function(stream, state) { + if (stream.eatSpace()) return null; + var style = (state.tokenize || tokenBase)(stream, state); + if (style == "comment" || style == "meta") return style; + return style; + }, + + electricChars: "{}" + }; +}); + +CodeMirror.defineMIME("text/x-pascal", "pascal"); + +}); diff --git a/modules/editor/codemirror/mode/powershell/test.min.js b/modules/editor/codemirror/mode/powershell/test.min.js @@ -0,0 +1,74 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function() { + var mode = CodeMirror.getMode({indentUnit: 2}, "powershell"); + function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } + + function forEach(arr, f) { for (var i = 0; i < arr.length; i++) f(arr[i], i) } + + MT('comment', '[number 1][comment # A]'); + MT('comment_multiline', '[number 1][comment <#]', + '[comment ABC]', + '[comment #>][number 2]'); + + forEach([ + '0', '1234', + '12kb', '12mb', '12Gb', '12Tb', '12PB', '12L', '12D', '12lkb', '12dtb', + '1.234', '1.234e56', '1.', '1.e2', '.2', '.2e34', + '1.2MB', '1.kb', '.1dTB', '1.e1gb', '.2', '.2e34', + '0x1', '0xabcdef', '0x3tb', '0xelmb' + ], function(number) { + MT("number_" + number, "[number " + number + "]"); + }); + + MT('string_literal_escaping', "[string 'a''']"); + MT('string_literal_variable', "[string 'a $x']"); + MT('string_escaping_1', '[string "a `""]'); + MT('string_escaping_2', '[string "a """]'); + MT('string_variable_escaping', '[string "a `$x"]'); + MT('string_variable', '[string "a ][variable-2 $x][string b"]'); + MT('string_variable_spaces', '[string "a ][variable-2 ${x y}][string b"]'); + MT('string_expression', '[string "a ][punctuation $(][variable-2 $x][operator +][number 3][punctuation )][string b"]'); + MT('string_expression_nested', '[string "A][punctuation $(][string "a][punctuation $(][string "w"][punctuation )][string b"][punctuation )][string B"]'); + + MT('string_heredoc', '[string @"]', + '[string abc]', + '[string "@]'); + MT('string_heredoc_quotes', '[string @"]', + '[string abc "\']', + '[string "@]'); + MT('string_heredoc_variable', '[string @"]', + '[string a ][variable-2 $x][string b]', + '[string "@]'); + MT('string_heredoc_nested_string', '[string @"]', + '[string a][punctuation $(][string "w"][punctuation )][string b]', + '[string "@]'); + MT('string_heredoc_literal_quotes', "[string @']", + '[string abc "\']', + "[string '@]"); + + MT('array', "[punctuation @(][string 'a'][punctuation ,][string 'b'][punctuation )]"); + MT('hash', "[punctuation @{][string 'key'][operator :][string 'value'][punctuation }]"); + + MT('variable', "[variable-2 $test]"); + MT('variable_global', "[variable-2 $global:test]"); + MT('variable_spaces', "[variable-2 ${test test}]"); + MT('operator_splat', "[variable-2 @x]"); + MT('variable_builtin', "[builtin $ErrorActionPreference]"); + MT('variable_builtin_symbols', "[builtin $$]"); + + MT('operator', "[operator +]"); + MT('operator_unary', "[operator +][number 3]"); + MT('operator_long', "[operator -match]"); + + forEach([ + '(', ')', '[[', ']]', '{', '}', ',', '`', ';', '.' + ], function(punctuation) { + MT("punctuation_" + punctuation.replace(/^[\[\]]/,''), "[punctuation " + punctuation + "]"); + }); + + MT('keyword', "[keyword if]"); + + MT('call_builtin', "[builtin Get-ChildItem]"); +})(); diff --git a/modules/editor/codemirror/mode/rst/rst.min.js b/modules/editor/codemirror/mode/rst/rst.min.js @@ -0,0 +1,557 @@ +// 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("../python/python"), require("../stex/stex"), require("../../addon/mode/overlay")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror", "../python/python", "../stex/stex", "../../addon/mode/overlay"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode('rst', function (config, options) { + + var rx_strong = /^\*\*[^\*\s](?:[^\*]*[^\*\s])?\*\*/; + var rx_emphasis = /^\*[^\*\s](?:[^\*]*[^\*\s])?\*/; + var rx_literal = /^``[^`\s](?:[^`]*[^`\s])``/; + + var rx_number = /^(?:[\d]+(?:[\.,]\d+)*)/; + var rx_positive = /^(?:\s\+[\d]+(?:[\.,]\d+)*)/; + var rx_negative = /^(?:\s\-[\d]+(?:[\.,]\d+)*)/; + + var rx_uri_protocol = "[Hh][Tt][Tt][Pp][Ss]?://"; + var rx_uri_domain = "(?:[\\d\\w.-]+)\\.(?:\\w{2,6})"; + var rx_uri_path = "(?:/[\\d\\w\\#\\%\\&\\-\\.\\,\\/\\:\\=\\?\\~]+)*"; + var rx_uri = new RegExp("^" + rx_uri_protocol + rx_uri_domain + rx_uri_path); + + var overlay = { + token: function (stream) { + + if (stream.match(rx_strong) && stream.match (/\W+|$/, false)) + return 'strong'; + if (stream.match(rx_emphasis) && stream.match (/\W+|$/, false)) + return 'em'; + if (stream.match(rx_literal) && stream.match (/\W+|$/, false)) + return 'string-2'; + if (stream.match(rx_number)) + return 'number'; + if (stream.match(rx_positive)) + return 'positive'; + if (stream.match(rx_negative)) + return 'negative'; + if (stream.match(rx_uri)) + return 'link'; + + while (stream.next() != null) { + if (stream.match(rx_strong, false)) break; + if (stream.match(rx_emphasis, false)) break; + if (stream.match(rx_literal, false)) break; + if (stream.match(rx_number, false)) break; + if (stream.match(rx_positive, false)) break; + if (stream.match(rx_negative, false)) break; + if (stream.match(rx_uri, false)) break; + } + + return null; + } + }; + + var mode = CodeMirror.getMode( + config, options.backdrop || 'rst-base' + ); + + return CodeMirror.overlayMode(mode, overlay, true); // combine +}, 'python', 'stex'); + +/////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// + +CodeMirror.defineMode('rst-base', function (config) { + + /////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////// + + function format(string) { + var args = Array.prototype.slice.call(arguments, 1); + return string.replace(/{(\d+)}/g, function (match, n) { + return typeof args[n] != 'undefined' ? args[n] : match; + }); + } + + /////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////// + + var mode_python = CodeMirror.getMode(config, 'python'); + var mode_stex = CodeMirror.getMode(config, 'stex'); + + /////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////// + + var SEPA = "\\s+"; + var TAIL = "(?:\\s*|\\W|$)", + rx_TAIL = new RegExp(format('^{0}', TAIL)); + + var NAME = + "(?:[^\\W\\d_](?:[\\w!\"#$%&'()\\*\\+,\\-\\.\/:;<=>\\?]*[^\\W_])?)", + rx_NAME = new RegExp(format('^{0}', NAME)); + var NAME_WWS = + "(?:[^\\W\\d_](?:[\\w\\s!\"#$%&'()\\*\\+,\\-\\.\/:;<=>\\?]*[^\\W_])?)"; + var REF_NAME = format('(?:{0}|`{1}`)', NAME, NAME_WWS); + + var TEXT1 = "(?:[^\\s\\|](?:[^\\|]*[^\\s\\|])?)"; + var TEXT2 = "(?:[^\\`]+)", + rx_TEXT2 = new RegExp(format('^{0}', TEXT2)); + + var rx_section = new RegExp( + "^([!'#$%&\"()*+,-./:;<=>?@\\[\\\\\\]^_`{|}~])\\1{3,}\\s*$"); + var rx_explicit = new RegExp( + format('^\\.\\.{0}', SEPA)); + var rx_link = new RegExp( + format('^_{0}:{1}|^__:{1}', REF_NAME, TAIL)); + var rx_directive = new RegExp( + format('^{0}::{1}', REF_NAME, TAIL)); + var rx_substitution = new RegExp( + format('^\\|{0}\\|{1}{2}::{3}', TEXT1, SEPA, REF_NAME, TAIL)); + var rx_footnote = new RegExp( + format('^\\[(?:\\d+|#{0}?|\\*)]{1}', REF_NAME, TAIL)); + var rx_citation = new RegExp( + format('^\\[{0}\\]{1}', REF_NAME, TAIL)); + + var rx_substitution_ref = new RegExp( + format('^\\|{0}\\|', TEXT1)); + var rx_footnote_ref = new RegExp( + format('^\\[(?:\\d+|#{0}?|\\*)]_', REF_NAME)); + var rx_citation_ref = new RegExp( + format('^\\[{0}\\]_', REF_NAME)); + var rx_link_ref1 = new RegExp( + format('^{0}__?', REF_NAME)); + var rx_link_ref2 = new RegExp( + format('^`{0}`_', TEXT2)); + + var rx_role_pre = new RegExp( + format('^:{0}:`{1}`{2}', NAME, TEXT2, TAIL)); + var rx_role_suf = new RegExp( + format('^`{1}`:{0}:{2}', NAME, TEXT2, TAIL)); + var rx_role = new RegExp( + format('^:{0}:{1}', NAME, TAIL)); + + var rx_directive_name = new RegExp(format('^{0}', REF_NAME)); + var rx_directive_tail = new RegExp(format('^::{0}', TAIL)); + var rx_substitution_text = new RegExp(format('^\\|{0}\\|', TEXT1)); + var rx_substitution_sepa = new RegExp(format('^{0}', SEPA)); + var rx_substitution_name = new RegExp(format('^{0}', REF_NAME)); + var rx_substitution_tail = new RegExp(format('^::{0}', TAIL)); + var rx_link_head = new RegExp("^_"); + var rx_link_name = new RegExp(format('^{0}|_', REF_NAME)); + var rx_link_tail = new RegExp(format('^:{0}', TAIL)); + + var rx_verbatim = new RegExp('^::\\s*$'); + var rx_examples = new RegExp('^\\s+(?:>>>|In \\[\\d+\\]:)\\s'); + + /////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////// + + function to_normal(stream, state) { + var token = null; + + if (stream.sol() && stream.match(rx_examples, false)) { + change(state, to_mode, { + mode: mode_python, local: CodeMirror.startState(mode_python) + }); + } else if (stream.sol() && stream.match(rx_explicit)) { + change(state, to_explicit); + token = 'meta'; + } else if (stream.sol() && stream.match(rx_section)) { + change(state, to_normal); + token = 'header'; + } else if (phase(state) == rx_role_pre || + stream.match(rx_role_pre, false)) { + + switch (stage(state)) { + case 0: + change(state, to_normal, context(rx_role_pre, 1)); + stream.match(/^:/); + token = 'meta'; + break; + case 1: + change(state, to_normal, context(rx_role_pre, 2)); + stream.match(rx_NAME); + token = 'keyword'; + + if (stream.current().match(/^(?:math|latex)/)) { + state.tmp_stex = true; + } + break; + case 2: + change(state, to_normal, context(rx_role_pre, 3)); + stream.match(/^:`/); + token = 'meta'; + break; + case 3: + if (state.tmp_stex) { + state.tmp_stex = undefined; state.tmp = { + mode: mode_stex, local: CodeMirror.startState(mode_stex) + }; + } + + if (state.tmp) { + if (stream.peek() == '`') { + change(state, to_normal, context(rx_role_pre, 4)); + state.tmp = undefined; + break; + } + + token = state.tmp.mode.token(stream, state.tmp.local); + break; + } + + change(state, to_normal, context(rx_role_pre, 4)); + stream.match(rx_TEXT2); + token = 'string'; + break; + case 4: + change(state, to_normal, context(rx_role_pre, 5)); + stream.match(/^`/); + token = 'meta'; + break; + case 5: + change(state, to_normal, context(rx_role_pre, 6)); + stream.match(rx_TAIL); + break; + default: + change(state, to_normal); + } + } else if (phase(state) == rx_role_suf || + stream.match(rx_role_suf, false)) { + + switch (stage(state)) { + case 0: + change(state, to_normal, context(rx_role_suf, 1)); + stream.match(/^`/); + token = 'meta'; + break; + case 1: + change(state, to_normal, context(rx_role_suf, 2)); + stream.match(rx_TEXT2); + token = 'string'; + break; + case 2: + change(state, to_normal, context(rx_role_suf, 3)); + stream.match(/^`:/); + token = 'meta'; + break; + case 3: + change(state, to_normal, context(rx_role_suf, 4)); + stream.match(rx_NAME); + token = 'keyword'; + break; + case 4: + change(state, to_normal, context(rx_role_suf, 5)); + stream.match(/^:/); + token = 'meta'; + break; + case 5: + change(state, to_normal, context(rx_role_suf, 6)); + stream.match(rx_TAIL); + break; + default: + change(state, to_normal); + } + } else if (phase(state) == rx_role || stream.match(rx_role, false)) { + + switch (stage(state)) { + case 0: + change(state, to_normal, context(rx_role, 1)); + stream.match(/^:/); + token = 'meta'; + break; + case 1: + change(state, to_normal, context(rx_role, 2)); + stream.match(rx_NAME); + token = 'keyword'; + break; + case 2: + change(state, to_normal, context(rx_role, 3)); + stream.match(/^:/); + token = 'meta'; + break; + case 3: + change(state, to_normal, context(rx_role, 4)); + stream.match(rx_TAIL); + break; + default: + change(state, to_normal); + } + } else if (phase(state) == rx_substitution_ref || + stream.match(rx_substitution_ref, false)) { + + switch (stage(state)) { + case 0: + change(state, to_normal, context(rx_substitution_ref, 1)); + stream.match(rx_substitution_text); + token = 'variable-2'; + break; + case 1: + change(state, to_normal, context(rx_substitution_ref, 2)); + if (stream.match(/^_?_?/)) token = 'link'; + break; + default: + change(state, to_normal); + } + } else if (stream.match(rx_footnote_ref)) { + change(state, to_normal); + token = 'quote'; + } else if (stream.match(rx_citation_ref)) { + change(state, to_normal); + token = 'quote'; + } else if (stream.match(rx_link_ref1)) { + change(state, to_normal); + if (!stream.peek() || stream.peek().match(/^\W$/)) { + token = 'link'; + } + } else if (phase(state) == rx_link_ref2 || + stream.match(rx_link_ref2, false)) { + + switch (stage(state)) { + case 0: + if (!stream.peek() || stream.peek().match(/^\W$/)) { + change(state, to_normal, context(rx_link_ref2, 1)); + } else { + stream.match(rx_link_ref2); + } + break; + case 1: + change(state, to_normal, context(rx_link_ref2, 2)); + stream.match(/^`/); + token = 'link'; + break; + case 2: + change(state, to_normal, context(rx_link_ref2, 3)); + stream.match(rx_TEXT2); + break; + case 3: + change(state, to_normal, context(rx_link_ref2, 4)); + stream.match(/^`_/); + token = 'link'; + break; + default: + change(state, to_normal); + } + } else if (stream.match(rx_verbatim)) { + change(state, to_verbatim); + } + + else { + if (stream.next()) change(state, to_normal); + } + + return token; + } + + /////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////// + + function to_explicit(stream, state) { + var token = null; + + if (phase(state) == rx_substitution || + stream.match(rx_substitution, false)) { + + switch (stage(state)) { + case 0: + change(state, to_explicit, context(rx_substitution, 1)); + stream.match(rx_substitution_text); + token = 'variable-2'; + break; + case 1: + change(state, to_explicit, context(rx_substitution, 2)); + stream.match(rx_substitution_sepa); + break; + case 2: + change(state, to_explicit, context(rx_substitution, 3)); + stream.match(rx_substitution_name); + token = 'keyword'; + break; + case 3: + change(state, to_explicit, context(rx_substitution, 4)); + stream.match(rx_substitution_tail); + token = 'meta'; + break; + default: + change(state, to_normal); + } + } else if (phase(state) == rx_directive || + stream.match(rx_directive, false)) { + + switch (stage(state)) { + case 0: + change(state, to_explicit, context(rx_directive, 1)); + stream.match(rx_directive_name); + token = 'keyword'; + + if (stream.current().match(/^(?:math|latex)/)) + state.tmp_stex = true; + else if (stream.current().match(/^python/)) + state.tmp_py = true; + break; + case 1: + change(state, to_explicit, context(rx_directive, 2)); + stream.match(rx_directive_tail); + token = 'meta'; + + if (stream.match(/^latex\s*$/) || state.tmp_stex) { + state.tmp_stex = undefined; change(state, to_mode, { + mode: mode_stex, local: CodeMirror.startState(mode_stex) + }); + } + break; + case 2: + change(state, to_explicit, context(rx_directive, 3)); + if (stream.match(/^python\s*$/) || state.tmp_py) { + state.tmp_py = undefined; change(state, to_mode, { + mode: mode_python, local: CodeMirror.startState(mode_python) + }); + } + break; + default: + change(state, to_normal); + } + } else if (phase(state) == rx_link || stream.match(rx_link, false)) { + + switch (stage(state)) { + case 0: + change(state, to_explicit, context(rx_link, 1)); + stream.match(rx_link_head); + stream.match(rx_link_name); + token = 'link'; + break; + case 1: + change(state, to_explicit, context(rx_link, 2)); + stream.match(rx_link_tail); + token = 'meta'; + break; + default: + change(state, to_normal); + } + } else if (stream.match(rx_footnote)) { + change(state, to_normal); + token = 'quote'; + } else if (stream.match(rx_citation)) { + change(state, to_normal); + token = 'quote'; + } + + else { + stream.eatSpace(); + if (stream.eol()) { + change(state, to_normal); + } else { + stream.skipToEnd(); + change(state, to_comment); + token = 'comment'; + } + } + + return token; + } + + /////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////// + + function to_comment(stream, state) { + return as_block(stream, state, 'comment'); + } + + function to_verbatim(stream, state) { + return as_block(stream, state, 'meta'); + } + + function as_block(stream, state, token) { + if (stream.eol() || stream.eatSpace()) { + stream.skipToEnd(); + return token; + } else { + change(state, to_normal); + return null; + } + } + + /////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////// + + function to_mode(stream, state) { + + if (state.ctx.mode && state.ctx.local) { + + if (stream.sol()) { + if (!stream.eatSpace()) change(state, to_normal); + return null; + } + + return state.ctx.mode.token(stream, state.ctx.local); + } + + change(state, to_normal); + return null; + } + + /////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////// + + function context(phase, stage, mode, local) { + return {phase: phase, stage: stage, mode: mode, local: local}; + } + + function change(state, tok, ctx) { + state.tok = tok; + state.ctx = ctx || {}; + } + + function stage(state) { + return state.ctx.stage || 0; + } + + function phase(state) { + return state.ctx.phase; + } + + /////////////////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////////////////// + + return { + startState: function () { + return {tok: to_normal, ctx: context(undefined, 0)}; + }, + + copyState: function (state) { + var ctx = state.ctx, tmp = state.tmp; + if (ctx.local) + ctx = {mode: ctx.mode, local: CodeMirror.copyState(ctx.mode, ctx.local)}; + if (tmp) + tmp = {mode: tmp.mode, local: CodeMirror.copyState(tmp.mode, tmp.local)}; + return {tok: state.tok, ctx: ctx, tmp: tmp}; + }, + + innerMode: function (state) { + return state.tmp ? {state: state.tmp.local, mode: state.tmp.mode} + : state.ctx.mode ? {state: state.ctx.local, mode: state.ctx.mode} + : null; + }, + + token: function (stream, state) { + return state.tok(stream, state); + } + }; +}, 'python', 'stex'); + +/////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// + +CodeMirror.defineMIME('text/x-rst', 'rst'); + +/////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// + +}); diff --git a/modules/editor/codemirror/mode/spreadsheet/spreadsheet.min.js b/modules/editor/codemirror/mode/spreadsheet/spreadsheet.min.js @@ -0,0 +1,112 @@ +// 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("spreadsheet", function () { + return { + startState: function () { + return { + stringType: null, + stack: [] + }; + }, + token: function (stream, state) { + if (!stream) return; + + //check for state changes + if (state.stack.length === 0) { + //strings + if ((stream.peek() == '"') || (stream.peek() == "'")) { + state.stringType = stream.peek(); + stream.next(); // Skip quote + state.stack.unshift("string"); + } + } + + //return state + //stack has + switch (state.stack[0]) { + case "string": + while (state.stack[0] === "string" && !stream.eol()) { + if (stream.peek() === state.stringType) { + stream.next(); // Skip quote + state.stack.shift(); // Clear flag + } else if (stream.peek() === "\\") { + stream.next(); + stream.next(); + } else { + stream.match(/^.[^\\\"\']*/); + } + } + return "string"; + + case "characterClass": + while (state.stack[0] === "characterClass" && !stream.eol()) { + if (!(stream.match(/^[^\]\\]+/) || stream.match(/^\\./))) + state.stack.shift(); + } + return "operator"; + } + + var peek = stream.peek(); + + //no stack + switch (peek) { + case "[": + stream.next(); + state.stack.unshift("characterClass"); + return "bracket"; + case ":": + stream.next(); + return "operator"; + case "\\": + if (stream.match(/\\[a-z]+/)) return "string-2"; + else { + stream.next(); + return "atom"; + } + case ".": + case ",": + case ";": + case "*": + case "-": + case "+": + case "^": + case "<": + case "/": + case "=": + stream.next(); + return "atom"; + case "$": + stream.next(); + return "builtin"; + } + + if (stream.match(/\d+/)) { + if (stream.match(/^\w+/)) return "error"; + return "number"; + } else if (stream.match(/^[a-zA-Z_]\w*/)) { + if (stream.match(/(?=[\(.])/, false)) return "keyword"; + return "variable-2"; + } else if (["[", "]", "(", ")", "{", "}"].indexOf(peek) != -1) { + stream.next(); + return "bracket"; + } else if (!stream.eatSpace()) { + stream.next(); + } + return null; + } + }; + }); + + CodeMirror.defineMIME("text/x-spreadsheet", "spreadsheet"); +}); diff --git a/modules/editor/codemirror/mode/tcl/tcl.min.js b/modules/editor/codemirror/mode/tcl/tcl.min.js @@ -0,0 +1,139 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +//tcl mode by Ford_Lawnmower :: Based on Velocity mode by Steve O'Hara + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { +"use strict"; + +CodeMirror.defineMode("tcl", function() { + function parseWords(str) { + var obj = {}, words = str.split(" "); + for (var i = 0; i < words.length; ++i) obj[words[i]] = true; + return obj; + } + var keywords = parseWords("Tcl safe after append array auto_execok auto_import auto_load " + + "auto_mkindex auto_mkindex_old auto_qualify auto_reset bgerror " + + "binary break catch cd close concat continue dde eof encoding error " + + "eval exec exit expr fblocked fconfigure fcopy file fileevent filename " + + "filename flush for foreach format gets glob global history http if " + + "incr info interp join lappend lindex linsert list llength load lrange " + + "lreplace lsearch lset lsort memory msgcat namespace open package parray " + + "pid pkg::create pkg_mkIndex proc puts pwd re_syntax read regex regexp " + + "registry regsub rename resource return scan seek set socket source split " + + "string subst switch tcl_endOfWord tcl_findLibrary tcl_startOfNextWord " + + "tcl_wordBreakAfter tcl_startOfPreviousWord tcl_wordBreakBefore tcltest " + + "tclvars tell time trace unknown unset update uplevel upvar variable " + + "vwait"); + var functions = parseWords("if elseif else and not or eq ne in ni for foreach while switch"); + var isOperatorChar = /[+\-*&%=<>!?^\/\|]/; + function chain(stream, state, f) { + state.tokenize = f; + return f(stream, state); + } + function tokenBase(stream, state) { + var beforeParams = state.beforeParams; + state.beforeParams = false; + var ch = stream.next(); + if ((ch == '"' || ch == "'") && state.inParams) { + return chain(stream, state, tokenString(ch)); + } else if (/[\[\]{}\(\),;\.]/.test(ch)) { + if (ch == "(" && beforeParams) state.inParams = true; + else if (ch == ")") state.inParams = false; + return null; + } else if (/\d/.test(ch)) { + stream.eatWhile(/[\w\.]/); + return "number"; + } else if (ch == "#") { + if (stream.eat("*")) + return chain(stream, state, tokenComment); + if (ch == "#" && stream.match(/ *\[ *\[/)) + return chain(stream, state, tokenUnparsed); + stream.skipToEnd(); + return "comment"; + } else if (ch == '"') { + stream.skipTo(/"/); + return "comment"; + } else if (ch == "$") { + stream.eatWhile(/[$_a-z0-9A-Z\.{:]/); + stream.eatWhile(/}/); + state.beforeParams = true; + return "builtin"; + } else if (isOperatorChar.test(ch)) { + stream.eatWhile(isOperatorChar); + return "comment"; + } else { + stream.eatWhile(/[\w\$_{}\xa1-\uffff]/); + var word = stream.current().toLowerCase(); + if (keywords && keywords.propertyIsEnumerable(word)) + return "keyword"; + if (functions && functions.propertyIsEnumerable(word)) { + state.beforeParams = true; + return "keyword"; + } + return null; + } + } + function tokenString(quote) { + return function(stream, state) { + var escaped = false, next, end = false; + while ((next = stream.next()) != null) { + if (next == quote && !escaped) { + end = true; + break; + } + escaped = !escaped && next == "\\"; + } + if (end) state.tokenize = tokenBase; + return "string"; + }; + } + function tokenComment(stream, state) { + var maybeEnd = false, ch; + while (ch = stream.next()) { + if (ch == "#" && maybeEnd) { + state.tokenize = tokenBase; + break; + } + maybeEnd = (ch == "*"); + } + return "comment"; + } + function tokenUnparsed(stream, state) { + var maybeEnd = 0, ch; + while (ch = stream.next()) { + if (ch == "#" && maybeEnd == 2) { + state.tokenize = tokenBase; + break; + } + if (ch == "]") + maybeEnd++; + else if (ch != " ") + maybeEnd = 0; + } + return "meta"; + } + return { + startState: function() { + return { + tokenize: tokenBase, + beforeParams: false, + inParams: false + }; + }, + token: function(stream, state) { + if (stream.eatSpace()) return null; + return state.tokenize(stream, state); + } + }; +}); +CodeMirror.defineMIME("text/x-tcl", "tcl"); + +}); diff --git a/modules/editor/codemirror/mode/textile/textile.min.js b/modules/editor/codemirror/mode/textile/textile.min.js @@ -0,0 +1,469 @@ +// 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 TOKEN_STYLES = { + addition: "positive", + attributes: "attribute", + bold: "strong", + cite: "keyword", + code: "atom", + definitionList: "number", + deletion: "negative", + div: "punctuation", + em: "em", + footnote: "variable", + footCite: "qualifier", + header: "header", + html: "comment", + image: "string", + italic: "em", + link: "link", + linkDefinition: "link", + list1: "variable-2", + list2: "variable-3", + list3: "keyword", + notextile: "string-2", + pre: "operator", + p: "property", + quote: "bracket", + span: "quote", + specialChar: "tag", + strong: "strong", + sub: "builtin", + sup: "builtin", + table: "variable-3", + tableHeading: "operator" + }; + + function startNewLine(stream, state) { + state.mode = Modes.newLayout; + state.tableHeading = false; + + if (state.layoutType === "definitionList" && state.spanningLayout && + stream.match(RE("definitionListEnd"), false)) + state.spanningLayout = false; + } + + function handlePhraseModifier(stream, state, ch) { + if (ch === "_") { + if (stream.eat("_")) + return togglePhraseModifier(stream, state, "italic", /__/, 2); + else + return togglePhraseModifier(stream, state, "em", /_/, 1); + } + + if (ch === "*") { + if (stream.eat("*")) { + return togglePhraseModifier(stream, state, "bold", /\*\*/, 2); + } + return togglePhraseModifier(stream, state, "strong", /\*/, 1); + } + + if (ch === "[") { + if (stream.match(/\d+\]/)) state.footCite = true; + return tokenStyles(state); + } + + if (ch === "(") { + var spec = stream.match(/^(r|tm|c)\)/); + if (spec) + return tokenStylesWith(state, TOKEN_STYLES.specialChar); + } + + if (ch === "<" && stream.match(/(\w+)[^>]+>[^<]+<\/\1>/)) + return tokenStylesWith(state, TOKEN_STYLES.html); + + if (ch === "?" && stream.eat("?")) + return togglePhraseModifier(stream, state, "cite", /\?\?/, 2); + + if (ch === "=" && stream.eat("=")) + return togglePhraseModifier(stream, state, "notextile", /==/, 2); + + if (ch === "-" && !stream.eat("-")) + return togglePhraseModifier(stream, state, "deletion", /-/, 1); + + if (ch === "+") + return togglePhraseModifier(stream, state, "addition", /\+/, 1); + + if (ch === "~") + return togglePhraseModifier(stream, state, "sub", /~/, 1); + + if (ch === "^") + return togglePhraseModifier(stream, state, "sup", /\^/, 1); + + if (ch === "%") + return togglePhraseModifier(stream, state, "span", /%/, 1); + + if (ch === "@") + return togglePhraseModifier(stream, state, "code", /@/, 1); + + if (ch === "!") { + var type = togglePhraseModifier(stream, state, "image", /(?:\([^\)]+\))?!/, 1); + stream.match(/^:\S+/); // optional Url portion + return type; + } + return tokenStyles(state); + } + + function togglePhraseModifier(stream, state, phraseModifier, closeRE, openSize) { + var charBefore = stream.pos > openSize ? stream.string.charAt(stream.pos - openSize - 1) : null; + var charAfter = stream.peek(); + if (state[phraseModifier]) { + if ((!charAfter || /\W/.test(charAfter)) && charBefore && /\S/.test(charBefore)) { + var type = tokenStyles(state); + state[phraseModifier] = false; + return type; + } + } else if ((!charBefore || /\W/.test(charBefore)) && charAfter && /\S/.test(charAfter) && + stream.match(new RegExp("^.*\\S" + closeRE.source + "(?:\\W|$)"), false)) { + state[phraseModifier] = true; + state.mode = Modes.attributes; + } + return tokenStyles(state); + }; + + function tokenStyles(state) { + var disabled = textileDisabled(state); + if (disabled) return disabled; + + var styles = []; + if (state.layoutType) styles.push(TOKEN_STYLES[state.layoutType]); + + styles = styles.concat(activeStyles( + state, "addition", "bold", "cite", "code", "deletion", "em", "footCite", + "image", "italic", "link", "span", "strong", "sub", "sup", "table", "tableHeading")); + + if (state.layoutType === "header") + styles.push(TOKEN_STYLES.header + "-" + state.header); + + return styles.length ? styles.join(" ") : null; + } + + function textileDisabled(state) { + var type = state.layoutType; + + switch(type) { + case "notextile": + case "code": + case "pre": + return TOKEN_STYLES[type]; + default: + if (state.notextile) + return TOKEN_STYLES.notextile + (type ? (" " + TOKEN_STYLES[type]) : ""); + return null; + } + } + + function tokenStylesWith(state, extraStyles) { + var disabled = textileDisabled(state); + if (disabled) return disabled; + + var type = tokenStyles(state); + if (extraStyles) + return type ? (type + " " + extraStyles) : extraStyles; + else + return type; + } + + function activeStyles(state) { + var styles = []; + for (var i = 1; i < arguments.length; ++i) { + if (state[arguments[i]]) + styles.push(TOKEN_STYLES[arguments[i]]); + } + return styles; + } + + function blankLine(state) { + var spanningLayout = state.spanningLayout, type = state.layoutType; + + for (var key in state) if (state.hasOwnProperty(key)) + delete state[key]; + + state.mode = Modes.newLayout; + if (spanningLayout) { + state.layoutType = type; + state.spanningLayout = true; + } + } + + var REs = { + cache: {}, + single: { + bc: "bc", + bq: "bq", + definitionList: /- .*?:=+/, + definitionListEnd: /.*=:\s*$/, + div: "div", + drawTable: /\|.*\|/, + foot: /fn\d+/, + header: /h[1-6]/, + html: /\s*<(?:\/)?(\w+)(?:[^>]+)?>(?:[^<]+<\/\1>)?/, + link: /[^"]+":\S/, + linkDefinition: /\[[^\s\]]+\]\S+/, + list: /(?:#+|\*+)/, + notextile: "notextile", + para: "p", + pre: "pre", + table: "table", + tableCellAttributes: /[\/\\]\d+/, + tableHeading: /\|_\./, + tableText: /[^"_\*\[\(\?\+~\^%@|-]+/, + text: /[^!"_=\*\[\(<\?\+~\^%@-]+/ + }, + attributes: { + align: /(?:<>|<|>|=)/, + selector: /\([^\(][^\)]+\)/, + lang: /\[[^\[\]]+\]/, + pad: /(?:\(+|\)+){1,2}/, + css: /\{[^\}]+\}/ + }, + createRe: function(name) { + switch (name) { + case "drawTable": + return REs.makeRe("^", REs.single.drawTable, "$"); + case "html": + return REs.makeRe("^", REs.single.html, "(?:", REs.single.html, ")*", "$"); + case "linkDefinition": + return REs.makeRe("^", REs.single.linkDefinition, "$"); + case "listLayout": + return REs.makeRe("^", REs.single.list, RE("allAttributes"), "*\\s+"); + case "tableCellAttributes": + return REs.makeRe("^", REs.choiceRe(REs.single.tableCellAttributes, + RE("allAttributes")), "+\\."); + case "type": + return REs.makeRe("^", RE("allTypes")); + case "typeLayout": + return REs.makeRe("^", RE("allTypes"), RE("allAttributes"), + "*\\.\\.?", "(\\s+|$)"); + case "attributes": + return REs.makeRe("^", RE("allAttributes"), "+"); + + case "allTypes": + return REs.choiceRe(REs.single.div, REs.single.foot, + REs.single.header, REs.single.bc, REs.single.bq, + REs.single.notextile, REs.single.pre, REs.single.table, + REs.single.para); + + case "allAttributes": + return REs.choiceRe(REs.attributes.selector, REs.attributes.css, + REs.attributes.lang, REs.attributes.align, REs.attributes.pad); + + default: + return REs.makeRe("^", REs.single[name]); + } + }, + makeRe: function() { + var pattern = ""; + for (var i = 0; i < arguments.length; ++i) { + var arg = arguments[i]; + pattern += (typeof arg === "string") ? arg : arg.source; + } + return new RegExp(pattern); + }, + choiceRe: function() { + var parts = [arguments[0]]; + for (var i = 1; i < arguments.length; ++i) { + parts[i * 2 - 1] = "|"; + parts[i * 2] = arguments[i]; + } + + parts.unshift("(?:"); + parts.push(")"); + return REs.makeRe.apply(null, parts); + } + }; + + function RE(name) { + return (REs.cache[name] || (REs.cache[name] = REs.createRe(name))); + } + + var Modes = { + newLayout: function(stream, state) { + if (stream.match(RE("typeLayout"), false)) { + state.spanningLayout = false; + return (state.mode = Modes.blockType)(stream, state); + } + var newMode; + if (!textileDisabled(state)) { + if (stream.match(RE("listLayout"), false)) + newMode = Modes.list; + else if (stream.match(RE("drawTable"), false)) + newMode = Modes.table; + else if (stream.match(RE("linkDefinition"), false)) + newMode = Modes.linkDefinition; + else if (stream.match(RE("definitionList"))) + newMode = Modes.definitionList; + else if (stream.match(RE("html"), false)) + newMode = Modes.html; + } + return (state.mode = (newMode || Modes.text))(stream, state); + }, + + blockType: function(stream, state) { + var match, type; + state.layoutType = null; + + if (match = stream.match(RE("type"))) + type = match[0]; + else + return (state.mode = Modes.text)(stream, state); + + if (match = type.match(RE("header"))) { + state.layoutType = "header"; + state.header = parseInt(match[0][1]); + } else if (type.match(RE("bq"))) { + state.layoutType = "quote"; + } else if (type.match(RE("bc"))) { + state.layoutType = "code"; + } else if (type.match(RE("foot"))) { + state.layoutType = "footnote"; + } else if (type.match(RE("notextile"))) { + state.layoutType = "notextile"; + } else if (type.match(RE("pre"))) { + state.layoutType = "pre"; + } else if (type.match(RE("div"))) { + state.layoutType = "div"; + } else if (type.match(RE("table"))) { + state.layoutType = "table"; + } + + state.mode = Modes.attributes; + return tokenStyles(state); + }, + + text: function(stream, state) { + if (stream.match(RE("text"))) return tokenStyles(state); + + var ch = stream.next(); + if (ch === '"') + return (state.mode = Modes.link)(stream, state); + return handlePhraseModifier(stream, state, ch); + }, + + attributes: function(stream, state) { + state.mode = Modes.layoutLength; + + if (stream.match(RE("attributes"))) + return tokenStylesWith(state, TOKEN_STYLES.attributes); + else + return tokenStyles(state); + }, + + layoutLength: function(stream, state) { + if (stream.eat(".") && stream.eat(".")) + state.spanningLayout = true; + + state.mode = Modes.text; + return tokenStyles(state); + }, + + list: function(stream, state) { + var match = stream.match(RE("list")); + state.listDepth = match[0].length; + var listMod = (state.listDepth - 1) % 3; + if (!listMod) + state.layoutType = "list1"; + else if (listMod === 1) + state.layoutType = "list2"; + else + state.layoutType = "list3"; + + state.mode = Modes.attributes; + return tokenStyles(state); + }, + + link: function(stream, state) { + state.mode = Modes.text; + if (stream.match(RE("link"))) { + stream.match(/\S+/); + return tokenStylesWith(state, TOKEN_STYLES.link); + } + return tokenStyles(state); + }, + + linkDefinition: function(stream, state) { + stream.skipToEnd(); + return tokenStylesWith(state, TOKEN_STYLES.linkDefinition); + }, + + definitionList: function(stream, state) { + stream.match(RE("definitionList")); + + state.layoutType = "definitionList"; + + if (stream.match(/\s*$/)) + state.spanningLayout = true; + else + state.mode = Modes.attributes; + + return tokenStyles(state); + }, + + html: function(stream, state) { + stream.skipToEnd(); + return tokenStylesWith(state, TOKEN_STYLES.html); + }, + + table: function(stream, state) { + state.layoutType = "table"; + return (state.mode = Modes.tableCell)(stream, state); + }, + + tableCell: function(stream, state) { + if (stream.match(RE("tableHeading"))) + state.tableHeading = true; + else + stream.eat("|"); + + state.mode = Modes.tableCellAttributes; + return tokenStyles(state); + }, + + tableCellAttributes: function(stream, state) { + state.mode = Modes.tableText; + + if (stream.match(RE("tableCellAttributes"))) + return tokenStylesWith(state, TOKEN_STYLES.attributes); + else + return tokenStyles(state); + }, + + tableText: function(stream, state) { + if (stream.match(RE("tableText"))) + return tokenStyles(state); + + if (stream.peek() === "|") { // end of cell + state.mode = Modes.tableCell; + return tokenStyles(state); + } + return handlePhraseModifier(stream, state, stream.next()); + } + }; + + CodeMirror.defineMode("textile", function() { + return { + startState: function() { + return { mode: Modes.newLayout }; + }, + token: function(stream, state) { + if (stream.sol()) startNewLine(stream, state); + return state.mode(stream, state); + }, + blankLine: blankLine + }; + }); + + CodeMirror.defineMIME("text/x-textile", "textile"); +}); diff --git a/modules/editor/codemirror/mode/tornado/tornado.min.js b/modules/editor/codemirror/mode/tornado/tornado.min.js @@ -0,0 +1,68 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function(mod) { + if (typeof exports == "object" && typeof module == "object") // CommonJS + mod(require("../../lib/codemirror"), require("../htmlmixed/htmlmixed"), + require("../../addon/mode/overlay")); + else if (typeof define == "function" && define.amd) // AMD + define(["../../lib/codemirror", "../htmlmixed/htmlmixed", + "../../addon/mode/overlay"], mod); + else // Plain browser env + mod(CodeMirror); +})(function(CodeMirror) { + "use strict"; + + CodeMirror.defineMode("tornado:inner", function() { + var keywords = ["and","as","assert","autoescape","block","break","class","comment","context", + "continue","datetime","def","del","elif","else","end","escape","except", + "exec","extends","false","finally","for","from","global","if","import","in", + "include","is","json_encode","lambda","length","linkify","load","module", + "none","not","or","pass","print","put","raise","raw","return","self","set", + "squeeze","super","true","try","url_escape","while","with","without","xhtml_escape","yield"]; + keywords = new RegExp("^((" + keywords.join(")|(") + "))\\b"); + + function tokenBase (stream, state) { + stream.eatWhile(/[^\{]/); + var ch = stream.next(); + if (ch == "{") { + if (ch = stream.eat(/\{|%|#/)) { + state.tokenize = inTag(ch); + return "tag"; + } + } + } + function inTag (close) { + if (close == "{") { + close = "}"; + } + return function (stream, state) { + var ch = stream.next(); + if ((ch == close) && stream.eat("}")) { + state.tokenize = tokenBase; + return "tag"; + } + if (stream.match(keywords)) { + return "keyword"; + } + return close == "#" ? "comment" : "string"; + }; + } + return { + startState: function () { + return {tokenize: tokenBase}; + }, + token: function (stream, state) { + return state.tokenize(stream, state); + } + }; + }); + + CodeMirror.defineMode("tornado", function(config) { + var htmlBase = CodeMirror.getMode(config, "text/html"); + var tornadoInner = CodeMirror.getMode(config, "tornado:inner"); + return CodeMirror.overlayMode(htmlBase, tornadoInner); + }); + + CodeMirror.defineMIME("text/x-tornado", "tornado"); +}); diff --git a/modules/editor/codemirror/mode/yaml/yaml.min.js b/modules/editor/codemirror/mode/yaml/yaml.min.js @@ -0,0 +1,118 @@ +// 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("yaml", function() { + + var cons = ['true', 'false', 'on', 'off', 'yes', 'no']; + var keywordRegex = new RegExp("\\b(("+cons.join(")|(")+"))$", 'i'); + + return { + token: function(stream, state) { + var ch = stream.peek(); + var esc = state.escaped; + state.escaped = false; + /* comments */ + if (ch == "#" && (stream.pos == 0 || /\s/.test(stream.string.charAt(stream.pos - 1)))) { + stream.skipToEnd(); + return "comment"; + } + + if (stream.match(/^('([^']|\\.)*'?|"([^"]|\\.)*"?)/)) + return "string"; + + if (state.literal && stream.indentation() > state.keyCol) { + stream.skipToEnd(); return "string"; + } else if (state.literal) { state.literal = false; } + if (stream.sol()) { + state.keyCol = 0; + state.pair = false; + state.pairStart = false; + /* document start */ + if(stream.match(/---/)) { return "def"; } + /* document end */ + if (stream.match(/\.\.\./)) { return "def"; } + /* array list item */ + if (stream.match(/\s*-\s+/)) { return 'meta'; } + } + /* inline pairs/lists */ + if (stream.match(/^(\{|\}|\[|\])/)) { + if (ch == '{') + state.inlinePairs++; + else if (ch == '}') + state.inlinePairs--; + else if (ch == '[') + state.inlineList++; + else + state.inlineList--; + return 'meta'; + } + + /* list seperator */ + if (state.inlineList > 0 && !esc && ch == ',') { + stream.next(); + return 'meta'; + } + /* pairs seperator */ + if (state.inlinePairs > 0 && !esc && ch == ',') { + state.keyCol = 0; + state.pair = false; + state.pairStart = false; + stream.next(); + return 'meta'; + } + + /* start of value of a pair */ + if (state.pairStart) { + /* block literals */ + if (stream.match(/^\s*(\||\>)\s*/)) { state.literal = true; return 'meta'; }; + /* references */ + if (stream.match(/^\s*(\&|\*)[a-z0-9\._-]+\b/i)) { return 'variable-2'; } + /* numbers */ + if (state.inlinePairs == 0 && stream.match(/^\s*-?[0-9\.\,]+\s?$/)) { return 'number'; } + if (state.inlinePairs > 0 && stream.match(/^\s*-?[0-9\.\,]+\s?(?=(,|}))/)) { return 'number'; } + /* keywords */ + if (stream.match(keywordRegex)) { return 'keyword'; } + } + + /* pairs (associative arrays) -> key */ + if (!state.pair && stream.match(/^\s*(?:[,\[\]{}&*!|>'"%@`][^\s'":]|[^,\[\]{}#&*!|>'"%@`])[^#]*?(?=\s*:($|\s))/)) { + state.pair = true; + state.keyCol = stream.indentation(); + return "atom"; + } + if (state.pair && stream.match(/^:\s*/)) { state.pairStart = true; return 'meta'; } + + /* nothing found, continue */ + state.pairStart = false; + state.escaped = (ch == '\\'); + stream.next(); + return null; + }, + startState: function() { + return { + pair: false, + pairStart: false, + keyCol: 0, + inlinePairs: 0, + inlineList: 0, + literal: false, + escaped: false + }; + } + }; +}); + +CodeMirror.defineMIME("text/x-yaml", "yaml"); +CodeMirror.defineMIME("text/yaml", "yaml"); + +}); diff --git a/modules/editor/codemirror/rollup.config.js b/modules/editor/codemirror/rollup.config.js @@ -0,0 +1,18 @@ +import buble from 'rollup-plugin-buble'; + +export default { + banner: `// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// This is CodeMirror (http://codemirror.net), a code editor +// implemented in JavaScript on top of the browser's DOM. +// +// You can find some technical background for some of the code below +// at http://marijnhaverbeke.nl/blog/#cm-internals . +`, + entry: "src/codemirror.js", + format: "umd", + dest: "lib/codemirror.js", + moduleName: "CodeMirror", + plugins: [ buble({namedFunctionExpressions: false}) ] +}; diff --git a/modules/editor/codemirror/src/codemirror.js b/modules/editor/codemirror/src/codemirror.js @@ -0,0 +1,3 @@ +import { CodeMirror } from "./edit/main.js" + +export default CodeMirror diff --git a/modules/editor/codemirror/src/display/Display.min.js b/modules/editor/codemirror/src/display/Display.min.js @@ -0,0 +1,106 @@ +import { gecko, ie, ie_version, mobile, webkit } from "../util/browser.js" +import { elt, eltP } from "../util/dom.js" +import { scrollerGap } from "../util/misc.js" + +// The display handles the DOM integration, both for input reading +// and content drawing. It holds references to DOM nodes and +// display-related state. + +export function Display(place, doc, input) { + let d = this + this.input = input + + // Covers bottom-right square when both scrollbars are present. + d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler") + d.scrollbarFiller.setAttribute("cm-not-content", "true") + // Covers bottom of gutter when coverGutterNextToScrollbar is on + // and h scrollbar is present. + d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler") + d.gutterFiller.setAttribute("cm-not-content", "true") + // Will contain the actual code, positioned to cover the viewport. + d.lineDiv = eltP("div", null, "CodeMirror-code") + // Elements are added to these to represent selection and cursors. + d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1") + d.cursorDiv = elt("div", null, "CodeMirror-cursors") + // A visibility: hidden element used to find the size of things. + d.measure = elt("div", null, "CodeMirror-measure") + // When lines outside of the viewport are measured, they are drawn in this. + d.lineMeasure = elt("div", null, "CodeMirror-measure") + // Wraps everything that needs to exist inside the vertically-padded coordinate system + d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], + null, "position: relative; outline: none") + let lines = eltP("div", [d.lineSpace], "CodeMirror-lines") + // Moved around its parent to cover visible view. + d.mover = elt("div", [lines], null, "position: relative") + // Set to the height of the document, allowing scrolling. + d.sizer = elt("div", [d.mover], "CodeMirror-sizer") + d.sizerWidth = null + // Behavior of elts with overflow: auto and padding is + // inconsistent across browsers. This is used to ensure the + // scrollable area is big enough. + d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;") + // Will contain the gutters, if any. + d.gutters = elt("div", null, "CodeMirror-gutters") + d.lineGutter = null + // Actual scrollable element. + d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll") + d.scroller.setAttribute("tabIndex", "-1") + // The element in which the editor lives. + d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror") + + // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) + if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0 } + if (!webkit && !(gecko && mobile)) d.scroller.draggable = true + + if (place) { + if (place.appendChild) place.appendChild(d.wrapper) + else place(d.wrapper) + } + + // Current rendered range (may be bigger than the view window). + d.viewFrom = d.viewTo = doc.first + d.reportedViewFrom = d.reportedViewTo = doc.first + // Information about the rendered lines. + d.view = [] + d.renderedView = null + // Holds info about a single rendered line when it was rendered + // for measurement, while not in view. + d.externalMeasured = null + // Empty space (in pixels) above the view + d.viewOffset = 0 + d.lastWrapHeight = d.lastWrapWidth = 0 + d.updateLineNumbers = null + + d.nativeBarWidth = d.barHeight = d.barWidth = 0 + d.scrollbarsClipped = false + + // Used to only resize the line number gutter when necessary (when + // the amount of lines crosses a boundary that makes its width change) + d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null + // Set to true when a non-horizontal-scrolling line widget is + // added. As an optimization, line widget aligning is skipped when + // this is false. + d.alignWidgets = false + + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null + + // Tracks the maximum line length so that the horizontal scrollbar + // can be kept static when scrolling. + d.maxLine = null + d.maxLineLength = 0 + d.maxLineChanged = false + + // Used for measuring wheel scrolling granularity + d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null + + // True when shift is held down. + d.shift = false + + // Used to track whether anything happened since the context menu + // was opened. + d.selForContextMenu = null + + d.activeTouch = null + + input.init(d) +} diff --git a/modules/editor/codemirror/src/display/operations.js b/modules/editor/codemirror/src/display/operations.js @@ -0,0 +1,205 @@ +import { clipPos } from "../line/pos.js" +import { findMaxLine } from "../line/spans.js" +import { displayWidth, measureChar, scrollGap } from "../measurement/position_measurement.js" +import { signal } from "../util/event.js" +import { activeElt } from "../util/dom.js" +import { finishOperation, pushOperation } from "../util/operation_group.js" + +import { ensureFocus } from "./focus.js" +import { measureForScrollbars, updateScrollbars } from "./scrollbars.js" +import { restartBlink } from "./selection.js" +import { maybeScrollWindow, scrollPosIntoView, setScrollLeft, setScrollTop } from "./scrolling.js" +import { DisplayUpdate, maybeClipScrollbars, postUpdateDisplay, setDocumentHeight, updateDisplayIfNeeded } from "./update_display.js" +import { updateHeightsInViewport } from "./update_lines.js" + +// Operations are used to wrap a series of changes to the editor +// state in such a way that each change won't have to update the +// cursor and display (which would be awkward, slow, and +// error-prone). Instead, display updates are batched and then all +// combined and executed at once. + +let nextOpId = 0 +// Start a new operation. +export function startOperation(cm) { + cm.curOp = { + cm: cm, + viewChanged: false, // Flag that indicates that lines might need to be redrawn + startHeight: cm.doc.height, // Used to detect need to update scrollbar + forceUpdate: false, // Used to force a redraw + updateInput: null, // Whether to reset the input textarea + typing: false, // Whether this reset should be careful to leave existing text (for compositing) + changeObjs: null, // Accumulated changes, for firing change events + cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on + cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already + selectionChanged: false, // Whether the selection needs to be redrawn + updateMaxLine: false, // Set when the widest line needs to be determined anew + scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet + scrollToPos: null, // Used to scroll to a specific position + focus: false, + id: ++nextOpId // Unique ID + } + pushOperation(cm.curOp) +} + +// Finish an operation, updating the display and signalling delayed events +export function endOperation(cm) { + let op = cm.curOp + finishOperation(op, group => { + for (let i = 0; i < group.ops.length; i++) + group.ops[i].cm.curOp = null + endOperations(group) + }) +} + +// The DOM updates done when an operation finishes are batched so +// that the minimum number of relayouts are required. +function endOperations(group) { + let ops = group.ops + for (let i = 0; i < ops.length; i++) // Read DOM + endOperation_R1(ops[i]) + for (let i = 0; i < ops.length; i++) // Write DOM (maybe) + endOperation_W1(ops[i]) + for (let i = 0; i < ops.length; i++) // Read DOM + endOperation_R2(ops[i]) + for (let i = 0; i < ops.length; i++) // Write DOM (maybe) + endOperation_W2(ops[i]) + for (let i = 0; i < ops.length; i++) // Read DOM + endOperation_finish(ops[i]) +} + +function endOperation_R1(op) { + let cm = op.cm, display = cm.display + maybeClipScrollbars(cm) + if (op.updateMaxLine) findMaxLine(cm) + + op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || + op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || + op.scrollToPos.to.line >= display.viewTo) || + display.maxLineChanged && cm.options.lineWrapping + op.update = op.mustUpdate && + new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate) +} + +function endOperation_W1(op) { + op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update) +} + +function endOperation_R2(op) { + let cm = op.cm, display = cm.display + if (op.updatedDisplay) updateHeightsInViewport(cm) + + op.barMeasure = measureForScrollbars(cm) + + // If the max line changed since it was last measured, measure it, + // and ensure the document's width matches it. + // updateDisplay_W2 will use these properties to do the actual resizing + if (display.maxLineChanged && !cm.options.lineWrapping) { + op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3 + cm.display.sizerWidth = op.adjustWidthTo + op.barMeasure.scrollWidth = + Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth) + op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)) + } + + if (op.updatedDisplay || op.selectionChanged) + op.preparedSelection = display.input.prepareSelection() +} + +function endOperation_W2(op) { + let cm = op.cm + + if (op.adjustWidthTo != null) { + cm.display.sizer.style.minWidth = op.adjustWidthTo + "px" + if (op.maxScrollLeft < cm.doc.scrollLeft) + setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true) + cm.display.maxLineChanged = false + } + + let takeFocus = op.focus && op.focus == activeElt() + if (op.preparedSelection) + cm.display.input.showSelection(op.preparedSelection, takeFocus) + if (op.updatedDisplay || op.startHeight != cm.doc.height) + updateScrollbars(cm, op.barMeasure) + if (op.updatedDisplay) + setDocumentHeight(cm, op.barMeasure) + + if (op.selectionChanged) restartBlink(cm) + + if (cm.state.focused && op.updateInput) + cm.display.input.reset(op.typing) + if (takeFocus) ensureFocus(op.cm) +} + +function endOperation_finish(op) { + let cm = op.cm, display = cm.display, doc = cm.doc + + if (op.updatedDisplay) postUpdateDisplay(cm, op.update) + + // Abort mouse wheel delta measurement, when scrolling explicitly + if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) + display.wheelStartX = display.wheelStartY = null + + // Propagate the scroll position to the actual DOM scroller + if (op.scrollTop != null) setScrollTop(cm, op.scrollTop, op.forceScroll) + + if (op.scrollLeft != null) setScrollLeft(cm, op.scrollLeft, true, true) + // If we need to scroll a specific position into view, do so. + if (op.scrollToPos) { + let rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), + clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin) + maybeScrollWindow(cm, rect) + } + + // Fire events for markers that are hidden/unidden by editing or + // undoing + let hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers + if (hidden) for (let i = 0; i < hidden.length; ++i) + if (!hidden[i].lines.length) signal(hidden[i], "hide") + if (unhidden) for (let i = 0; i < unhidden.length; ++i) + if (unhidden[i].lines.length) signal(unhidden[i], "unhide") + + if (display.wrapper.offsetHeight) + doc.scrollTop = cm.display.scroller.scrollTop + + // Fire change events, and delayed event handlers + if (op.changeObjs) + signal(cm, "changes", cm, op.changeObjs) + if (op.update) + op.update.finish() +} + +// Run the given function in an operation +export function runInOp(cm, f) { + if (cm.curOp) return f() + startOperation(cm) + try { return f() } + finally { endOperation(cm) } +} +// Wraps a function in an operation. Returns the wrapped function. +export function operation(cm, f) { + return function() { + if (cm.curOp) return f.apply(cm, arguments) + startOperation(cm) + try { return f.apply(cm, arguments) } + finally { endOperation(cm) } + } +} +// Used to add methods to editor and doc instances, wrapping them in +// operations. +export function methodOp(f) { + return function() { + if (this.curOp) return f.apply(this, arguments) + startOperation(this) + try { return f.apply(this, arguments) } + finally { endOperation(this) } + } +} +export function docMethodOp(f) { + return function() { + let cm = this.cm + if (!cm || cm.curOp) return f.apply(this, arguments) + startOperation(cm) + try { return f.apply(this, arguments) } + finally { endOperation(cm) } + } +} diff --git a/modules/editor/codemirror/src/display/scroll_events.js b/modules/editor/codemirror/src/display/scroll_events.js @@ -0,0 +1,115 @@ +import { chrome, gecko, ie, mac, presto, safari, webkit } from "../util/browser.js" +import { e_preventDefault } from "../util/event.js" + +import { updateDisplaySimple } from "./update_display.js" +import { setScrollLeft, updateScrollTop } from "./scrolling.js" + +// Since the delta values reported on mouse wheel events are +// unstandardized between browsers and even browser versions, and +// generally horribly unpredictable, this code starts by measuring +// the scroll effect that the first few mouse wheel events have, +// and, from that, detects the way it can convert deltas to pixel +// offsets afterwards. +// +// The reason we want to know the amount a wheel event will scroll +// is that it gives us a chance to update the display before the +// actual scrolling happens, reducing flickering. + +let wheelSamples = 0, wheelPixelsPerUnit = null +// Fill in a browser-detected starting value on browsers where we +// know one. These don't have to be accurate -- the result of them +// being wrong would just be a slight flicker on the first wheel +// scroll (if it is large enough). +if (ie) wheelPixelsPerUnit = -.53 +else if (gecko) wheelPixelsPerUnit = 15 +else if (chrome) wheelPixelsPerUnit = -.7 +else if (safari) wheelPixelsPerUnit = -1/3 + +function wheelEventDelta(e) { + let dx = e.wheelDeltaX, dy = e.wheelDeltaY + if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail + if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail + else if (dy == null) dy = e.wheelDelta + return {x: dx, y: dy} +} +export function wheelEventPixels(e) { + let delta = wheelEventDelta(e) + delta.x *= wheelPixelsPerUnit + delta.y *= wheelPixelsPerUnit + return delta +} + +export function onScrollWheel(cm, e) { + let delta = wheelEventDelta(e), dx = delta.x, dy = delta.y + + let display = cm.display, scroll = display.scroller + // Quit if there's nothing to scroll here + let canScrollX = scroll.scrollWidth > scroll.clientWidth + let canScrollY = scroll.scrollHeight > scroll.clientHeight + if (!(dx && canScrollX || dy && canScrollY)) return + + // Webkit browsers on OS X abort momentum scrolls when the target + // of the scroll event is removed from the scrollable element. + // This hack (see related code in patchDisplay) makes sure the + // element is kept around. + if (dy && mac && webkit) { + outer: for (let cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { + for (let i = 0; i < view.length; i++) { + if (view[i].node == cur) { + cm.display.currentWheelTarget = cur + break outer + } + } + } + } + + // On some browsers, horizontal scrolling will cause redraws to + // happen before the gutter has been realigned, causing it to + // wriggle around in a most unseemly way. When we have an + // estimated pixels/delta value, we just handle horizontal + // scrolling entirely here. It'll be slightly off from native, but + // better than glitching out. + if (dx && !gecko && !presto && wheelPixelsPerUnit != null) { + if (dy && canScrollY) + updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)) + setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit)) + // Only prevent default scrolling if vertical scrolling is + // actually possible. Otherwise, it causes vertical scroll + // jitter on OSX trackpads when deltaX is small and deltaY + // is large (issue #3579) + if (!dy || (dy && canScrollY)) + e_preventDefault(e) + display.wheelStartX = null // Abort measurement, if in progress + return + } + + // 'Project' the visible viewport to cover the area that is being + // scrolled into view (if we know enough to estimate it). + if (dy && wheelPixelsPerUnit != null) { + let pixels = dy * wheelPixelsPerUnit + let top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight + if (pixels < 0) top = Math.max(0, top + pixels - 50) + else bot = Math.min(cm.doc.height, bot + pixels + 50) + updateDisplaySimple(cm, {top: top, bottom: bot}) + } + + if (wheelSamples < 20) { + if (display.wheelStartX == null) { + display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop + display.wheelDX = dx; display.wheelDY = dy + setTimeout(() => { + if (display.wheelStartX == null) return + let movedX = scroll.scrollLeft - display.wheelStartX + let movedY = scroll.scrollTop - display.wheelStartY + let sample = (movedY && display.wheelDY && movedY / display.wheelDY) || + (movedX && display.wheelDX && movedX / display.wheelDX) + display.wheelStartX = display.wheelStartY = null + if (!sample) return + wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1) + ++wheelSamples + }, 200) + } else { + display.wheelDX += dx; display.wheelDY += dy + } + } +} diff --git a/modules/editor/codemirror/src/display/view_tracking.js b/modules/editor/codemirror/src/display/view_tracking.js @@ -0,0 +1,153 @@ +import { buildViewArray } from "../line/line_data.js" +import { sawCollapsedSpans } from "../line/saw_special_spans.js" +import { visualLineEndNo, visualLineNo } from "../line/spans.js" +import { findViewIndex } from "../measurement/position_measurement.js" +import { indexOf } from "../util/misc.js" + +// Updates the display.view data structure for a given change to the +// document. From and to are in pre-change coordinates. Lendiff is +// the amount of lines added or subtracted by the change. This is +// used for changes that span multiple lines, or change the way +// lines are divided into visual lines. regLineChange (below) +// registers single-line changes. +export function regChange(cm, from, to, lendiff) { + if (from == null) from = cm.doc.first + if (to == null) to = cm.doc.first + cm.doc.size + if (!lendiff) lendiff = 0 + + let display = cm.display + if (lendiff && to < display.viewTo && + (display.updateLineNumbers == null || display.updateLineNumbers > from)) + display.updateLineNumbers = from + + cm.curOp.viewChanged = true + + if (from >= display.viewTo) { // Change after + if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) + resetView(cm) + } else if (to <= display.viewFrom) { // Change before + if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { + resetView(cm) + } else { + display.viewFrom += lendiff + display.viewTo += lendiff + } + } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap + resetView(cm) + } else if (from <= display.viewFrom) { // Top overlap + let cut = viewCuttingPoint(cm, to, to + lendiff, 1) + if (cut) { + display.view = display.view.slice(cut.index) + display.viewFrom = cut.lineN + display.viewTo += lendiff + } else { + resetView(cm) + } + } else if (to >= display.viewTo) { // Bottom overlap + let cut = viewCuttingPoint(cm, from, from, -1) + if (cut) { + display.view = display.view.slice(0, cut.index) + display.viewTo = cut.lineN + } else { + resetView(cm) + } + } else { // Gap in the middle + let cutTop = viewCuttingPoint(cm, from, from, -1) + let cutBot = viewCuttingPoint(cm, to, to + lendiff, 1) + if (cutTop && cutBot) { + display.view = display.view.slice(0, cutTop.index) + .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) + .concat(display.view.slice(cutBot.index)) + display.viewTo += lendiff + } else { + resetView(cm) + } + } + + let ext = display.externalMeasured + if (ext) { + if (to < ext.lineN) + ext.lineN += lendiff + else if (from < ext.lineN + ext.size) + display.externalMeasured = null + } +} + +// Register a change to a single line. Type must be one of "text", +// "gutter", "class", "widget" +export function regLineChange(cm, line, type) { + cm.curOp.viewChanged = true + let display = cm.display, ext = cm.display.externalMeasured + if (ext && line >= ext.lineN && line < ext.lineN + ext.size) + display.externalMeasured = null + + if (line < display.viewFrom || line >= display.viewTo) return + let lineView = display.view[findViewIndex(cm, line)] + if (lineView.node == null) return + let arr = lineView.changes || (lineView.changes = []) + if (indexOf(arr, type) == -1) arr.push(type) +} + +// Clear the view. +export function resetView(cm) { + cm.display.viewFrom = cm.display.viewTo = cm.doc.first + cm.display.view = [] + cm.display.viewOffset = 0 +} + +function viewCuttingPoint(cm, oldN, newN, dir) { + let index = findViewIndex(cm, oldN), diff, view = cm.display.view + if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) + return {index: index, lineN: newN} + let n = cm.display.viewFrom + for (let i = 0; i < index; i++) + n += view[i].size + if (n != oldN) { + if (dir > 0) { + if (index == view.length - 1) return null + diff = (n + view[index].size) - oldN + index++ + } else { + diff = n - oldN + } + oldN += diff; newN += diff + } + while (visualLineNo(cm.doc, newN) != newN) { + if (index == (dir < 0 ? 0 : view.length - 1)) return null + newN += dir * view[index - (dir < 0 ? 1 : 0)].size + index += dir + } + return {index: index, lineN: newN} +} + +// Force the view to cover a given range, adding empty view element +// or clipping off existing ones as needed. +export function adjustView(cm, from, to) { + let display = cm.display, view = display.view + if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { + display.view = buildViewArray(cm, from, to) + display.viewFrom = from + } else { + if (display.viewFrom > from) + display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view) + else if (display.viewFrom < from) + display.view = display.view.slice(findViewIndex(cm, from)) + display.viewFrom = from + if (display.viewTo < to) + display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)) + else if (display.viewTo > to) + display.view = display.view.slice(0, findViewIndex(cm, to)) + } + display.viewTo = to +} + +// Count the number of lines in the view whose DOM representation is +// out of date (or nonexistent). +export function countDirtyView(cm) { + let view = cm.display.view, dirty = 0 + for (let i = 0; i < view.length; i++) { + let lineView = view[i] + if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty + } + return dirty +} diff --git a/modules/editor/codemirror/src/edit/commands.min.js b/modules/editor/codemirror/src/edit/commands.min.js @@ -0,0 +1,178 @@ +import { deleteNearSelection } from "./deleteNearSelection.js" +import { runInOp } from "../display/operations.js" +import { ensureCursorVisible } from "../display/scrolling.js" +import { endOfLine } from "../input/movement.js" +import { clipPos, Pos } from "../line/pos.js" +import { visualLine, visualLineEnd } from "../line/spans.js" +import { getLine, lineNo } from "../line/utils_line.js" +import { Range } from "../model/selection.js" +import { selectAll } from "../model/selection_updates.js" +import { countColumn, sel_dontScroll, sel_move, spaceStr } from "../util/misc.js" +import { getOrder } from "../util/bidi.js" + +// Commands are parameter-less actions that can be performed on an +// editor, mostly used for keybindings. +export let commands = { + selectAll: selectAll, + singleSelection: cm => cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll), + killLine: cm => deleteNearSelection(cm, range => { + if (range.empty()) { + let len = getLine(cm.doc, range.head.line).text.length + if (range.head.ch == len && range.head.line < cm.lastLine()) + return {from: range.head, to: Pos(range.head.line + 1, 0)} + else + return {from: range.head, to: Pos(range.head.line, len)} + } else { + return {from: range.from(), to: range.to()} + } + }), + deleteLine: cm => deleteNearSelection(cm, range => ({ + from: Pos(range.from().line, 0), + to: clipPos(cm.doc, Pos(range.to().line + 1, 0)) + })), + delLineLeft: cm => deleteNearSelection(cm, range => ({ + from: Pos(range.from().line, 0), to: range.from() + })), + delWrappedLineLeft: cm => deleteNearSelection(cm, range => { + let top = cm.charCoords(range.head, "div").top + 5 + let leftPos = cm.coordsChar({left: 0, top: top}, "div") + return {from: leftPos, to: range.from()} + }), + delWrappedLineRight: cm => deleteNearSelection(cm, range => { + let top = cm.charCoords(range.head, "div").top + 5 + let rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div") + return {from: range.from(), to: rightPos } + }), + undo: cm => cm.undo(), + redo: cm => cm.redo(), + undoSelection: cm => cm.undoSelection(), + redoSelection: cm => cm.redoSelection(), + goDocStart: cm => cm.extendSelection(Pos(cm.firstLine(), 0)), + goDocEnd: cm => cm.extendSelection(Pos(cm.lastLine())), + goLineStart: cm => cm.extendSelectionsBy(range => lineStart(cm, range.head.line), + {origin: "+move", bias: 1} + ), + goLineStartSmart: cm => cm.extendSelectionsBy(range => lineStartSmart(cm, range.head), + {origin: "+move", bias: 1} + ), + goLineEnd: cm => cm.extendSelectionsBy(range => lineEnd(cm, range.head.line), + {origin: "+move", bias: -1} + ), + goLineRight: cm => cm.extendSelectionsBy(range => { + let top = cm.cursorCoords(range.head, "div").top + 5 + return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div") + }, sel_move), + goLineLeft: cm => cm.extendSelectionsBy(range => { + let top = cm.cursorCoords(range.head, "div").top + 5 + return cm.coordsChar({left: 0, top: top}, "div") + }, sel_move), + goLineLeftSmart: cm => cm.extendSelectionsBy(range => { + let top = cm.cursorCoords(range.head, "div").top + 5 + let pos = cm.coordsChar({left: 0, top: top}, "div") + if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head) + return pos + }, sel_move), + goLineUp: cm => cm.moveV(-1, "line"), + goLineDown: cm => cm.moveV(1, "line"), + goPageUp: cm => cm.moveV(-1, "page"), + goPageDown: cm => cm.moveV(1, "page"), + goCharLeft: cm => cm.moveH(-1, "char"), + goCharRight: cm => cm.moveH(1, "char"), + goColumnLeft: cm => cm.moveH(-1, "column"), + goColumnRight: cm => cm.moveH(1, "column"), + goWordLeft: cm => cm.moveH(-1, "word"), + goGroupRight: cm => cm.moveH(1, "group"), + goGroupLeft: cm => cm.moveH(-1, "group"), + goWordRight: cm => cm.moveH(1, "word"), + delCharBefore: cm => cm.deleteH(-1, "char"), + delCharAfter: cm => cm.deleteH(1, "char"), + delWordBefore: cm => cm.deleteH(-1, "word"), + delWordAfter: cm => cm.deleteH(1, "word"), + delGroupBefore: cm => cm.deleteH(-1, "group"), + delGroupAfter: cm => cm.deleteH(1, "group"), + indentAuto: cm => cm.indentSelection("smart"), + indentMore: cm => cm.indentSelection("add"), + indentLess: cm => cm.indentSelection("subtract"), + insertTab: cm => cm.replaceSelection("\t"), + insertSoftTab: cm => { + let spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize + for (let i = 0; i < ranges.length; i++) { + let pos = ranges[i].from() + let col = countColumn(cm.getLine(pos.line), pos.ch, tabSize) + spaces.push(spaceStr(tabSize - col % tabSize)) + } + cm.replaceSelections(spaces) + }, + defaultTab: cm => { + if (cm.somethingSelected()) cm.indentSelection("add") + else cm.execCommand("insertTab") + }, + // Swap the two chars left and right of each selection's head. + // Move cursor behind the two swapped characters afterwards. + // + // Doesn't consider line feeds a character. + // Doesn't scan more than one line above to find a character. + // Doesn't do anything on an empty line. + // Doesn't do anything with non-empty selections. + transposeChars: cm => runInOp(cm, () => { + let ranges = cm.listSelections(), newSel = [] + for (let i = 0; i < ranges.length; i++) { + if (!ranges[i].empty()) continue + let cur = ranges[i].head, line = getLine(cm.doc, cur.line).text + if (line) { + if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1) + if (cur.ch > 0) { + cur = new Pos(cur.line, cur.ch + 1) + cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), + Pos(cur.line, cur.ch - 2), cur, "+transpose") + } else if (cur.line > cm.doc.first) { + let prev = getLine(cm.doc, cur.line - 1).text + if (prev) { + cur = new Pos(cur.line, 1) + cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() + + prev.charAt(prev.length - 1), + Pos(cur.line - 1, prev.length - 1), cur, "+transpose") + } + } + } + newSel.push(new Range(cur, cur)) + } + cm.setSelections(newSel) + }), + newlineAndIndent: cm => runInOp(cm, () => { + let sels = cm.listSelections() + for (let i = sels.length - 1; i >= 0; i--) + cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input") + sels = cm.listSelections() + for (let i = 0; i < sels.length; i++) + cm.indentLine(sels[i].from().line, null, true) + ensureCursorVisible(cm) + }), + openLine: cm => cm.replaceSelection("\n", "start"), + toggleOverwrite: cm => cm.toggleOverwrite() +} + + +function lineStart(cm, lineN) { + let line = getLine(cm.doc, lineN) + let visual = visualLine(line) + if (visual != line) lineN = lineNo(visual) + return endOfLine(true, cm, visual, lineN, 1) +} +function lineEnd(cm, lineN) { + let line = getLine(cm.doc, lineN) + let visual = visualLineEnd(line) + if (visual != line) lineN = lineNo(visual) + return endOfLine(true, cm, line, lineN, -1) +} +function lineStartSmart(cm, pos) { + let start = lineStart(cm, pos.line) + let line = getLine(cm.doc, start.line) + let order = getOrder(line, cm.doc.direction) + if (!order || order[0].level == 0) { + let firstNonWS = Math.max(0, line.text.search(/\S/)) + let inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch + return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky) + } + return start +} diff --git a/modules/editor/codemirror/src/edit/deleteNearSelection.js b/modules/editor/codemirror/src/edit/deleteNearSelection.js @@ -0,0 +1,30 @@ +import { runInOp } from "../display/operations.js" +import { ensureCursorVisible } from "../display/scrolling.js" +import { cmp } from "../line/pos.js" +import { replaceRange } from "../model/changes.js" +import { lst } from "../util/misc.js" + +// Helper for deleting text near the selection(s), used to implement +// backspace, delete, and similar functionality. +export function deleteNearSelection(cm, compute) { + let ranges = cm.doc.sel.ranges, kill = [] + // Build up a set of ranges to kill first, merging overlapping + // ranges. + for (let i = 0; i < ranges.length; i++) { + let toKill = compute(ranges[i]) + while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { + let replaced = kill.pop() + if (cmp(replaced.from, toKill.from) < 0) { + toKill.from = replaced.from + break + } + } + kill.push(toKill) + } + // Next, remove those actual ranges. + runInOp(cm, () => { + for (let i = kill.length - 1; i >= 0; i--) + replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete") + ensureCursorVisible(cm) + }) +} diff --git a/modules/editor/codemirror/src/edit/deleteNearSelection.min.js b/modules/editor/codemirror/src/edit/deleteNearSelection.min.js @@ -0,0 +1,30 @@ +import { runInOp } from "../display/operations.js" +import { ensureCursorVisible } from "../display/scrolling.js" +import { cmp } from "../line/pos.js" +import { replaceRange } from "../model/changes.js" +import { lst } from "../util/misc.js" + +// Helper for deleting text near the selection(s), used to implement +// backspace, delete, and similar functionality. +export function deleteNearSelection(cm, compute) { + let ranges = cm.doc.sel.ranges, kill = [] + // Build up a set of ranges to kill first, merging overlapping + // ranges. + for (let i = 0; i < ranges.length; i++) { + let toKill = compute(ranges[i]) + while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { + let replaced = kill.pop() + if (cmp(replaced.from, toKill.from) < 0) { + toKill.from = replaced.from + break + } + } + kill.push(toKill) + } + // Next, remove those actual ranges. + runInOp(cm, () => { + for (let i = kill.length - 1; i >= 0; i--) + replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete") + ensureCursorVisible(cm) + }) +} diff --git a/modules/editor/codemirror/src/edit/global_events.min.js b/modules/editor/codemirror/src/edit/global_events.min.js @@ -0,0 +1,44 @@ +import { onBlur } from "../display/focus.js" +import { on } from "../util/event.js" + +// These must be handled carefully, because naively registering a +// handler for each editor will cause the editors to never be +// garbage collected. + +function forEachCodeMirror(f) { + if (!document.getElementsByClassName) return + let byClass = document.getElementsByClassName("CodeMirror") + for (let i = 0; i < byClass.length; i++) { + let cm = byClass[i].CodeMirror + if (cm) f(cm) + } +} + +let globalsRegistered = false +export function ensureGlobalHandlers() { + if (globalsRegistered) return + registerGlobalHandlers() + globalsRegistered = true +} +function registerGlobalHandlers() { + // When the window resizes, we need to refresh active editors. + let resizeTimer + on(window, "resize", () => { + if (resizeTimer == null) resizeTimer = setTimeout(() => { + resizeTimer = null + forEachCodeMirror(onResize) + }, 100) + }) + // When the window loses focus, we want to show the editor as blurred + on(window, "blur", () => forEachCodeMirror(onBlur)) +} +// Called when the window resizes +function onResize(cm) { + let d = cm.display + if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth) + return + // Might be a text scaling operation, clear size caches. + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null + d.scrollbarsClipped = false + cm.setSize() +} diff --git a/modules/editor/codemirror/src/edit/legacy.js b/modules/editor/codemirror/src/edit/legacy.js @@ -0,0 +1,62 @@ +import { scrollbarModel } from "../display/scrollbars.js" +import { wheelEventPixels } from "../display/scroll_events.js" +import { keyMap, keyName, isModifierKey, lookupKey, normalizeKeyMap } from "../input/keymap.js" +import { keyNames } from "../input/keynames.js" +import { Line } from "../line/line_data.js" +import { cmp, Pos } from "../line/pos.js" +import { changeEnd } from "../model/change_measurement.js" +import Doc from "../model/Doc.js" +import { LineWidget } from "../model/line_widget.js" +import { SharedTextMarker, TextMarker } from "../model/mark_text.js" +import { copyState, extendMode, getMode, innerMode, mimeModes, modeExtensions, modes, resolveMode, startState } from "../modes.js" +import { addClass, contains, rmClass } from "../util/dom.js" +import { e_preventDefault, e_stop, e_stopPropagation, off, on, signal } from "../util/event.js" +import { splitLinesAuto } from "../util/feature_detection.js" +import { countColumn, findColumn, isWordCharBasic, Pass } from "../util/misc.js" +import StringStream from "../util/StringStream.js" + +import { commands } from "./commands.js" + +export function addLegacyProps(CodeMirror) { + CodeMirror.off = off + CodeMirror.on = on + CodeMirror.wheelEventPixels = wheelEventPixels + CodeMirror.Doc = Doc + CodeMirror.splitLines = splitLinesAuto + CodeMirror.countColumn = countColumn + CodeMirror.findColumn = findColumn + CodeMirror.isWordChar = isWordCharBasic + CodeMirror.Pass = Pass + CodeMirror.signal = signal + CodeMirror.Line = Line + CodeMirror.changeEnd = changeEnd + CodeMirror.scrollbarModel = scrollbarModel + CodeMirror.Pos = Pos + CodeMirror.cmpPos = cmp + CodeMirror.modes = modes + CodeMirror.mimeModes = mimeModes + CodeMirror.resolveMode = resolveMode + CodeMirror.getMode = getMode + CodeMirror.modeExtensions = modeExtensions + CodeMirror.extendMode = extendMode + CodeMirror.copyState = copyState + CodeMirror.startState = startState + CodeMirror.innerMode = innerMode + CodeMirror.commands = commands + CodeMirror.keyMap = keyMap + CodeMirror.keyName = keyName + CodeMirror.isModifierKey = isModifierKey + CodeMirror.lookupKey = lookupKey + CodeMirror.normalizeKeyMap = normalizeKeyMap + CodeMirror.StringStream = StringStream + CodeMirror.SharedTextMarker = SharedTextMarker + CodeMirror.TextMarker = TextMarker + CodeMirror.LineWidget = LineWidget + CodeMirror.e_preventDefault = e_preventDefault + CodeMirror.e_stopPropagation = e_stopPropagation + CodeMirror.e_stop = e_stop + CodeMirror.addClass = addClass + CodeMirror.contains = contains + CodeMirror.rmClass = rmClass + CodeMirror.keyNames = keyNames +} diff --git a/modules/editor/codemirror/src/input/input.js b/modules/editor/codemirror/src/input/input.js @@ -0,0 +1,135 @@ +import { runInOp } from "../display/operations.js" +import { ensureCursorVisible } from "../display/scrolling.js" +import { Pos } from "../line/pos.js" +import { getLine } from "../line/utils_line.js" +import { makeChange } from "../model/changes.js" +import { ios, webkit } from "../util/browser.js" +import { elt } from "../util/dom.js" +import { lst, map } from "../util/misc.js" +import { signalLater } from "../util/operation_group.js" +import { splitLinesAuto } from "../util/feature_detection.js" + +import { indentLine } from "./indent.js" + +// This will be set to a {lineWise: bool, text: [string]} object, so +// that, when pasting, we know what kind of selections the copied +// text was made out of. +export let lastCopied = null + +export function setLastCopied(newLastCopied) { + lastCopied = newLastCopied +} + +export function applyTextInput(cm, inserted, deleted, sel, origin) { + let doc = cm.doc + cm.display.shift = false + if (!sel) sel = doc.sel + + let paste = cm.state.pasteIncoming || origin == "paste" + let textLines = splitLinesAuto(inserted), multiPaste = null + // When pasing N lines into N selections, insert one line per selection + if (paste && sel.ranges.length > 1) { + if (lastCopied && lastCopied.text.join("\n") == inserted) { + if (sel.ranges.length % lastCopied.text.length == 0) { + multiPaste = [] + for (let i = 0; i < lastCopied.text.length; i++) + multiPaste.push(doc.splitLines(lastCopied.text[i])) + } + } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) { + multiPaste = map(textLines, l => [l]) + } + } + + let updateInput + // Normal behavior is to insert the new text into every selection + for (let i = sel.ranges.length - 1; i >= 0; i--) { + let range = sel.ranges[i] + let from = range.from(), to = range.to() + if (range.empty()) { + if (deleted && deleted > 0) // Handle deletion + from = Pos(from.line, from.ch - deleted) + else if (cm.state.overwrite && !paste) // Handle overwrite + to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)) + else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted) + from = to = Pos(from.line, 0) + } + updateInput = cm.curOp.updateInput + let changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines, + origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")} + makeChange(cm.doc, changeEvent) + signalLater(cm, "inputRead", cm, changeEvent) + } + if (inserted && !paste) + triggerElectric(cm, inserted) + + ensureCursorVisible(cm) + cm.curOp.updateInput = updateInput + cm.curOp.typing = true + cm.state.pasteIncoming = cm.state.cutIncoming = false +} + +export function handlePaste(e, cm) { + let pasted = e.clipboardData && e.clipboardData.getData("Text") + if (pasted) { + e.preventDefault() + if (!cm.isReadOnly() && !cm.options.disableInput) + runInOp(cm, () => applyTextInput(cm, pasted, 0, null, "paste")) + return true + } +} + +export function triggerElectric(cm, inserted) { + // When an 'electric' character is inserted, immediately trigger a reindent + if (!cm.options.electricChars || !cm.options.smartIndent) return + let sel = cm.doc.sel + + for (let i = sel.ranges.length - 1; i >= 0; i--) { + let range = sel.ranges[i] + if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue + let mode = cm.getModeAt(range.head) + let indented = false + if (mode.electricChars) { + for (let j = 0; j < mode.electricChars.length; j++) + if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { + indented = indentLine(cm, range.head.line, "smart") + break + } + } else if (mode.electricInput) { + if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch))) + indented = indentLine(cm, range.head.line, "smart") + } + if (indented) signalLater(cm, "electricInput", cm, range.head.line) + } +} + +export function copyableRanges(cm) { + let text = [], ranges = [] + for (let i = 0; i < cm.doc.sel.ranges.length; i++) { + let line = cm.doc.sel.ranges[i].head.line + let lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)} + ranges.push(lineRange) + text.push(cm.getRange(lineRange.anchor, lineRange.head)) + } + return {text: text, ranges: ranges} +} + +export function disableBrowserMagic(field, spellcheck) { + field.setAttribute("autocorrect", "off") + field.setAttribute("autocapitalize", "off") + field.setAttribute("spellcheck", !!spellcheck) +} + +export function hiddenTextarea() { + let te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none") + let div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;") + // The textarea is kept positioned near the cursor to prevent the + // fact that it'll be scrolled into view on input from scrolling + // our fake cursor out of view. On webkit, when wrap=off, paste is + // very slow. So make the area wide instead. + if (webkit) te.style.width = "1000px" + else te.setAttribute("wrap", "off") + // If border: 0; -- iOS fails to open keyboard (issue #1287) + if (ios) te.style.border = "1px solid black" + disableBrowserMagic(te) + return div +} diff --git a/modules/editor/codemirror/src/line/line_data.js b/modules/editor/codemirror/src/line/line_data.js @@ -0,0 +1,337 @@ +import { getOrder } from "../util/bidi.js" +import { ie, ie_version, webkit } from "../util/browser.js" +import { elt, eltP, joinClasses } from "../util/dom.js" +import { eventMixin, signal } from "../util/event.js" +import { hasBadBidiRects, zeroWidthElement } from "../util/feature_detection.js" +import { lst, spaceStr } from "../util/misc.js" + +import { getLineStyles } from "./highlight.js" +import { attachMarkedSpans, compareCollapsedMarkers, detachMarkedSpans, lineIsHidden, visualLineContinued } from "./spans.js" +import { getLine, lineNo, updateLineHeight } from "./utils_line.js" + +// LINE DATA STRUCTURE + +// Line objects. These hold state related to a line, including +// highlighting info (the styles array). +export class Line { + constructor(text, markedSpans, estimateHeight) { + this.text = text + attachMarkedSpans(this, markedSpans) + this.height = estimateHeight ? estimateHeight(this) : 1 + } + + lineNo() { return lineNo(this) } +} +eventMixin(Line) + +// Change the content (text, markers) of a line. Automatically +// invalidates cached information and tries to re-estimate the +// line's height. +export function updateLine(line, text, markedSpans, estimateHeight) { + line.text = text + if (line.stateAfter) line.stateAfter = null + if (line.styles) line.styles = null + if (line.order != null) line.order = null + detachMarkedSpans(line) + attachMarkedSpans(line, markedSpans) + let estHeight = estimateHeight ? estimateHeight(line) : 1 + if (estHeight != line.height) updateLineHeight(line, estHeight) +} + +// Detach a line from the document tree and its markers. +export function cleanUpLine(line) { + line.parent = null + detachMarkedSpans(line) +} + +// Convert a style as returned by a mode (either null, or a string +// containing one or more styles) to a CSS style. This is cached, +// and also looks for line-wide styles. +let styleToClassCache = {}, styleToClassCacheWithMode = {} +function interpretTokenStyle(style, options) { + if (!style || /^\s*$/.test(style)) return null + let cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache + return cache[style] || + (cache[style] = style.replace(/\S+/g, "cm-$&")) +} + +// Render the DOM representation of the text of a line. Also builds +// up a 'line map', which points at the DOM nodes that represent +// specific stretches of text, and is used by the measuring code. +// The returned object contains the DOM node, this map, and +// information about line-wide styles that were set by the mode. +export function buildLineContent(cm, lineView) { + // The padding-right forces the element to have a 'border', which + // is needed on Webkit to be able to get line-level bounding + // rectangles for it (in measureChar). + let content = eltP("span", null, null, webkit ? "padding-right: .1px" : null) + let builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content, + col: 0, pos: 0, cm: cm, + trailingSpace: false, + splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")} + lineView.measure = {} + + // Iterate over the logical lines that make up this visual line. + for (let i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { + let line = i ? lineView.rest[i - 1] : lineView.line, order + builder.pos = 0 + builder.addToken = buildToken + // Optionally wire in some hacks into the token-rendering + // algorithm, to deal with browser quirks. + if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction))) + builder.addToken = buildTokenBadBidi(builder.addToken, order) + builder.map = [] + let allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line) + insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)) + if (line.styleClasses) { + if (line.styleClasses.bgClass) + builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "") + if (line.styleClasses.textClass) + builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "") + } + + // Ensure at least a single node is present, for measuring. + if (builder.map.length == 0) + builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))) + + // Store the map and a cache object for the current logical line + if (i == 0) { + lineView.measure.map = builder.map + lineView.measure.cache = {} + } else { + ;(lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map) + ;(lineView.measure.caches || (lineView.measure.caches = [])).push({}) + } + } + + // See issue #2901 + if (webkit) { + let last = builder.content.lastChild + if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab"))) + builder.content.className = "cm-tab-wrap-hack" + } + + signal(cm, "renderLine", cm, lineView.line, builder.pre) + if (builder.pre.className) + builder.textClass = joinClasses(builder.pre.className, builder.textClass || "") + + return builder +} + +export function defaultSpecialCharPlaceholder(ch) { + let token = elt("span", "\u2022", "cm-invalidchar") + token.title = "\\u" + ch.charCodeAt(0).toString(16) + token.setAttribute("aria-label", token.title) + return token +} + +// Build up the DOM representation for a single token, and add it to +// the line map. Takes care to render special characters separately. +function buildToken(builder, text, style, startStyle, endStyle, title, css) { + if (!text) return + let displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text + let special = builder.cm.state.specialChars, mustWrap = false + let content + if (!special.test(text)) { + builder.col += text.length + content = document.createTextNode(displayText) + builder.map.push(builder.pos, builder.pos + text.length, content) + if (ie && ie_version < 9) mustWrap = true + builder.pos += text.length + } else { + content = document.createDocumentFragment() + let pos = 0 + while (true) { + special.lastIndex = pos + let m = special.exec(text) + let skipped = m ? m.index - pos : text.length - pos + if (skipped) { + let txt = document.createTextNode(displayText.slice(pos, pos + skipped)) + if (ie && ie_version < 9) content.appendChild(elt("span", [txt])) + else content.appendChild(txt) + builder.map.push(builder.pos, builder.pos + skipped, txt) + builder.col += skipped + builder.pos += skipped + } + if (!m) break + pos += skipped + 1 + let txt + if (m[0] == "\t") { + let tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize + txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")) + txt.setAttribute("role", "presentation") + txt.setAttribute("cm-text", "\t") + builder.col += tabWidth + } else if (m[0] == "\r" || m[0] == "\n") { + txt = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar")) + txt.setAttribute("cm-text", m[0]) + builder.col += 1 + } else { + txt = builder.cm.options.specialCharPlaceholder(m[0]) + txt.setAttribute("cm-text", m[0]) + if (ie && ie_version < 9) content.appendChild(elt("span", [txt])) + else content.appendChild(txt) + builder.col += 1 + } + builder.map.push(builder.pos, builder.pos + 1, txt) + builder.pos++ + } + } + builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32 + if (style || startStyle || endStyle || mustWrap || css) { + let fullStyle = style || "" + if (startStyle) fullStyle += startStyle + if (endStyle) fullStyle += endStyle + let token = elt("span", [content], fullStyle, css) + if (title) token.title = title + return builder.content.appendChild(token) + } + builder.content.appendChild(content) +} + +function splitSpaces(text, trailingBefore) { + if (text.length > 1 && !/ /.test(text)) return text + let spaceBefore = trailingBefore, result = "" + for (let i = 0; i < text.length; i++) { + let ch = text.charAt(i) + if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32)) + ch = "\u00a0" + result += ch + spaceBefore = ch == " " + } + return result +} + +// Work around nonsense dimensions being reported for stretches of +// right-to-left text. +function buildTokenBadBidi(inner, order) { + return (builder, text, style, startStyle, endStyle, title, css) => { + style = style ? style + " cm-force-border" : "cm-force-border" + let start = builder.pos, end = start + text.length + for (;;) { + // Find the part that overlaps with the start of this text + let part + for (let i = 0; i < order.length; i++) { + part = order[i] + if (part.to > start && part.from <= start) break + } + if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css) + inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css) + startStyle = null + text = text.slice(part.to - start) + start = part.to + } + } +} + +function buildCollapsedSpan(builder, size, marker, ignoreWidget) { + let widget = !ignoreWidget && marker.widgetNode + if (widget) builder.map.push(builder.pos, builder.pos + size, widget) + if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { + if (!widget) + widget = builder.content.appendChild(document.createElement("span")) + widget.setAttribute("cm-marker", marker.id) + } + if (widget) { + builder.cm.display.input.setUneditable(widget) + builder.content.appendChild(widget) + } + builder.pos += size + builder.trailingSpace = false +} + +// Outputs a number of spans to make up a line, taking highlighting +// and marked text into account. +function insertLineContent(line, builder, styles) { + let spans = line.markedSpans, allText = line.text, at = 0 + if (!spans) { + for (let i = 1; i < styles.length; i+=2) + builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options)) + return + } + + let len = allText.length, pos = 0, i = 1, text = "", style, css + let nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed + for (;;) { + if (nextChange == pos) { // Update current marker set + spanStyle = spanEndStyle = spanStartStyle = title = css = "" + collapsed = null; nextChange = Infinity + let foundBookmarks = [], endStyles + for (let j = 0; j < spans.length; ++j) { + let sp = spans[j], m = sp.marker + if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { + foundBookmarks.push(m) + } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { + if (sp.to != null && sp.to != pos && nextChange > sp.to) { + nextChange = sp.to + spanEndStyle = "" + } + if (m.className) spanStyle += " " + m.className + if (m.css) css = (css ? css + ";" : "") + m.css + if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle + if (m.endStyle && sp.to == nextChange) (endStyles || (endStyles = [])).push(m.endStyle, sp.to) + if (m.title && !title) title = m.title + if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) + collapsed = sp + } else if (sp.from > pos && nextChange > sp.from) { + nextChange = sp.from + } + } + if (endStyles) for (let j = 0; j < endStyles.length; j += 2) + if (endStyles[j + 1] == nextChange) spanEndStyle += " " + endStyles[j] + + if (!collapsed || collapsed.from == pos) for (let j = 0; j < foundBookmarks.length; ++j) + buildCollapsedSpan(builder, 0, foundBookmarks[j]) + if (collapsed && (collapsed.from || 0) == pos) { + buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, + collapsed.marker, collapsed.from == null) + if (collapsed.to == null) return + if (collapsed.to == pos) collapsed = false + } + } + if (pos >= len) break + + let upto = Math.min(len, nextChange) + while (true) { + if (text) { + let end = pos + text.length + if (!collapsed) { + let tokenText = end > upto ? text.slice(0, upto - pos) : text + builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, + spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css) + } + if (end >= upto) {text = text.slice(upto - pos); pos = upto; break} + pos = end + spanStartStyle = "" + } + text = allText.slice(at, at = styles[i++]) + style = interpretTokenStyle(styles[i++], builder.cm.options) + } + } +} + + +// These objects are used to represent the visible (currently drawn) +// part of the document. A LineView may correspond to multiple +// logical lines, if those are connected by collapsed ranges. +export function LineView(doc, line, lineN) { + // The starting line + this.line = line + // Continuing lines, if any + this.rest = visualLineContinued(line) + // Number of logical lines in this visual line + this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1 + this.node = this.text = null + this.hidden = lineIsHidden(doc, line) +} + +// Create a range of LineView objects for the given lines. +export function buildViewArray(cm, from, to) { + let array = [], nextPos + for (let pos = from; pos < to; pos = nextPos) { + let view = new LineView(cm.doc, getLine(cm.doc, pos), pos) + nextPos = pos + view.size + array.push(view) + } + return array +} diff --git a/modules/editor/codemirror/src/model/selection.min.js b/modules/editor/codemirror/src/model/selection.min.js @@ -0,0 +1,82 @@ +import { cmp, copyPos, equalCursorPos, maxPos, minPos } from "../line/pos.js" +import { indexOf } from "../util/misc.js" + +// Selection objects are immutable. A new one is created every time +// the selection changes. A selection is one or more non-overlapping +// (and non-touching) ranges, sorted, and an integer that indicates +// which one is the primary selection (the one that's scrolled into +// view, that getCursor returns, etc). +export class Selection { + constructor(ranges, primIndex) { + this.ranges = ranges + this.primIndex = primIndex + } + + primary() { return this.ranges[this.primIndex] } + + equals(other) { + if (other == this) return true + if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false + for (let i = 0; i < this.ranges.length; i++) { + let here = this.ranges[i], there = other.ranges[i] + if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) return false + } + return true + } + + deepCopy() { + let out = [] + for (let i = 0; i < this.ranges.length; i++) + out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)) + return new Selection(out, this.primIndex) + } + + somethingSelected() { + for (let i = 0; i < this.ranges.length; i++) + if (!this.ranges[i].empty()) return true + return false + } + + contains(pos, end) { + if (!end) end = pos + for (let i = 0; i < this.ranges.length; i++) { + let range = this.ranges[i] + if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) + return i + } + return -1 + } +} + +export class Range { + constructor(anchor, head) { + this.anchor = anchor; this.head = head + } + + from() { return minPos(this.anchor, this.head) } + to() { return maxPos(this.anchor, this.head) } + empty() { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch } +} + +// Take an unsorted, potentially overlapping set of ranges, and +// build a selection out of it. 'Consumes' ranges array (modifying +// it). +export function normalizeSelection(ranges, primIndex) { + let prim = ranges[primIndex] + ranges.sort((a, b) => cmp(a.from(), b.from())) + primIndex = indexOf(ranges, prim) + for (let i = 1; i < ranges.length; i++) { + let cur = ranges[i], prev = ranges[i - 1] + if (cmp(prev.to(), cur.from()) >= 0) { + let from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()) + let inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head + if (i <= primIndex) --primIndex + ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)) + } + } + return new Selection(ranges, primIndex) +} + +export function simpleSelection(anchor, head) { + return new Selection([new Range(anchor, head || anchor)], 0) +} diff --git a/modules/editor/codemirror/src/modes.min.js b/modules/editor/codemirror/src/modes.min.js @@ -0,0 +1,96 @@ +import { copyObj, createObj } from "./util/misc.js" + +// Known modes, by name and by MIME +export let modes = {}, mimeModes = {} + +// Extra arguments are stored as the mode's dependencies, which is +// used by (legacy) mechanisms like loadmode.js to automatically +// load a mode. (Preferred mechanism is the require/define calls.) +export function defineMode(name, mode) { + if (arguments.length > 2) + mode.dependencies = Array.prototype.slice.call(arguments, 2) + modes[name] = mode +} + +export function defineMIME(mime, spec) { + mimeModes[mime] = spec +} + +// Given a MIME type, a {name, ...options} config object, or a name +// string, return a mode config object. +export function resolveMode(spec) { + if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { + spec = mimeModes[spec] + } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { + let found = mimeModes[spec.name] + if (typeof found == "string") found = {name: found} + spec = createObj(found, spec) + spec.name = found.name + } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { + return resolveMode("application/xml") + } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) { + return resolveMode("application/json") + } + if (typeof spec == "string") return {name: spec} + else return spec || {name: "null"} +} + +// Given a mode spec (anything that resolveMode accepts), find and +// initialize an actual mode object. +export function getMode(options, spec) { + spec = resolveMode(spec) + let mfactory = modes[spec.name] + if (!mfactory) return getMode(options, "text/plain") + let modeObj = mfactory(options, spec) + if (modeExtensions.hasOwnProperty(spec.name)) { + let exts = modeExtensions[spec.name] + for (let prop in exts) { + if (!exts.hasOwnProperty(prop)) continue + if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop] + modeObj[prop] = exts[prop] + } + } + modeObj.name = spec.name + if (spec.helperType) modeObj.helperType = spec.helperType + if (spec.modeProps) for (let prop in spec.modeProps) + modeObj[prop] = spec.modeProps[prop] + + return modeObj +} + +// This can be used to attach properties to mode objects from +// outside the actual mode definition. +export let modeExtensions = {} +export function extendMode(mode, properties) { + let exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}) + copyObj(properties, exts) +} + +export function copyState(mode, state) { + if (state === true) return state + if (mode.copyState) return mode.copyState(state) + let nstate = {} + for (let n in state) { + let val = state[n] + if (val instanceof Array) val = val.concat([]) + nstate[n] = val + } + return nstate +} + +// Given a mode and a state (for that mode), find the inner mode and +// state at the position that the state refers to. +export function innerMode(mode, state) { + let info + while (mode.innerMode) { + info = mode.innerMode(state) + if (!info || info.mode == mode) break + state = info.state + mode = info.mode + } + return info || {mode: mode, state: state} +} + +export function startState(mode, a1, a2) { + return mode.startState ? mode.startState(a1, a2) : true +} diff --git a/modules/editor/codemirror/src/util/dom.js b/modules/editor/codemirror/src/util/dom.js @@ -0,0 +1,97 @@ +import { ie, ios } from "./browser.js" + +export function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") } + +export let rmClass = function(node, cls) { + let current = node.className + let match = classTest(cls).exec(current) + if (match) { + let after = current.slice(match.index + match[0].length) + node.className = current.slice(0, match.index) + (after ? match[1] + after : "") + } +} + +export function removeChildren(e) { + for (let count = e.childNodes.length; count > 0; --count) + e.removeChild(e.firstChild) + return e +} + +export function removeChildrenAndAdd(parent, e) { + return removeChildren(parent).appendChild(e) +} + +export function elt(tag, content, className, style) { + let e = document.createElement(tag) + if (className) e.className = className + if (style) e.style.cssText = style + if (typeof content == "string") e.appendChild(document.createTextNode(content)) + else if (content) for (let i = 0; i < content.length; ++i) e.appendChild(content[i]) + return e +} +// wrapper for elt, which removes the elt from the accessibility tree +export function eltP(tag, content, className, style) { + let e = elt(tag, content, className, style) + e.setAttribute("role", "presentation") + return e +} + +export let range +if (document.createRange) range = function(node, start, end, endNode) { + let r = document.createRange() + r.setEnd(endNode || node, end) + r.setStart(node, start) + return r +} +else range = function(node, start, end) { + let r = document.body.createTextRange() + try { r.moveToElementText(node.parentNode) } + catch(e) { return r } + r.collapse(true) + r.moveEnd("character", end) + r.moveStart("character", start) + return r +} + +export function contains(parent, child) { + if (child.nodeType == 3) // Android browser always returns false when child is a textnode + child = child.parentNode + if (parent.contains) + return parent.contains(child) + do { + if (child.nodeType == 11) child = child.host + if (child == parent) return true + } while (child = child.parentNode) +} + +export function activeElt() { + // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement. + // IE < 10 will throw when accessed while the page is loading or in an iframe. + // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable. + let activeElement + try { + activeElement = document.activeElement + } catch(e) { + activeElement = document.body || null + } + while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement) + activeElement = activeElement.shadowRoot.activeElement + return activeElement +} + +export function addClass(node, cls) { + let current = node.className + if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls +} +export function joinClasses(a, b) { + let as = a.split(" ") + for (let i = 0; i < as.length; i++) + if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i] + return b +} + +export let selectInput = function(node) { node.select() } +if (ios) // Mobile Safari apparently has a bug where select() is broken. + selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length } +else if (ie) // Suppress mysterious IE10 errors + selectInput = function(node) { try { node.select() } catch(_e) {} } diff --git a/modules/editor/codemirror/src/util/dom.min.js b/modules/editor/codemirror/src/util/dom.min.js @@ -0,0 +1,97 @@ +import { ie, ios } from "./browser.js" + +export function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") } + +export let rmClass = function(node, cls) { + let current = node.className + let match = classTest(cls).exec(current) + if (match) { + let after = current.slice(match.index + match[0].length) + node.className = current.slice(0, match.index) + (after ? match[1] + after : "") + } +} + +export function removeChildren(e) { + for (let count = e.childNodes.length; count > 0; --count) + e.removeChild(e.firstChild) + return e +} + +export function removeChildrenAndAdd(parent, e) { + return removeChildren(parent).appendChild(e) +} + +export function elt(tag, content, className, style) { + let e = document.createElement(tag) + if (className) e.className = className + if (style) e.style.cssText = style + if (typeof content == "string") e.appendChild(document.createTextNode(content)) + else if (content) for (let i = 0; i < content.length; ++i) e.appendChild(content[i]) + return e +} +// wrapper for elt, which removes the elt from the accessibility tree +export function eltP(tag, content, className, style) { + let e = elt(tag, content, className, style) + e.setAttribute("role", "presentation") + return e +} + +export let range +if (document.createRange) range = function(node, start, end, endNode) { + let r = document.createRange() + r.setEnd(endNode || node, end) + r.setStart(node, start) + return r +} +else range = function(node, start, end) { + let r = document.body.createTextRange() + try { r.moveToElementText(node.parentNode) } + catch(e) { return r } + r.collapse(true) + r.moveEnd("character", end) + r.moveStart("character", start) + return r +} + +export function contains(parent, child) { + if (child.nodeType == 3) // Android browser always returns false when child is a textnode + child = child.parentNode + if (parent.contains) + return parent.contains(child) + do { + if (child.nodeType == 11) child = child.host + if (child == parent) return true + } while (child = child.parentNode) +} + +export function activeElt() { + // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement. + // IE < 10 will throw when accessed while the page is loading or in an iframe. + // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable. + let activeElement + try { + activeElement = document.activeElement + } catch(e) { + activeElement = document.body || null + } + while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement) + activeElement = activeElement.shadowRoot.activeElement + return activeElement +} + +export function addClass(node, cls) { + let current = node.className + if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls +} +export function joinClasses(a, b) { + let as = a.split(" ") + for (let i = 0; i < as.length; i++) + if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i] + return b +} + +export let selectInput = function(node) { node.select() } +if (ios) // Mobile Safari apparently has a bug where select() is broken. + selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length } +else if (ie) // Suppress mysterious IE10 errors + selectInput = function(node) { try { node.select() } catch(_e) {} } diff --git a/modules/editor/codemirror/src/util/operation_group.min.js b/modules/editor/codemirror/src/util/operation_group.min.js @@ -0,0 +1,72 @@ +import { getHandlers } from "./event.js" + +let operationGroup = null + +export function pushOperation(op) { + if (operationGroup) { + operationGroup.ops.push(op) + } else { + op.ownsGroup = operationGroup = { + ops: [op], + delayedCallbacks: [] + } + } +} + +function fireCallbacksForOps(group) { + // Calls delayed callbacks and cursorActivity handlers until no + // new ones appear + let callbacks = group.delayedCallbacks, i = 0 + do { + for (; i < callbacks.length; i++) + callbacks[i].call(null) + for (let j = 0; j < group.ops.length; j++) { + let op = group.ops[j] + if (op.cursorActivityHandlers) + while (op.cursorActivityCalled < op.cursorActivityHandlers.length) + op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm) + } + } while (i < callbacks.length) +} + +export function finishOperation(op, endCb) { + let group = op.ownsGroup + if (!group) return + + try { fireCallbacksForOps(group) } + finally { + operationGroup = null + endCb(group) + } +} + +let orphanDelayedCallbacks = null + +// Often, we want to signal events at a point where we are in the +// middle of some work, but don't want the handler to start calling +// other methods on the editor, which might be in an inconsistent +// state or simply not expect any other events to happen. +// signalLater looks whether there are any handlers, and schedules +// them to be executed when the last operation ends, or, if no +// operation is active, when a timeout fires. +export function signalLater(emitter, type /*, values...*/) { + let arr = getHandlers(emitter, type) + if (!arr.length) return + let args = Array.prototype.slice.call(arguments, 2), list + if (operationGroup) { + list = operationGroup.delayedCallbacks + } else if (orphanDelayedCallbacks) { + list = orphanDelayedCallbacks + } else { + list = orphanDelayedCallbacks = [] + setTimeout(fireOrphanDelayed, 0) + } + for (let i = 0; i < arr.length; ++i) + list.push(() => arr[i].apply(null, args)) +} + +function fireOrphanDelayed() { + let delayed = orphanDelayedCallbacks + orphanDelayedCallbacks = null + for (let i = 0; i < delayed.length; ++i) delayed[i]() +} diff --git a/modules/editor/codemirror/test/lint.js b/modules/editor/codemirror/test/lint.js @@ -0,0 +1,20 @@ +var blint = require("blint"); + +["mode", "lib", "addon", "keymap"].forEach(function(dir) { + blint.checkDir(dir, { + browser: true, + allowedGlobals: ["CodeMirror", "define", "test", "requirejs"], + ecmaVersion: 5, + tabs: dir == "lib" + }); +}); + +["src"].forEach(function(dir) { + blint.checkDir(dir, { + browser: true, + ecmaVersion: 6, + semicolons: false + }); +}); + +module.exports = {ok: blint.success()}; diff --git a/modules/editor/codemirror/test/sql-hint-test.js b/modules/editor/codemirror/test/sql-hint-test.js @@ -0,0 +1,238 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function() { + var Pos = CodeMirror.Pos; + + var simpleTables = { + "users": ["name", "score", "birthDate"], + "xcountries": ["name", "population", "size"] + }; + + var schemaTables = { + "schema.users": ["name", "score", "birthDate"], + "schema.countries": ["name", "population", "size"] + }; + + var displayTextTables = [{ + text: "mytable", + displayText: "mytable | The main table", + columns: [{text: "id", displayText: "id | Unique ID"}, + {text: "name", displayText: "name | The name"}] + }]; + + namespace = "sql-hint_"; + + function test(name, spec) { + testCM(name, function(cm) { + cm.setValue(spec.value); + cm.setCursor(spec.cursor); + var completion = CodeMirror.hint.sql(cm, {tables: spec.tables}); + if (!deepCompare(completion.list, spec.list)) + throw new Failure("Wrong completion results " + JSON.stringify(completion.list) + " vs " + JSON.stringify(spec.list)); + eqCharPos(completion.from, spec.from); + eqCharPos(completion.to, spec.to); + }, { + value: spec.value, + mode: spec.mode || "text/x-mysql" + }); + } + + test("keywords", { + value: "SEL", + cursor: Pos(0, 3), + list: ["SELECT"], + from: Pos(0, 0), + to: Pos(0, 3) + }); + + test("from", { + value: "SELECT * fr", + cursor: Pos(0, 11), + list: ["FROM"], + from: Pos(0, 9), + to: Pos(0, 11) + }); + + test("table", { + value: "SELECT xc", + cursor: Pos(0, 9), + tables: simpleTables, + list: ["xcountries"], + from: Pos(0, 7), + to: Pos(0, 9) + }); + + test("columns", { + value: "SELECT users.", + cursor: Pos(0, 13), + tables: simpleTables, + list: ["users.name", "users.score", "users.birthDate"], + from: Pos(0, 7), + to: Pos(0, 13) + }); + + test("singlecolumn", { + value: "SELECT users.na", + cursor: Pos(0, 15), + tables: simpleTables, + list: ["users.name"], + from: Pos(0, 7), + to: Pos(0, 15) + }); + + test("quoted", { + value: "SELECT `users`.`na", + cursor: Pos(0, 18), + tables: simpleTables, + list: ["`users`.`name`"], + from: Pos(0, 7), + to: Pos(0, 18) + }); + + test("doublequoted", { + value: "SELECT \"users\".\"na", + cursor: Pos(0, 18), + tables: simpleTables, + list: ["\"users\".\"name\""], + from: Pos(0, 7), + to: Pos(0, 18), + mode: "text/x-sqlite" + }); + + test("quotedcolumn", { + value: "SELECT users.`na", + cursor: Pos(0, 16), + tables: simpleTables, + list: ["`users`.`name`"], + from: Pos(0, 7), + to: Pos(0, 16) + }); + + test("doublequotedcolumn", { + value: "SELECT users.\"na", + cursor: Pos(0, 16), + tables: simpleTables, + list: ["\"users\".\"name\""], + from: Pos(0, 7), + to: Pos(0, 16), + mode: "text/x-sqlite" + }); + + test("schema", { + value: "SELECT schem", + cursor: Pos(0, 12), + tables: schemaTables, + list: ["schema.users", "schema.countries", + "SCHEMA", "SCHEMA_NAME", "SCHEMAS"], + from: Pos(0, 7), + to: Pos(0, 12) + }); + + test("schemaquoted", { + value: "SELECT `sch", + cursor: Pos(0, 11), + tables: schemaTables, + list: ["`schema`.`users`", "`schema`.`countries`"], + from: Pos(0, 7), + to: Pos(0, 11) + }); + + test("schemadoublequoted", { + value: "SELECT \"sch", + cursor: Pos(0, 11), + tables: schemaTables, + list: ["\"schema\".\"users\"", "\"schema\".\"countries\""], + from: Pos(0, 7), + to: Pos(0, 11), + mode: "text/x-sqlite" + }); + + test("schemacolumn", { + value: "SELECT schema.users.", + cursor: Pos(0, 20), + tables: schemaTables, + list: ["schema.users.name", + "schema.users.score", + "schema.users.birthDate"], + from: Pos(0, 7), + to: Pos(0, 20) + }); + + test("schemacolumnquoted", { + value: "SELECT `schema`.`users`.", + cursor: Pos(0, 24), + tables: schemaTables, + list: ["`schema`.`users`.`name`", + "`schema`.`users`.`score`", + "`schema`.`users`.`birthDate`"], + from: Pos(0, 7), + to: Pos(0, 24) + }); + + test("schemacolumndoublequoted", { + value: "SELECT \"schema\".\"users\".", + cursor: Pos(0, 24), + tables: schemaTables, + list: ["\"schema\".\"users\".\"name\"", + "\"schema\".\"users\".\"score\"", + "\"schema\".\"users\".\"birthDate\""], + from: Pos(0, 7), + to: Pos(0, 24), + mode: "text/x-sqlite" + }); + + test("displayText_table", { + value: "SELECT myt", + cursor: Pos(0, 10), + tables: displayTextTables, + list: [{text: "mytable", displayText: "mytable | The main table",}], + from: Pos(0, 7), + to: Pos(0, 10) + }); + + test("displayText_column", { + value: "SELECT mytable.", + cursor: Pos(0, 15), + tables: displayTextTables, + list: [{text: "mytable.id", displayText: "id | Unique ID"}, + {text: "mytable.name", displayText: "name | The name"}], + from: Pos(0, 7), + to: Pos(0, 15) + }); + + test("alias_complete", { + value: "SELECT t. FROM users t", + cursor: Pos(0, 9), + tables: simpleTables, + list: ["t.name", "t.score", "t.birthDate"], + from: Pos(0, 7), + to: Pos(0, 9) + }); + + test("alias_complete_with_displayText", { + value: "SELECT t. FROM mytable t", + cursor: Pos(0, 9), + tables: displayTextTables, + list: [{text: "t.id", displayText: "id | Unique ID"}, + {text: "t.name", displayText: "name | The name"}], + from: Pos(0, 7), + to: Pos(0, 9) + }) + + function deepCompare(a, b) { + if (a === b) return true + if (!(a && typeof a == "object") || + !(b && typeof b == "object")) return false + var array = Array.isArray(a) + if (Array.isArray(b) != array) return false + if (array) { + if (a.length != b.length) return false + for (var i = 0; i < a.length; i++) if (!deepCompare(a[i], b[i])) return false + } else { + for (var p in a) if (!(p in b) || !deepCompare(a[p], b[p])) return false + for (var p in b) if (!(p in a)) return false + } + return true + } +})(); diff --git a/modules/editor/codemirror/test/test.min.js b/modules/editor/codemirror/test/test.min.js @@ -0,0 +1,2550 @@ +var Pos = CodeMirror.Pos; + +CodeMirror.defaults.rtlMoveVisually = true; + +function forEach(arr, f) { + for (var i = 0, e = arr.length; i < e; ++i) f(arr[i], i); +} + +function addDoc(cm, width, height) { + var content = [], line = ""; + for (var i = 0; i < width; ++i) line += "x"; + for (var i = 0; i < height; ++i) content.push(line); + cm.setValue(content.join("\n")); +} + +function byClassName(elt, cls) { + if (elt.getElementsByClassName) return elt.getElementsByClassName(cls); + var found = [], re = new RegExp("\\b" + cls + "\\b"); + function search(elt) { + if (elt.nodeType == 3) return; + if (re.test(elt.className)) found.push(elt); + for (var i = 0, e = elt.childNodes.length; i < e; ++i) + search(elt.childNodes[i]); + } + search(elt); + return found; +} + +var ie_lt8 = /MSIE [1-7]\b/.test(navigator.userAgent); +var ie_lt9 = /MSIE [1-8]\b/.test(navigator.userAgent); +var mac = /Mac/.test(navigator.platform); +var phantom = /PhantomJS/.test(navigator.userAgent); +var opera = /Opera\/\./.test(navigator.userAgent); +var opera_version = opera && navigator.userAgent.match(/Version\/(\d+\.\d+)/); +if (opera_version) opera_version = Number(opera_version); +var opera_lt10 = opera && (!opera_version || opera_version < 10); + +namespace = "core_"; + +test("core_fromTextArea", function() { + var te = document.getElementById("code"); + te.value = "CONTENT"; + var cm = CodeMirror.fromTextArea(te); + is(!te.offsetHeight); + eq(cm.getValue(), "CONTENT"); + cm.setValue("foo\nbar"); + eq(cm.getValue(), "foo\nbar"); + cm.save(); + is(/^foo\r?\nbar$/.test(te.value)); + cm.setValue("xxx"); + cm.toTextArea(); + is(te.offsetHeight); + eq(te.value, "xxx"); +}); + +testCM("getRange", function(cm) { + eq(cm.getLine(0), "1234"); + eq(cm.getLine(1), "5678"); + eq(cm.getLine(2), null); + eq(cm.getLine(-1), null); + eq(cm.getRange(Pos(0, 0), Pos(0, 3)), "123"); + eq(cm.getRange(Pos(0, -1), Pos(0, 200)), "1234"); + eq(cm.getRange(Pos(0, 2), Pos(1, 2)), "34\n56"); + eq(cm.getRange(Pos(1, 2), Pos(100, 0)), "78"); +}, {value: "1234\n5678"}); + +testCM("replaceRange", function(cm) { + eq(cm.getValue(), ""); + cm.replaceRange("foo\n", Pos(0, 0)); + eq(cm.getValue(), "foo\n"); + cm.replaceRange("a\nb", Pos(0, 1)); + eq(cm.getValue(), "fa\nboo\n"); + eq(cm.lineCount(), 3); + cm.replaceRange("xyzzy", Pos(0, 0), Pos(1, 1)); + eq(cm.getValue(), "xyzzyoo\n"); + cm.replaceRange("abc", Pos(0, 0), Pos(10, 0)); + eq(cm.getValue(), "abc"); + eq(cm.lineCount(), 1); +}); + +testCM("selection", function(cm) { + cm.setSelection(Pos(0, 4), Pos(2, 2)); + is(cm.somethingSelected()); + eq(cm.getSelection(), "11\n222222\n33"); + eqCursorPos(cm.getCursor(false), Pos(2, 2)); + eqCursorPos(cm.getCursor(true), Pos(0, 4)); + cm.setSelection(Pos(1, 0)); + is(!cm.somethingSelected()); + eq(cm.getSelection(), ""); + eqCursorPos(cm.getCursor(true), Pos(1, 0)); + cm.replaceSelection("abc", "around"); + eq(cm.getSelection(), "abc"); + eq(cm.getValue(), "111111\nabc222222\n333333"); + cm.replaceSelection("def", "end"); + eq(cm.getSelection(), ""); + eqCursorPos(cm.getCursor(true), Pos(1, 3)); + cm.setCursor(Pos(2, 1)); + eqCursorPos(cm.getCursor(true), Pos(2, 1)); + cm.setCursor(1, 2); + eqCursorPos(cm.getCursor(true), Pos(1, 2)); +}, {value: "111111\n222222\n333333"}); + +testCM("extendSelection", function(cm) { + cm.setExtending(true); + addDoc(cm, 10, 10); + cm.setSelection(Pos(3, 5)); + eqCursorPos(cm.getCursor("head"), Pos(3, 5)); + eqCursorPos(cm.getCursor("anchor"), Pos(3, 5)); + cm.setSelection(Pos(2, 5), Pos(5, 5)); + eqCursorPos(cm.getCursor("head"), Pos(5, 5)); + eqCursorPos(cm.getCursor("anchor"), Pos(2, 5)); + eqCursorPos(cm.getCursor("start"), Pos(2, 5)); + eqCursorPos(cm.getCursor("end"), Pos(5, 5)); + cm.setSelection(Pos(5, 5), Pos(2, 5)); + eqCursorPos(cm.getCursor("head"), Pos(2, 5)); + eqCursorPos(cm.getCursor("anchor"), Pos(5, 5)); + eqCursorPos(cm.getCursor("start"), Pos(2, 5)); + eqCursorPos(cm.getCursor("end"), Pos(5, 5)); + cm.extendSelection(Pos(3, 2)); + eqCursorPos(cm.getCursor("head"), Pos(3, 2)); + eqCursorPos(cm.getCursor("anchor"), Pos(5, 5)); + cm.extendSelection(Pos(6, 2)); + eqCursorPos(cm.getCursor("head"), Pos(6, 2)); + eqCursorPos(cm.getCursor("anchor"), Pos(5, 5)); + cm.extendSelection(Pos(6, 3), Pos(6, 4)); + eqCursorPos(cm.getCursor("head"), Pos(6, 4)); + eqCursorPos(cm.getCursor("anchor"), Pos(5, 5)); + cm.extendSelection(Pos(0, 3), Pos(0, 4)); + eqCursorPos(cm.getCursor("head"), Pos(0, 3)); + eqCursorPos(cm.getCursor("anchor"), Pos(5, 5)); + cm.extendSelection(Pos(4, 5), Pos(6, 5)); + eqCursorPos(cm.getCursor("head"), Pos(6, 5)); + eqCursorPos(cm.getCursor("anchor"), Pos(4, 5)); + cm.setExtending(false); + cm.extendSelection(Pos(0, 3), Pos(0, 4)); + eqCursorPos(cm.getCursor("head"), Pos(0, 3)); + eqCursorPos(cm.getCursor("anchor"), Pos(0, 4)); +}); + +testCM("lines", function(cm) { + eq(cm.getLine(0), "111111"); + eq(cm.getLine(1), "222222"); + eq(cm.getLine(-1), null); + cm.replaceRange("", Pos(1, 0), Pos(2, 0)) + cm.replaceRange("abc", Pos(1, 0), Pos(1)); + eq(cm.getValue(), "111111\nabc"); +}, {value: "111111\n222222\n333333"}); + +testCM("indent", function(cm) { + cm.indentLine(1); + eq(cm.getLine(1), " blah();"); + cm.setOption("indentUnit", 8); + cm.indentLine(1); + eq(cm.getLine(1), "\tblah();"); + cm.setOption("indentUnit", 10); + cm.setOption("tabSize", 4); + cm.indentLine(1); + eq(cm.getLine(1), "\t\t blah();"); +}, {value: "if (x) {\nblah();\n}", indentUnit: 3, indentWithTabs: true, tabSize: 8}); + +testCM("indentByNumber", function(cm) { + cm.indentLine(0, 2); + eq(cm.getLine(0), " foo"); + cm.indentLine(0, -200); + eq(cm.getLine(0), "foo"); + cm.setSelection(Pos(0, 0), Pos(1, 2)); + cm.indentSelection(3); + eq(cm.getValue(), " foo\n bar\nbaz"); +}, {value: "foo\nbar\nbaz"}); + +test("core_defaults", function() { + var defsCopy = {}, defs = CodeMirror.defaults; + for (var opt in defs) defsCopy[opt] = defs[opt]; + defs.indentUnit = 5; + defs.value = "uu"; + defs.indentWithTabs = true; + defs.tabindex = 55; + var place = document.getElementById("testground"), cm = CodeMirror(place); + try { + eq(cm.getOption("indentUnit"), 5); + cm.setOption("indentUnit", 10); + eq(defs.indentUnit, 5); + eq(cm.getValue(), "uu"); + eq(cm.getOption("indentWithTabs"), true); + eq(cm.getInputField().tabIndex, 55); + } + finally { + for (var opt in defsCopy) defs[opt] = defsCopy[opt]; + place.removeChild(cm.getWrapperElement()); + } +}); + +testCM("lineInfo", function(cm) { + eq(cm.lineInfo(-1), null); + var mark = document.createElement("span"); + var lh = cm.setGutterMarker(1, "FOO", mark); + var info = cm.lineInfo(1); + eq(info.text, "222222"); + eq(info.gutterMarkers.FOO, mark); + eq(info.line, 1); + eq(cm.lineInfo(2).gutterMarkers, null); + cm.setGutterMarker(lh, "FOO", null); + eq(cm.lineInfo(1).gutterMarkers, null); + cm.setGutterMarker(1, "FOO", mark); + cm.setGutterMarker(0, "FOO", mark); + cm.clearGutter("FOO"); + eq(cm.lineInfo(0).gutterMarkers, null); + eq(cm.lineInfo(1).gutterMarkers, null); +}, {value: "111111\n222222\n333333"}); + +testCM("coords", function(cm) { + cm.setSize(null, 100); + addDoc(cm, 32, 200); + var top = cm.charCoords(Pos(0, 0)); + var bot = cm.charCoords(Pos(200, 30)); + is(top.left < bot.left); + is(top.top < bot.top); + is(top.top < top.bottom); + cm.scrollTo(null, 100); + var top2 = cm.charCoords(Pos(0, 0)); + is(top.top > top2.top); + eq(top.left, top2.left); +}); + +testCM("coordsChar", function(cm) { + addDoc(cm, 35, 70); + for (var i = 0; i < 2; ++i) { + var sys = i ? "local" : "page"; + for (var ch = 0; ch <= 35; ch += 5) { + for (var line = 0; line < 70; line += 5) { + cm.setCursor(line, ch); + var coords = cm.charCoords(Pos(line, ch), sys); + var pos = cm.coordsChar({left: coords.left + 1, top: coords.top + 1}, sys); + eqCharPos(pos, Pos(line, ch)); + } + } + } +}, {lineNumbers: true}); + +testCM("coordsCharBidi", function(cm) { + addDoc(cm, 35, 70); + // Put an rtl character into each line to trigger the bidi code path in coordsChar + cm.setValue(cm.getValue().replace(/\bx/g, 'و')) + for (var i = 0; i < 2; ++i) { + var sys = i ? "local" : "page"; + for (var ch = 2; ch <= 35; ch += 5) { + for (var line = 0; line < 70; line += 5) { + cm.setCursor(line, ch); + var coords = cm.charCoords(Pos(line, ch), sys); + var pos = cm.coordsChar({left: coords.left + 1, top: coords.top + 1}, sys); + eqCharPos(pos, Pos(line, ch)); + } + } + } +}, {lineNumbers: true}); + +testCM("badBidiOptimization", function(cm) { + var coords = cm.charCoords(Pos(0, 34)) + eqCharPos(cm.coordsChar({left: coords.right, top: coords.top + 2}), Pos(0, 34)) +}, {value: "----------<p class=\"title\">هل يمكنك اختيار مستوى قسط التأمين الذي ترغب بدفعه؟</p>"}) + +testCM("posFromIndex", function(cm) { + cm.setValue( + "This function should\n" + + "convert a zero based index\n" + + "to line and ch." + ); + + var examples = [ + { index: -1, line: 0, ch: 0 }, // <- Tests clipping + { index: 0, line: 0, ch: 0 }, + { index: 10, line: 0, ch: 10 }, + { index: 39, line: 1, ch: 18 }, + { index: 55, line: 2, ch: 7 }, + { index: 63, line: 2, ch: 15 }, + { index: 64, line: 2, ch: 15 } // <- Tests clipping + ]; + + for (var i = 0; i < examples.length; i++) { + var example = examples[i]; + var pos = cm.posFromIndex(example.index); + eq(pos.line, example.line); + eq(pos.ch, example.ch); + if (example.index >= 0 && example.index < 64) + eq(cm.indexFromPos(pos), example.index); + } +}); + +testCM("undo", function(cm) { + cm.replaceRange("def", Pos(0, 0), Pos(0)); + eq(cm.historySize().undo, 1); + cm.undo(); + eq(cm.getValue(), "abc"); + eq(cm.historySize().undo, 0); + eq(cm.historySize().redo, 1); + cm.redo(); + eq(cm.getValue(), "def"); + eq(cm.historySize().undo, 1); + eq(cm.historySize().redo, 0); + cm.setValue("1\n\n\n2"); + cm.clearHistory(); + eq(cm.historySize().undo, 0); + for (var i = 0; i < 20; ++i) { + cm.replaceRange("a", Pos(0, 0)); + cm.replaceRange("b", Pos(3, 0)); + } + eq(cm.historySize().undo, 40); + for (var i = 0; i < 40; ++i) + cm.undo(); + eq(cm.historySize().redo, 40); + eq(cm.getValue(), "1\n\n\n2"); +}, {value: "abc"}); + +testCM("undoDepth", function(cm) { + cm.replaceRange("d", Pos(0)); + cm.replaceRange("e", Pos(0)); + cm.replaceRange("f", Pos(0)); + cm.undo(); cm.undo(); cm.undo(); + eq(cm.getValue(), "abcd"); +}, {value: "abc", undoDepth: 4}); + +testCM("undoDoesntClearValue", function(cm) { + cm.undo(); + eq(cm.getValue(), "x"); +}, {value: "x"}); + +testCM("undoMultiLine", function(cm) { + cm.operation(function() { + cm.replaceRange("x", Pos(0, 0)); + cm.replaceRange("y", Pos(1, 0)); + }); + cm.undo(); + eq(cm.getValue(), "abc\ndef\nghi"); + cm.operation(function() { + cm.replaceRange("y", Pos(1, 0)); + cm.replaceRange("x", Pos(0, 0)); + }); + cm.undo(); + eq(cm.getValue(), "abc\ndef\nghi"); + cm.operation(function() { + cm.replaceRange("y", Pos(2, 0)); + cm.replaceRange("x", Pos(1, 0)); + cm.replaceRange("z", Pos(2, 0)); + }); + cm.undo(); + eq(cm.getValue(), "abc\ndef\nghi", 3); +}, {value: "abc\ndef\nghi"}); + +testCM("undoComposite", function(cm) { + cm.replaceRange("y", Pos(1)); + cm.operation(function() { + cm.replaceRange("x", Pos(0)); + cm.replaceRange("z", Pos(2)); + }); + eq(cm.getValue(), "ax\nby\ncz\n"); + cm.undo(); + eq(cm.getValue(), "a\nby\nc\n"); + cm.undo(); + eq(cm.getValue(), "a\nb\nc\n"); + cm.redo(); cm.redo(); + eq(cm.getValue(), "ax\nby\ncz\n"); +}, {value: "a\nb\nc\n"}); + +testCM("undoSelection", function(cm) { + cm.setSelection(Pos(0, 2), Pos(0, 4)); + cm.replaceSelection(""); + cm.setCursor(Pos(1, 0)); + cm.undo(); + eqCursorPos(cm.getCursor(true), Pos(0, 2)); + eqCursorPos(cm.getCursor(false), Pos(0, 4)); + cm.setCursor(Pos(1, 0)); + cm.redo(); + eqCursorPos(cm.getCursor(true), Pos(0, 2)); + eqCursorPos(cm.getCursor(false), Pos(0, 2)); +}, {value: "abcdefgh\n"}); + +testCM("undoSelectionAsBefore", function(cm) { + cm.replaceSelection("abc", "around"); + cm.undo(); + cm.redo(); + eq(cm.getSelection(), "abc"); +}); + +testCM("selectionChangeConfusesHistory", function(cm) { + cm.replaceSelection("abc", null, "dontmerge"); + cm.operation(function() { + cm.setCursor(Pos(0, 0)); + cm.replaceSelection("abc", null, "dontmerge"); + }); + eq(cm.historySize().undo, 2); +}); + +testCM("markTextSingleLine", function(cm) { + forEach([{a: 0, b: 1, c: "", f: 2, t: 5}, + {a: 0, b: 4, c: "", f: 0, t: 2}, + {a: 1, b: 2, c: "x", f: 3, t: 6}, + {a: 4, b: 5, c: "", f: 3, t: 5}, + {a: 4, b: 5, c: "xx", f: 3, t: 7}, + {a: 2, b: 5, c: "", f: 2, t: 3}, + {a: 2, b: 5, c: "abcd", f: 6, t: 7}, + {a: 2, b: 6, c: "x", f: null, t: null}, + {a: 3, b: 6, c: "", f: null, t: null}, + {a: 0, b: 9, c: "hallo", f: null, t: null}, + {a: 4, b: 6, c: "x", f: 3, t: 4}, + {a: 4, b: 8, c: "", f: 3, t: 4}, + {a: 6, b: 6, c: "a", f: 3, t: 6}, + {a: 8, b: 9, c: "", f: 3, t: 6}], function(test) { + cm.setValue("1234567890"); + var r = cm.markText(Pos(0, 3), Pos(0, 6), {className: "foo"}); + cm.replaceRange(test.c, Pos(0, test.a), Pos(0, test.b)); + var f = r.find(); + eq(f && f.from.ch, test.f); eq(f && f.to.ch, test.t); + }); +}); + +testCM("markTextMultiLine", function(cm) { + function p(v) { return v && Pos(v[0], v[1]); } + forEach([{a: [0, 0], b: [0, 5], c: "", f: [0, 0], t: [2, 5]}, + {a: [0, 0], b: [0, 5], c: "foo\n", f: [1, 0], t: [3, 5]}, + {a: [0, 1], b: [0, 10], c: "", f: [0, 1], t: [2, 5]}, + {a: [0, 5], b: [0, 6], c: "x", f: [0, 6], t: [2, 5]}, + {a: [0, 0], b: [1, 0], c: "", f: [0, 0], t: [1, 5]}, + {a: [0, 6], b: [2, 4], c: "", f: [0, 5], t: [0, 7]}, + {a: [0, 6], b: [2, 4], c: "aa", f: [0, 5], t: [0, 9]}, + {a: [1, 2], b: [1, 8], c: "", f: [0, 5], t: [2, 5]}, + {a: [0, 5], b: [2, 5], c: "xx", f: null, t: null}, + {a: [0, 0], b: [2, 10], c: "x", f: null, t: null}, + {a: [1, 5], b: [2, 5], c: "", f: [0, 5], t: [1, 5]}, + {a: [2, 0], b: [2, 3], c: "", f: [0, 5], t: [2, 2]}, + {a: [2, 5], b: [3, 0], c: "a\nb", f: [0, 5], t: [2, 5]}, + {a: [2, 3], b: [3, 0], c: "x", f: [0, 5], t: [2, 3]}, + {a: [1, 1], b: [1, 9], c: "1\n2\n3", f: [0, 5], t: [4, 5]}], function(test) { + cm.setValue("aaaaaaaaaa\nbbbbbbbbbb\ncccccccccc\ndddddddd\n"); + var r = cm.markText(Pos(0, 5), Pos(2, 5), + {className: "CodeMirror-matchingbracket"}); + cm.replaceRange(test.c, p(test.a), p(test.b)); + var f = r.find(); + eqCursorPos(f && f.from, p(test.f)); eqCursorPos(f && f.to, p(test.t)); + }); +}); + +testCM("markTextUndo", function(cm) { + var marker1, marker2, bookmark; + marker1 = cm.markText(Pos(0, 1), Pos(0, 3), + {className: "CodeMirror-matchingbracket"}); + marker2 = cm.markText(Pos(0, 0), Pos(2, 1), + {className: "CodeMirror-matchingbracket"}); + bookmark = cm.setBookmark(Pos(1, 5)); + cm.operation(function(){ + cm.replaceRange("foo", Pos(0, 2)); + cm.replaceRange("bar\nbaz\nbug\n", Pos(2, 0), Pos(3, 0)); + }); + var v1 = cm.getValue(); + cm.setValue(""); + eq(marker1.find(), null); eq(marker2.find(), null); eq(bookmark.find(), null); + cm.undo(); + eqCursorPos(bookmark.find(), Pos(1, 5), "still there"); + cm.undo(); + var m1Pos = marker1.find(), m2Pos = marker2.find(); + eqCursorPos(m1Pos.from, Pos(0, 1)); eqCursorPos(m1Pos.to, Pos(0, 3)); + eqCursorPos(m2Pos.from, Pos(0, 0)); eqCursorPos(m2Pos.to, Pos(2, 1)); + eqCursorPos(bookmark.find(), Pos(1, 5)); + cm.redo(); cm.redo(); + eq(bookmark.find(), null); + cm.undo(); + eqCursorPos(bookmark.find(), Pos(1, 5)); + eq(cm.getValue(), v1); +}, {value: "1234\n56789\n00\n"}); + +testCM("markTextStayGone", function(cm) { + var m1 = cm.markText(Pos(0, 0), Pos(0, 1)); + cm.replaceRange("hi", Pos(0, 2)); + m1.clear(); + cm.undo(); + eq(m1.find(), null); +}, {value: "hello"}); + +testCM("markTextAllowEmpty", function(cm) { + var m1 = cm.markText(Pos(0, 1), Pos(0, 2), {clearWhenEmpty: false}); + is(m1.find()); + cm.replaceRange("x", Pos(0, 0)); + is(m1.find()); + cm.replaceRange("y", Pos(0, 2)); + is(m1.find()); + cm.replaceRange("z", Pos(0, 3), Pos(0, 4)); + is(!m1.find()); + var m2 = cm.markText(Pos(0, 1), Pos(0, 2), {clearWhenEmpty: false, + inclusiveLeft: true, + inclusiveRight: true}); + cm.replaceRange("q", Pos(0, 1), Pos(0, 2)); + is(m2.find()); + cm.replaceRange("", Pos(0, 0), Pos(0, 3)); + is(!m2.find()); + var m3 = cm.markText(Pos(0, 1), Pos(0, 1), {clearWhenEmpty: false}); + cm.replaceRange("a", Pos(0, 3)); + is(m3.find()); + cm.replaceRange("b", Pos(0, 1)); + is(!m3.find()); +}, {value: "abcde"}); + +testCM("markTextStacked", function(cm) { + var m1 = cm.markText(Pos(0, 0), Pos(0, 0), {clearWhenEmpty: false}); + var m2 = cm.markText(Pos(0, 0), Pos(0, 0), {clearWhenEmpty: false}); + cm.replaceRange("B", Pos(0, 1)); + is(m1.find() && m2.find()); +}, {value: "A"}); + +testCM("undoPreservesNewMarks", function(cm) { + cm.markText(Pos(0, 3), Pos(0, 4)); + cm.markText(Pos(1, 1), Pos(1, 3)); + cm.replaceRange("", Pos(0, 3), Pos(3, 1)); + var mBefore = cm.markText(Pos(0, 0), Pos(0, 1)); + var mAfter = cm.markText(Pos(0, 5), Pos(0, 6)); + var mAround = cm.markText(Pos(0, 2), Pos(0, 4)); + cm.undo(); + eqCursorPos(mBefore.find().from, Pos(0, 0)); + eqCursorPos(mBefore.find().to, Pos(0, 1)); + eqCursorPos(mAfter.find().from, Pos(3, 3)); + eqCursorPos(mAfter.find().to, Pos(3, 4)); + eqCursorPos(mAround.find().from, Pos(0, 2)); + eqCursorPos(mAround.find().to, Pos(3, 2)); + var found = cm.findMarksAt(Pos(2, 2)); + eq(found.length, 1); + eq(found[0], mAround); +}, {value: "aaaa\nbbbb\ncccc\ndddd"}); + +testCM("markClearBetween", function(cm) { + cm.setValue("aaa\nbbb\nccc\nddd\n"); + cm.markText(Pos(0, 0), Pos(2)); + cm.replaceRange("aaa\nbbb\nccc", Pos(0, 0), Pos(2)); + eq(cm.findMarksAt(Pos(1, 1)).length, 0); +}); + +testCM("findMarksMiddle", function(cm) { + var mark = cm.markText(Pos(1, 1), Pos(3, 1)); + var found = cm.findMarks(Pos(2, 1), Pos(2, 2)); + eq(found.length, 1); + eq(found[0], mark); +}, {value: "line 0\nline 1\nline 2\nline 3"}); + +testCM("deleteSpanCollapsedInclusiveLeft", function(cm) { + var from = Pos(1, 0), to = Pos(1, 1); + var m = cm.markText(from, to, {collapsed: true, inclusiveLeft: true}); + // Delete collapsed span. + cm.replaceRange("", from, to); +}, {value: "abc\nX\ndef"}); + +testCM("markTextCSS", function(cm) { + function present() { + var spans = cm.display.lineDiv.getElementsByTagName("span"); + for (var i = 0; i < spans.length; i++) + if (spans[i].style.color == "cyan" && span[i].textContent == "cdefg") return true; + } + var m = cm.markText(Pos(0, 2), Pos(0, 6), {css: "color: cyan"}); + m.clear(); + is(!present()); +}, {value: "abcdefgh"}); + +testCM("bookmark", function(cm) { + function p(v) { return v && Pos(v[0], v[1]); } + forEach([{a: [1, 0], b: [1, 1], c: "", d: [1, 4]}, + {a: [1, 1], b: [1, 1], c: "xx", d: [1, 7]}, + {a: [1, 4], b: [1, 5], c: "ab", d: [1, 6]}, + {a: [1, 4], b: [1, 6], c: "", d: null}, + {a: [1, 5], b: [1, 6], c: "abc", d: [1, 5]}, + {a: [1, 6], b: [1, 8], c: "", d: [1, 5]}, + {a: [1, 4], b: [1, 4], c: "\n\n", d: [3, 1]}, + {bm: [1, 9], a: [1, 1], b: [1, 1], c: "\n", d: [2, 8]}], function(test) { + cm.setValue("1234567890\n1234567890\n1234567890"); + var b = cm.setBookmark(p(test.bm) || Pos(1, 5)); + cm.replaceRange(test.c, p(test.a), p(test.b)); + eqCursorPos(b.find(), p(test.d)); + }); +}); + +testCM("bookmarkInsertLeft", function(cm) { + var br = cm.setBookmark(Pos(0, 2), {insertLeft: false}); + var bl = cm.setBookmark(Pos(0, 2), {insertLeft: true}); + cm.setCursor(Pos(0, 2)); + cm.replaceSelection("hi"); + eqCursorPos(br.find(), Pos(0, 2)); + eqCursorPos(bl.find(), Pos(0, 4)); + cm.replaceRange("", Pos(0, 4), Pos(0, 5)); + cm.replaceRange("", Pos(0, 2), Pos(0, 4)); + cm.replaceRange("", Pos(0, 1), Pos(0, 2)); + // Verify that deleting next to bookmarks doesn't kill them + eqCursorPos(br.find(), Pos(0, 1)); + eqCursorPos(bl.find(), Pos(0, 1)); +}, {value: "abcdef"}); + +testCM("bookmarkCursor", function(cm) { + var pos01 = cm.cursorCoords(Pos(0, 1)), pos11 = cm.cursorCoords(Pos(1, 1)), + pos20 = cm.cursorCoords(Pos(2, 0)), pos30 = cm.cursorCoords(Pos(3, 0)), + pos41 = cm.cursorCoords(Pos(4, 1)); + cm.setBookmark(Pos(0, 1), {widget: document.createTextNode("←"), insertLeft: true}); + cm.setBookmark(Pos(2, 0), {widget: document.createTextNode("←"), insertLeft: true}); + cm.setBookmark(Pos(1, 1), {widget: document.createTextNode("→")}); + cm.setBookmark(Pos(3, 0), {widget: document.createTextNode("→")}); + var new01 = cm.cursorCoords(Pos(0, 1)), new11 = cm.cursorCoords(Pos(1, 1)), + new20 = cm.cursorCoords(Pos(2, 0)), new30 = cm.cursorCoords(Pos(3, 0)); + near(new01.left, pos01.left, 1); + near(new01.top, pos01.top, 1); + is(new11.left > pos11.left, "at right, middle of line"); + near(new11.top == pos11.top, 1); + near(new20.left, pos20.left, 1); + near(new20.top, pos20.top, 1); + is(new30.left > pos30.left, "at right, empty line"); + near(new30.top, pos30, 1); + cm.setBookmark(Pos(4, 0), {widget: document.createTextNode("→")}); + is(cm.cursorCoords(Pos(4, 1)).left > pos41.left, "single-char bug"); +}, {value: "foo\nbar\n\n\nx\ny"}); + +testCM("multiBookmarkCursor", function(cm) { + if (phantom) return; + var ms = [], m; + function add(insertLeft) { + for (var i = 0; i < 3; ++i) { + var node = document.createElement("span"); + node.innerHTML = "X"; + ms.push(cm.setBookmark(Pos(0, 1), {widget: node, insertLeft: insertLeft})); + } + } + var base1 = cm.cursorCoords(Pos(0, 1)).left, base4 = cm.cursorCoords(Pos(0, 4)).left; + add(true); + near(base1, cm.cursorCoords(Pos(0, 1)).left, 1); + while (m = ms.pop()) m.clear(); + add(false); + near(base4, cm.cursorCoords(Pos(0, 1)).left, 1); +}, {value: "abcdefg"}); + +testCM("getAllMarks", function(cm) { + addDoc(cm, 10, 10); + var m1 = cm.setBookmark(Pos(0, 2)); + var m2 = cm.markText(Pos(0, 2), Pos(3, 2)); + var m3 = cm.markText(Pos(1, 2), Pos(1, 8)); + var m4 = cm.markText(Pos(8, 0), Pos(9, 0)); + eq(cm.getAllMarks().length, 4); + m1.clear(); + m3.clear(); + eq(cm.getAllMarks().length, 2); +}); + +testCM("setValueClears", function(cm) { + cm.addLineClass(0, "wrap", "foo"); + var mark = cm.markText(Pos(0, 0), Pos(1, 1), {inclusiveLeft: true, inclusiveRight: true}); + cm.setValue("foo"); + is(!cm.lineInfo(0).wrapClass); + is(!mark.find()); +}, {value: "a\nb"}); + +testCM("bug577", function(cm) { + cm.setValue("a\nb"); + cm.clearHistory(); + cm.setValue("fooooo"); + cm.undo(); +}); + +testCM("scrollSnap", function(cm) { + cm.setSize(100, 100); + addDoc(cm, 200, 200); + cm.setCursor(Pos(100, 180)); + var info = cm.getScrollInfo(); + is(info.left > 0 && info.top > 0); + cm.setCursor(Pos(0, 0)); + info = cm.getScrollInfo(); + is(info.left == 0 && info.top == 0, "scrolled clean to top"); + cm.setCursor(Pos(100, 180)); + cm.setCursor(Pos(199, 0)); + info = cm.getScrollInfo(); + is(info.left == 0 && info.top + 2 > info.height - cm.getScrollerElement().clientHeight, "scrolled clean to bottom"); +}); + +testCM("scrollIntoView", function(cm) { + if (phantom) return; + function test(line, ch, msg) { + var pos = Pos(line, ch); + cm.scrollIntoView(pos); + var outer = cm.getWrapperElement().getBoundingClientRect(); + var box = cm.charCoords(pos, "window"); + is(box.left >= outer.left, msg + " (left)"); + is(box.right <= outer.right, msg + " (right)"); + is(box.top >= outer.top, msg + " (top)"); + is(box.bottom <= outer.bottom, msg + " (bottom)"); + } + addDoc(cm, 200, 200); + test(199, 199, "bottom right"); + test(0, 0, "top left"); + test(100, 100, "center"); + test(199, 0, "bottom left"); + test(0, 199, "top right"); + test(100, 100, "center again"); +}); + +testCM("scrollBackAndForth", function(cm) { + addDoc(cm, 1, 200); + cm.operation(function() { + cm.scrollIntoView(Pos(199, 0)); + cm.scrollIntoView(Pos(4, 0)); + }); + is(cm.getScrollInfo().top > 0); +}); + +testCM("selectAllNoScroll", function(cm) { + addDoc(cm, 1, 200); + cm.execCommand("selectAll"); + eq(cm.getScrollInfo().top, 0); + cm.setCursor(199); + cm.execCommand("selectAll"); + is(cm.getScrollInfo().top > 0); +}); + +testCM("selectionPos", function(cm) { + if (phantom || cm.getOption("inputStyle") != "textarea") return; + cm.setSize(100, 100); + addDoc(cm, 200, 100); + cm.setSelection(Pos(1, 100), Pos(98, 100)); + var lineWidth = cm.charCoords(Pos(0, 200), "local").left; + var lineHeight = (cm.charCoords(Pos(99)).top - cm.charCoords(Pos(0)).top) / 100; + cm.scrollTo(0, 0); + var selElt = byClassName(cm.getWrapperElement(), "CodeMirror-selected"); + var outer = cm.getWrapperElement().getBoundingClientRect(); + var sawMiddle, sawTop, sawBottom; + for (var i = 0, e = selElt.length; i < e; ++i) { + var box = selElt[i].getBoundingClientRect(); + var atLeft = box.left - outer.left < 30; + var width = box.right - box.left; + var atRight = box.right - outer.left > .8 * lineWidth; + if (atLeft && atRight) { + sawMiddle = true; + is(box.bottom - box.top > 90 * lineHeight, "middle high"); + is(width > .9 * lineWidth, "middle wide"); + } else { + is(width > .4 * lineWidth, "top/bot wide enough"); + is(width < .6 * lineWidth, "top/bot slim enough"); + if (atLeft) { + sawBottom = true; + is(box.top - outer.top > 96 * lineHeight, "bot below"); + } else if (atRight) { + sawTop = true; + is(box.top - outer.top < 2.1 * lineHeight, "top above"); + } + } + } + is(sawTop && sawBottom && sawMiddle, "all parts"); +}, null); + +testCM("restoreHistory", function(cm) { + cm.setValue("abc\ndef"); + cm.replaceRange("hello", Pos(1, 0), Pos(1)); + cm.replaceRange("goop", Pos(0, 0), Pos(0)); + cm.undo(); + var storedVal = cm.getValue(), storedHist = cm.getHistory(); + if (window.JSON) storedHist = JSON.parse(JSON.stringify(storedHist)); + eq(storedVal, "abc\nhello"); + cm.setValue(""); + cm.clearHistory(); + eq(cm.historySize().undo, 0); + cm.setValue(storedVal); + cm.setHistory(storedHist); + cm.redo(); + eq(cm.getValue(), "goop\nhello"); + cm.undo(); cm.undo(); + eq(cm.getValue(), "abc\ndef"); +}); + +testCM("doubleScrollbar", function(cm) { + var dummy = document.body.appendChild(document.createElement("p")); + dummy.style.cssText = "height: 50px; overflow: scroll; width: 50px"; + var scrollbarWidth = dummy.offsetWidth + 1 - dummy.clientWidth; + document.body.removeChild(dummy); + if (scrollbarWidth < 2) return; + cm.setSize(null, 100); + addDoc(cm, 1, 300); + var wrap = cm.getWrapperElement(); + is(wrap.offsetWidth - byClassName(wrap, "CodeMirror-lines")[0].offsetWidth <= scrollbarWidth * 1.5); +}); + +testCM("weirdLinebreaks", function(cm) { + cm.setValue("foo\nbar\rbaz\r\nquux\n\rplop"); + is(cm.getValue(), "foo\nbar\nbaz\nquux\n\nplop"); + is(cm.lineCount(), 6); + cm.setValue("\n\n"); + is(cm.lineCount(), 3); +}); + +testCM("setSize", function(cm) { + cm.setSize(100, 100); + var wrap = cm.getWrapperElement(); + is(wrap.offsetWidth, 100); + is(wrap.offsetHeight, 100); + cm.setSize("100%", "3em"); + is(wrap.style.width, "100%"); + is(wrap.style.height, "3em"); + cm.setSize(null, 40); + is(wrap.style.width, "100%"); + is(wrap.style.height, "40px"); +}); + +function foldLines(cm, start, end, autoClear) { + return cm.markText(Pos(start, 0), Pos(end - 1), { + inclusiveLeft: true, + inclusiveRight: true, + collapsed: true, + clearOnEnter: autoClear + }); +} + +testCM("collapsedLines", function(cm) { + addDoc(cm, 4, 10); + var range = foldLines(cm, 4, 5), cleared = 0; + CodeMirror.on(range, "clear", function() {cleared++;}); + cm.setCursor(Pos(3, 0)); + CodeMirror.commands.goLineDown(cm); + eqCharPos(cm.getCursor(), Pos(5, 0)); + cm.replaceRange("abcdefg", Pos(3, 0), Pos(3)); + cm.setCursor(Pos(3, 6)); + CodeMirror.commands.goLineDown(cm); + eqCharPos(cm.getCursor(), Pos(5, 4)); + cm.replaceRange("ab", Pos(3, 0), Pos(3)); + cm.setCursor(Pos(3, 2)); + CodeMirror.commands.goLineDown(cm); + eqCharPos(cm.getCursor(), Pos(5, 2)); + cm.operation(function() {range.clear(); range.clear();}); + eq(cleared, 1); +}); + +testCM("collapsedRangeCoordsChar", function(cm) { + var pos_1_3 = cm.charCoords(Pos(1, 3)); + pos_1_3.left += 2; pos_1_3.top += 2; + var opts = {collapsed: true, inclusiveLeft: true, inclusiveRight: true}; + var m1 = cm.markText(Pos(0, 0), Pos(2, 0), opts); + eqCharPos(cm.coordsChar(pos_1_3), Pos(3, 3)); + m1.clear(); + var m1 = cm.markText(Pos(0, 0), Pos(1, 1), {collapsed: true, inclusiveLeft: true}); + var m2 = cm.markText(Pos(1, 1), Pos(2, 0), {collapsed: true, inclusiveRight: true}); + eqCharPos(cm.coordsChar(pos_1_3), Pos(3, 3)); + m1.clear(); m2.clear(); + var m1 = cm.markText(Pos(0, 0), Pos(1, 6), opts); + eqCharPos(cm.coordsChar(pos_1_3), Pos(3, 3)); +}, {value: "123456\nabcdef\nghijkl\nmnopqr\n"}); + +testCM("collapsedRangeBetweenLinesSelected", function(cm) { + if (cm.getOption("inputStyle") != "textarea") return; + var widget = document.createElement("span"); + widget.textContent = "\u2194"; + cm.markText(Pos(0, 3), Pos(1, 0), {replacedWith: widget}); + cm.setSelection(Pos(0, 3), Pos(1, 0)); + var selElts = byClassName(cm.getWrapperElement(), "CodeMirror-selected"); + for (var i = 0, w = 0; i < selElts.length; i++) + w += selElts[i].offsetWidth; + is(w > 0); +}, {value: "one\ntwo"}); + +testCM("randomCollapsedRanges", function(cm) { + addDoc(cm, 20, 500); + cm.operation(function() { + for (var i = 0; i < 200; i++) { + var start = Pos(Math.floor(Math.random() * 500), Math.floor(Math.random() * 20)); + if (i % 4) + try { cm.markText(start, Pos(start.line + 2, 1), {collapsed: true}); } + catch(e) { if (!/overlapping/.test(String(e))) throw e; } + else + cm.markText(start, Pos(start.line, start.ch + 4), {"className": "foo"}); + } + }); +}); + +testCM("hiddenLinesAutoUnfold", function(cm) { + var range = foldLines(cm, 1, 3, true), cleared = 0; + CodeMirror.on(range, "clear", function() {cleared++;}); + cm.setCursor(Pos(3, 0)); + eq(cleared, 0); + cm.execCommand("goCharLeft"); + eq(cleared, 1); + range = foldLines(cm, 1, 3, true); + CodeMirror.on(range, "clear", function() {cleared++;}); + eqCursorPos(cm.getCursor(), Pos(3, 0)); + cm.setCursor(Pos(0, 3)); + cm.execCommand("goCharRight"); + eq(cleared, 2); +}, {value: "abc\ndef\nghi\njkl"}); + +testCM("hiddenLinesSelectAll", function(cm) { // Issue #484 + addDoc(cm, 4, 20); + foldLines(cm, 0, 10); + foldLines(cm, 11, 20); + CodeMirror.commands.selectAll(cm); + eqCursorPos(cm.getCursor(true), Pos(10, 0)); + eqCursorPos(cm.getCursor(false), Pos(10, 4)); +}); + + +testCM("everythingFolded", function(cm) { + addDoc(cm, 2, 2); + function enterPress() { + cm.triggerOnKeyDown({type: "keydown", keyCode: 13, preventDefault: function(){}, stopPropagation: function(){}}); + } + var fold = foldLines(cm, 0, 2); + enterPress(); + eq(cm.getValue(), "xx\nxx"); + fold.clear(); + fold = foldLines(cm, 0, 2, true); + eq(fold.find(), null); + enterPress(); + eq(cm.getValue(), "\nxx\nxx"); +}); + +testCM("structuredFold", function(cm) { + if (phantom) return; + addDoc(cm, 4, 8); + var range = cm.markText(Pos(1, 2), Pos(6, 2), { + replacedWith: document.createTextNode("Q") + }); + cm.setCursor(0, 3); + CodeMirror.commands.goLineDown(cm); + eqCharPos(cm.getCursor(), Pos(6, 2)); + CodeMirror.commands.goCharLeft(cm); + eqCharPos(cm.getCursor(), Pos(1, 2)); + CodeMirror.commands.delCharAfter(cm); + eq(cm.getValue(), "xxxx\nxxxx\nxxxx"); + addDoc(cm, 4, 8); + range = cm.markText(Pos(1, 2), Pos(6, 2), { + replacedWith: document.createTextNode("M"), + clearOnEnter: true + }); + var cleared = 0; + CodeMirror.on(range, "clear", function(){++cleared;}); + cm.setCursor(0, 3); + CodeMirror.commands.goLineDown(cm); + eqCharPos(cm.getCursor(), Pos(6, 2)); + CodeMirror.commands.goCharLeft(cm); + eqCharPos(cm.getCursor(), Pos(6, 1)); + eq(cleared, 1); + range.clear(); + eq(cleared, 1); + range = cm.markText(Pos(1, 2), Pos(6, 2), { + replacedWith: document.createTextNode("Q"), + clearOnEnter: true + }); + range.clear(); + cm.setCursor(1, 2); + CodeMirror.commands.goCharRight(cm); + eqCharPos(cm.getCursor(), Pos(1, 3)); + range = cm.markText(Pos(2, 0), Pos(4, 4), { + replacedWith: document.createTextNode("M") + }); + cm.setCursor(1, 0); + CodeMirror.commands.goLineDown(cm); + eqCharPos(cm.getCursor(), Pos(2, 0)); +}, null); + +testCM("nestedFold", function(cm) { + addDoc(cm, 10, 3); + function fold(ll, cl, lr, cr) { + return cm.markText(Pos(ll, cl), Pos(lr, cr), {collapsed: true}); + } + var inner1 = fold(0, 6, 1, 3), inner2 = fold(0, 2, 1, 8), outer = fold(0, 1, 2, 3), inner0 = fold(0, 5, 0, 6); + cm.setCursor(0, 1); + CodeMirror.commands.goCharRight(cm); + eqCursorPos(cm.getCursor(), Pos(2, 3)); + inner0.clear(); + CodeMirror.commands.goCharLeft(cm); + eqCursorPos(cm.getCursor(), Pos(0, 1)); + outer.clear(); + CodeMirror.commands.goCharRight(cm); + eqCursorPos(cm.getCursor(), Pos(0, 2, "before")); + CodeMirror.commands.goCharRight(cm); + eqCursorPos(cm.getCursor(), Pos(1, 8)); + inner2.clear(); + CodeMirror.commands.goCharLeft(cm); + eqCursorPos(cm.getCursor(), Pos(1, 7, "after")); + cm.setCursor(0, 5); + CodeMirror.commands.goCharRight(cm); + eqCursorPos(cm.getCursor(), Pos(0, 6, "before")); + CodeMirror.commands.goCharRight(cm); + eqCursorPos(cm.getCursor(), Pos(1, 3)); +}); + +testCM("badNestedFold", function(cm) { + addDoc(cm, 4, 4); + cm.markText(Pos(0, 2), Pos(3, 2), {collapsed: true}); + var caught; + try {cm.markText(Pos(0, 1), Pos(0, 3), {collapsed: true});} + catch(e) {caught = e;} + is(caught instanceof Error, "no error"); + is(/overlap/i.test(caught.message), "wrong error"); +}); + +testCM("nestedFoldOnSide", function(cm) { + var m1 = cm.markText(Pos(0, 1), Pos(2, 1), {collapsed: true, inclusiveRight: true}); + var m2 = cm.markText(Pos(0, 1), Pos(0, 2), {collapsed: true}); + cm.markText(Pos(0, 1), Pos(0, 2), {collapsed: true}).clear(); + try { cm.markText(Pos(0, 1), Pos(0, 2), {collapsed: true, inclusiveLeft: true}); } + catch(e) { var caught = e; } + is(caught && /overlap/i.test(caught.message)); + var m3 = cm.markText(Pos(2, 0), Pos(2, 1), {collapsed: true}); + var m4 = cm.markText(Pos(2, 0), Pos(2, 1), {collapse: true, inclusiveRight: true}); + m1.clear(); m4.clear(); + m1 = cm.markText(Pos(0, 1), Pos(2, 1), {collapsed: true}); + cm.markText(Pos(2, 0), Pos(2, 1), {collapsed: true}).clear(); + try { cm.markText(Pos(2, 0), Pos(2, 1), {collapsed: true, inclusiveRight: true}); } + catch(e) { var caught = e; } + is(caught && /overlap/i.test(caught.message)); +}, {value: "ab\ncd\ef"}); + +testCM("editInFold", function(cm) { + addDoc(cm, 4, 6); + var m = cm.markText(Pos(1, 2), Pos(3, 2), {collapsed: true}); + cm.replaceRange("", Pos(0, 0), Pos(1, 3)); + cm.replaceRange("", Pos(2, 1), Pos(3, 3)); + cm.replaceRange("a\nb\nc\nd", Pos(0, 1), Pos(1, 0)); + cm.cursorCoords(Pos(0, 0)); +}); + +testCM("wrappingInlineWidget", function(cm) { + cm.setSize("11em"); + var w = document.createElement("span"); + w.style.color = "red"; + w.innerHTML = "one two three four"; + cm.markText(Pos(0, 6), Pos(0, 9), {replacedWith: w}); + var cur0 = cm.cursorCoords(Pos(0, 0)), cur1 = cm.cursorCoords(Pos(0, 10)); + is(cur0.top < cur1.top); + is(cur0.bottom < cur1.bottom); + var curL = cm.cursorCoords(Pos(0, 6)), curR = cm.cursorCoords(Pos(0, 9)); + eq(curL.top, cur0.top); + eq(curL.bottom, cur0.bottom); + eq(curR.top, cur1.top); + eq(curR.bottom, cur1.bottom); + cm.replaceRange("", Pos(0, 9), Pos(0)); + curR = cm.cursorCoords(Pos(0, 9)); + if (phantom) return; + eq(curR.top, cur1.top); + eq(curR.bottom, cur1.bottom); +}, {value: "1 2 3 xxx 4", lineWrapping: true}); + +testCM("showEmptyWidgetSpan", function(cm) { + var marker = cm.markText(Pos(0, 2), Pos(0, 2), { + clearWhenEmpty: false, + replacedWith: document.createTextNode("X") + }); + var text = cm.display.view[0].text; + eq(text.textContent || text.innerText, "abXc"); +}, {value: "abc"}); + +testCM("changedInlineWidget", function(cm) { + cm.setSize("10em"); + var w = document.createElement("span"); + w.innerHTML = "x"; + var m = cm.markText(Pos(0, 4), Pos(0, 5), {replacedWith: w}); + w.innerHTML = "and now the widget is really really long all of a sudden and a scrollbar is needed"; + m.changed(); + var hScroll = byClassName(cm.getWrapperElement(), "CodeMirror-hscrollbar")[0]; + is(hScroll.scrollWidth > hScroll.clientWidth); +}, {value: "hello there"}); + +testCM("changedBookmark", function(cm) { + cm.setSize("10em"); + var w = document.createElement("span"); + w.innerHTML = "x"; + var m = cm.setBookmark(Pos(0, 4), {widget: w}); + w.innerHTML = "and now the widget is really really long all of a sudden and a scrollbar is needed"; + m.changed(); + var hScroll = byClassName(cm.getWrapperElement(), "CodeMirror-hscrollbar")[0]; + is(hScroll.scrollWidth > hScroll.clientWidth); +}, {value: "abcdefg"}); + +testCM("inlineWidget", function(cm) { + var w = cm.setBookmark(Pos(0, 2), {widget: document.createTextNode("uu")}); + cm.setCursor(0, 2); + CodeMirror.commands.goLineDown(cm); + eqCharPos(cm.getCursor(), Pos(1, 4)); + cm.setCursor(0, 2); + cm.replaceSelection("hi"); + eqCharPos(w.find(), Pos(0, 2)); + cm.setCursor(0, 1); + cm.replaceSelection("ay"); + eqCharPos(w.find(), Pos(0, 4)); + eq(cm.getLine(0), "uayuhiuu"); +}, {value: "uuuu\nuuuuuu"}); + +testCM("wrappingAndResizing", function(cm) { + cm.setSize(null, "auto"); + cm.setOption("lineWrapping", true); + var wrap = cm.getWrapperElement(), h0 = wrap.offsetHeight; + var doc = "xxx xxx xxx xxx xxx"; + cm.setValue(doc); + for (var step = 10, w = cm.charCoords(Pos(0, 18), "div").right;; w += step) { + cm.setSize(w); + if (wrap.offsetHeight <= h0 * (opera_lt10 ? 1.2 : 1.5)) { + if (step == 10) { w -= 10; step = 1; } + else break; + } + } + // Ensure that putting the cursor at the end of the maximally long + // line doesn't cause wrapping to happen. + cm.setCursor(Pos(0, doc.length)); + eq(wrap.offsetHeight, h0); + cm.replaceSelection("x"); + is(wrap.offsetHeight > h0, "wrapping happens"); + // Now add a max-height and, in a document consisting of + // almost-wrapped lines, go over it so that a scrollbar appears. + cm.setValue(doc + "\n" + doc + "\n"); + cm.getScrollerElement().style.maxHeight = "100px"; + cm.replaceRange("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n!\n", Pos(2, 0)); + forEach([Pos(0, doc.length), Pos(0, doc.length - 1), + Pos(0, 0), Pos(1, doc.length), Pos(1, doc.length - 1)], + function(pos) { + var coords = cm.charCoords(pos); + eqCharPos(pos, cm.coordsChar({left: coords.left + 2, top: coords.top + 5})); + }); +}, null, ie_lt8); + +testCM("measureEndOfLine", function(cm) { + if (phantom) return; + cm.setSize(null, "auto"); + var inner = byClassName(cm.getWrapperElement(), "CodeMirror-lines")[0].firstChild; + var lh = inner.offsetHeight; + for (var step = 10, w = cm.charCoords(Pos(0, 7), "div").right;; w += step) { + cm.setSize(w); + if (inner.offsetHeight < 2.5 * lh) { + if (step == 10) { w -= 10; step = 1; } + else break; + } + } + cm.setValue(cm.getValue() + "\n\n"); + var endPos = cm.charCoords(Pos(0, 18), "local"); + is(endPos.top > lh * .8, "not at top"); + is(endPos.left > w - 20, "at right"); + endPos = cm.charCoords(Pos(0, 18)); + eqCursorPos(cm.coordsChar({left: endPos.left, top: endPos.top + 5}), Pos(0, 18, "before")); + + var wrapPos = cm.cursorCoords(Pos(0, 9, "before")); + is(wrapPos.top < endPos.top, "wrapPos is actually in first line"); + eqCursorPos(cm.coordsChar({left: wrapPos.left + 10, top: wrapPos.top}), Pos(0, 9, "before")); +}, {mode: "text/html", value: "<!-- foo barrr -->", lineWrapping: true}, ie_lt8 || opera_lt10); + +testCM("measureWrappedEndOfLine", function(cm) { + if (phantom) return; + cm.setSize(null, "auto"); + var inner = byClassName(cm.getWrapperElement(), "CodeMirror-lines")[0].firstChild; + var lh = inner.offsetHeight; + for (var step = 10, w = cm.charCoords(Pos(0, 7), "div").right;; w += step) { + cm.setSize(w); + if (inner.offsetHeight < 2.5 * lh) { + if (step == 10) { w -= 10; step = 1; } + else break; + } + } + for (var i = 0; i < 3; ++i) { + var endPos = cm.charCoords(Pos(0, 12)); // Next-to-last since last would wrap (#1862) + endPos.left += w; // Add width of editor just to be sure that we are behind last character + eqCursorPos(cm.coordsChar(endPos), Pos(0, 13, "before")); + endPos.left += w * 100; + eqCursorPos(cm.coordsChar(endPos), Pos(0, 13, "before")); + cm.setValue("0123456789abcابجابجابجابج"); + if (i == 1) { + var node = document.createElement("div"); + node.innerHTML = "hi"; node.style.height = "30px"; + cm.addLineWidget(0, node, {above: true}); + } + } +}, {mode: "text/html", value: "0123456789abcde0123456789", lineWrapping: true}, ie_lt8 || opera_lt10); + +testCM("measureEndOfLineBidi", function(cm) { + eqCursorPos(cm.coordsChar({left: 5000, top: cm.charCoords(Pos(0, 0)).top}), Pos(0, 8, "after")) +}, {value: "إإإإuuuuإإإإ"}) + +testCM("measureWrappedBidiLevel2", function(cm) { + cm.setSize(cm.charCoords(Pos(0, 6), "editor").right + 60) + var c9 = cm.charCoords(Pos(0, 9)) + eqCharPos(cm.coordsChar({left: c9.right - 1, top: c9.top + 1}), Pos(0, 9)) +}, {value: "foobar إإ إإ إإ إإ 555 بببببب", lineWrapping: true}) + +testCM("measureWrappedBeginOfLine", function(cm) { + if (phantom) return; + cm.setSize(null, "auto"); + var inner = byClassName(cm.getWrapperElement(), "CodeMirror-lines")[0].firstChild; + var lh = inner.offsetHeight; + for (var step = 10, w = cm.charCoords(Pos(0, 7), "div").right;; w += step) { + cm.setSize(w); + if (inner.offsetHeight < 2.5 * lh) { + if (step == 10) { w -= 10; step = 1; } + else break; + } + } + var beginOfSecondLine = Pos(0, 13, "after"); + for (var i = 0; i < 2; ++i) { + var beginPos = cm.charCoords(Pos(0, 0)); + beginPos.left -= w; + eqCursorPos(cm.coordsChar(beginPos), Pos(0, 0, "after")); + beginPos = cm.cursorCoords(beginOfSecondLine); + beginPos.left = 0; + eqCursorPos(cm.coordsChar(beginPos), beginOfSecondLine); + cm.setValue("0123456789abcابجابجابجابج"); + beginOfSecondLine = Pos(0, 25, "before"); + } +}, {mode: "text/html", value: "0123456789abcde0123456789", lineWrapping: true}); + +testCM("scrollVerticallyAndHorizontally", function(cm) { + if (cm.getOption("inputStyle") != "textarea") return; + cm.setSize(100, 100); + addDoc(cm, 40, 40); + cm.setCursor(39); + var wrap = cm.getWrapperElement(), bar = byClassName(wrap, "CodeMirror-vscrollbar")[0]; + is(bar.offsetHeight < wrap.offsetHeight, "vertical scrollbar limited by horizontal one"); + var cursorBox = byClassName(wrap, "CodeMirror-cursor")[0].getBoundingClientRect(); + var editorBox = wrap.getBoundingClientRect(); + is(cursorBox.bottom < editorBox.top + cm.getScrollerElement().clientHeight, + "bottom line visible"); +}, {lineNumbers: true}); + +testCM("moveVstuck", function(cm) { + var lines = byClassName(cm.getWrapperElement(), "CodeMirror-lines")[0].firstChild, h0 = lines.offsetHeight; + var val = "fooooooooooooooooooooooooo baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaar\n"; + cm.setValue(val); + for (var w = cm.charCoords(Pos(0, 26), "div").right * 2.8;; w += 5) { + cm.setSize(w); + if (lines.offsetHeight <= 3.5 * h0) break; + } + cm.setCursor(Pos(0, val.length - 1)); + cm.moveV(-1, "line"); + eqCursorPos(cm.getCursor(), Pos(0, 27, "before")); + is(cm.cursorCoords(null, "local").top < h0, "cursor is in first visual line"); +}, {lineWrapping: true}, ie_lt8 || opera_lt10); + +testCM("collapseOnMove", function(cm) { + cm.setSelection(Pos(0, 1), Pos(2, 4)); + cm.execCommand("goLineUp"); + is(!cm.somethingSelected()); + eqCharPos(cm.getCursor(), Pos(0, 1)); + cm.setSelection(Pos(0, 1), Pos(2, 4)); + cm.execCommand("goPageDown"); + is(!cm.somethingSelected()); + eqCharPos(cm.getCursor(), Pos(2, 4)); + cm.execCommand("goLineUp"); + cm.execCommand("goLineUp"); + eqCharPos(cm.getCursor(), Pos(0, 4)); + cm.setSelection(Pos(0, 1), Pos(2, 4)); + cm.execCommand("goCharLeft"); + is(!cm.somethingSelected()); + eqCharPos(cm.getCursor(), Pos(0, 1)); +}, {value: "aaaaa\nb\nccccc"}); + +testCM("clickTab", function(cm) { + var p0 = cm.charCoords(Pos(0, 0)); + eqCharPos(cm.coordsChar({left: p0.left + 5, top: p0.top + 5}), Pos(0, 0)); + eqCharPos(cm.coordsChar({left: p0.right - 5, top: p0.top + 5}), Pos(0, 1)); +}, {value: "\t\n\n", lineWrapping: true, tabSize: 8}); + +testCM("verticalScroll", function(cm) { + cm.setSize(100, 200); + cm.setValue("foo\nbar\nbaz\n"); + var sc = cm.getScrollerElement(), baseWidth = sc.scrollWidth; + cm.replaceRange("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah", Pos(0, 0), Pos(0)); + is(sc.scrollWidth > baseWidth, "scrollbar present"); + cm.replaceRange("foo", Pos(0, 0), Pos(0)); + if (!phantom) eq(sc.scrollWidth, baseWidth, "scrollbar gone"); + cm.replaceRange("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah", Pos(0, 0), Pos(0)); + cm.replaceRange("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbh", Pos(1, 0), Pos(1)); + is(sc.scrollWidth > baseWidth, "present again"); + var curWidth = sc.scrollWidth; + cm.replaceRange("foo", Pos(0, 0), Pos(0)); + is(sc.scrollWidth < curWidth, "scrollbar smaller"); + is(sc.scrollWidth > baseWidth, "but still present"); +}); + +testCM("extraKeys", function(cm) { + var outcome; + function fakeKey(expected, code, props) { + if (typeof code == "string") code = code.charCodeAt(0); + var e = {type: "keydown", keyCode: code, preventDefault: function(){}, stopPropagation: function(){}}; + if (props) for (var n in props) e[n] = props[n]; + outcome = null; + cm.triggerOnKeyDown(e); + eq(outcome, expected); + } + CodeMirror.commands.testCommand = function() {outcome = "tc";}; + CodeMirror.commands.goTestCommand = function() {outcome = "gtc";}; + cm.setOption("extraKeys", {"Shift-X": function() {outcome = "sx";}, + "X": function() {outcome = "x";}, + "Ctrl-Alt-U": function() {outcome = "cau";}, + "End": "testCommand", + "Home": "goTestCommand", + "Tab": false}); + fakeKey(null, "U"); + fakeKey("cau", "U", {ctrlKey: true, altKey: true}); + fakeKey(null, "U", {shiftKey: true, ctrlKey: true, altKey: true}); + fakeKey("x", "X"); + fakeKey("sx", "X", {shiftKey: true}); + fakeKey("tc", 35); + fakeKey(null, 35, {shiftKey: true}); + fakeKey("gtc", 36); + fakeKey("gtc", 36, {shiftKey: true}); + fakeKey(null, 9); +}, null, window.opera && mac); + +testCM("wordMovementCommands", function(cm) { + cm.execCommand("goWordLeft"); + eqCursorPos(cm.getCursor(), Pos(0, 0)); + cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); + eqCursorPos(cm.getCursor(), Pos(0, 7, "before")); + cm.execCommand("goWordLeft"); + eqCursorPos(cm.getCursor(), Pos(0, 5, "after")); + cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); + eqCursorPos(cm.getCursor(), Pos(0, 12, "before")); + cm.execCommand("goWordLeft"); + eqCursorPos(cm.getCursor(), Pos(0, 9, "after")); + cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); + eqCursorPos(cm.getCursor(), Pos(0, 24, "before")); + cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); + eqCursorPos(cm.getCursor(), Pos(1, 9, "before")); + cm.execCommand("goWordRight"); + eqCursorPos(cm.getCursor(), Pos(1, 13, "before")); + cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); + eqCharPos(cm.getCursor(), Pos(2, 0)); +}, {value: "this is (the) firstline.\na foo12\u00e9\u00f8\u00d7bar\n"}); + +testCM("groupMovementCommands", function(cm) { + cm.execCommand("goGroupLeft"); + eqCursorPos(cm.getCursor(), Pos(0, 0)); + cm.execCommand("goGroupRight"); + eqCursorPos(cm.getCursor(), Pos(0, 4, "before")); + cm.execCommand("goGroupRight"); + eqCursorPos(cm.getCursor(), Pos(0, 7, "before")); + cm.execCommand("goGroupRight"); + eqCursorPos(cm.getCursor(), Pos(0, 10, "before")); + cm.execCommand("goGroupLeft"); + eqCursorPos(cm.getCursor(), Pos(0, 7, "after")); + cm.execCommand("goGroupRight"); cm.execCommand("goGroupRight"); cm.execCommand("goGroupRight"); + eqCursorPos(cm.getCursor(), Pos(0, 15, "before")); + cm.setCursor(Pos(0, 17)); + cm.execCommand("goGroupLeft"); + eqCursorPos(cm.getCursor(), Pos(0, 16, "after")); + cm.execCommand("goGroupLeft"); + eqCursorPos(cm.getCursor(), Pos(0, 14, "after")); + cm.execCommand("goGroupRight"); cm.execCommand("goGroupRight"); + eqCursorPos(cm.getCursor(), Pos(0, 20, "before")); + cm.execCommand("goGroupRight"); + eqCursorPos(cm.getCursor(), Pos(1, 0, "after")); + cm.execCommand("goGroupRight"); + eqCursorPos(cm.getCursor(), Pos(1, 2, "before")); + cm.execCommand("goGroupRight"); + eqCursorPos(cm.getCursor(), Pos(1, 5, "before")); + cm.execCommand("goGroupLeft"); cm.execCommand("goGroupLeft"); + eqCursorPos(cm.getCursor(), Pos(1, 0, "after")); + cm.execCommand("goGroupLeft"); + eqCursorPos(cm.getCursor(), Pos(0, 20, "after")); + cm.execCommand("goGroupLeft"); + eqCursorPos(cm.getCursor(), Pos(0, 16, "after")); +}, {value: "booo ba---quux. ffff\n abc d"}); + +testCM("groupsAndWhitespace", function(cm) { + var positions = [Pos(0, 0), Pos(0, 2), Pos(0, 5), Pos(0, 9), Pos(0, 11), + Pos(1, 0), Pos(1, 2), Pos(1, 5)]; + for (var i = 1; i < positions.length; i++) { + cm.execCommand("goGroupRight"); + eqCharPos(cm.getCursor(), positions[i]); + } + for (var i = positions.length - 2; i >= 0; i--) { + cm.execCommand("goGroupLeft"); + eqCharPos(cm.getCursor(), i == 2 ? Pos(0, 6, "before") : positions[i]); + } +}, {value: " foo +++ \n bar"}); + +testCM("charMovementCommands", function(cm) { + cm.execCommand("goCharLeft"); cm.execCommand("goColumnLeft"); + eqCursorPos(cm.getCursor(), Pos(0, 0)); + cm.execCommand("goCharRight"); cm.execCommand("goCharRight"); + eqCursorPos(cm.getCursor(), Pos(0, 2, "before")); + cm.setCursor(Pos(1, 0)); + cm.execCommand("goColumnLeft"); + eqCursorPos(cm.getCursor(), Pos(1, 0)); + cm.execCommand("goCharLeft"); + eqCursorPos(cm.getCursor(), Pos(0, 5, "before")); + cm.execCommand("goColumnRight"); + eqCursorPos(cm.getCursor(), Pos(0, 5, "before")); + cm.execCommand("goCharRight"); + eqCursorPos(cm.getCursor(), Pos(1, 0, "after")); + cm.execCommand("goLineEnd"); + eqCursorPos(cm.getCursor(), Pos(1, 5, "before")); + cm.execCommand("goLineStartSmart"); + eqCursorPos(cm.getCursor(), Pos(1, 1, "after")); + cm.execCommand("goLineStartSmart"); + eqCursorPos(cm.getCursor(), Pos(1, 0, "after")); + cm.setCursor(Pos(2, 0)); + cm.execCommand("goCharRight"); cm.execCommand("goColumnRight"); + eqCursorPos(cm.getCursor(), Pos(2, 0)); +}, {value: "line1\n ine2\n"}); + +testCM("verticalMovementCommands", function(cm) { + cm.execCommand("goLineUp"); + eqCharPos(cm.getCursor(), Pos(0, 0)); + cm.execCommand("goLineDown"); + if (!phantom) // This fails in PhantomJS, though not in a real Webkit + eqCharPos(cm.getCursor(), Pos(1, 0)); + cm.setCursor(Pos(1, 12)); + cm.execCommand("goLineDown"); + eqCharPos(cm.getCursor(), Pos(2, 5)); + cm.execCommand("goLineDown"); + eqCharPos(cm.getCursor(), Pos(3, 0)); + cm.execCommand("goLineUp"); + eqCharPos(cm.getCursor(), Pos(2, 5)); + cm.execCommand("goLineUp"); + eqCharPos(cm.getCursor(), Pos(1, 12)); + cm.execCommand("goPageDown"); + eqCharPos(cm.getCursor(), Pos(5, 0)); + cm.execCommand("goPageDown"); cm.execCommand("goLineDown"); + eqCharPos(cm.getCursor(), Pos(5, 0)); + cm.execCommand("goPageUp"); + eqCharPos(cm.getCursor(), Pos(0, 0)); +}, {value: "line1\nlong long line2\nline3\n\nline5\n"}); + +testCM("verticalMovementCommandsWrapping", function(cm) { + cm.setSize(120); + cm.setCursor(Pos(0, 5)); + cm.execCommand("goLineDown"); + eq(cm.getCursor().line, 0); + is(cm.getCursor().ch > 5, "moved beyond wrap"); + for (var i = 0; ; ++i) { + is(i < 20, "no endless loop"); + cm.execCommand("goLineDown"); + var cur = cm.getCursor(); + if (cur.line == 1) eq(cur.ch, 5); + if (cur.line == 2) { eq(cur.ch, 1); break; } + } +}, {value: "a very long line that wraps around somehow so that we can test cursor movement\nshortone\nk", + lineWrapping: true}); + +testCM("verticalMovementCommandsSingleLine", function(cm) { + cm.display.wrapper.style.height = "auto"; + cm.refresh(); + cm.execCommand("goLineUp"); + eqCursorPos(cm.getCursor(), Pos(0, 0)); + cm.execCommand("goLineDown"); + eqCursorPos(cm.getCursor(), Pos(0, 11)); + cm.setCursor(Pos(0, 5)); + cm.execCommand("goLineDown"); + eqCursorPos(cm.getCursor(), Pos(0, 11)); + cm.execCommand("goLineDown"); + eqCursorPos(cm.getCursor(), Pos(0, 11)); + cm.execCommand("goLineUp"); + eqCursorPos(cm.getCursor(), Pos(0, 0)); + cm.execCommand("goLineUp"); + eqCursorPos(cm.getCursor(), Pos(0, 0)); + cm.execCommand("goPageDown"); + eqCursorPos(cm.getCursor(), Pos(0, 11)); + cm.execCommand("goPageDown"); cm.execCommand("goLineDown"); + eqCursorPos(cm.getCursor(), Pos(0, 11)); + cm.execCommand("goPageUp"); + eqCursorPos(cm.getCursor(), Pos(0, 0)); + cm.setCursor(Pos(0, 5)); + cm.execCommand("goPageUp"); + eqCursorPos(cm.getCursor(), Pos(0, 0)); + cm.setCursor(Pos(0, 5)); + cm.execCommand("goPageDown"); + eqCursorPos(cm.getCursor(), Pos(0, 11)); +}, {value: "single line"}); + + +testCM("rtlMovement", function(cm) { + if (cm.getOption("inputStyle") != "textarea") return; + forEach(["خحج", "خحabcخحج", "abخحخحجcd", "abخde", "abخح2342خ1حج", "خ1ح2خح3حxج", + "خحcd", "1خحcd", "abcdeح1ج", "خمرحبها مها!", "foobarر", "خ ة ق", + "<img src=\"/בדיקה3.jpg\">", "يتم السحب في 05 فبراير 2014"], function(line) { + cm.setValue(line + "\n"); cm.execCommand("goLineStart"); + var cursors = byClassName(cm.getWrapperElement(), "CodeMirror-cursors")[0]; + var cursor = cursors.firstChild; + var prevX = cursor.offsetLeft, prevY = cursor.offsetTop; + for (var i = 0; i <= line.length; ++i) { + cm.execCommand("goCharRight"); + cursor = cursors.firstChild; + if (i == line.length) is(cursor.offsetTop > prevY, "next line"); + else is(cursor.offsetLeft > prevX, "moved right"); + prevX = cursor.offsetLeft; prevY = cursor.offsetTop; + } + cm.setCursor(0, 0); cm.execCommand("goLineEnd"); + prevX = cursors.firstChild.offsetLeft; + for (var i = 0; i < line.length; ++i) { + cm.execCommand("goCharLeft"); + cursor = cursors.firstChild; + is(cursor.offsetLeft < prevX, "moved left"); + prevX = cursor.offsetLeft; + } + }); +}, null, ie_lt9); + +// Verify that updating a line clears its bidi ordering +testCM("bidiUpdate", function(cm) { + cm.setCursor(Pos(0, 2, "before")); + cm.replaceSelection("خحج", "start"); + cm.execCommand("goCharRight"); + eqCursorPos(cm.getCursor(), Pos(0, 6, "before")); +}, {value: "abcd\n"}); + +testCM("movebyTextUnit", function(cm) { + cm.setValue("בְּרֵאשִ\nééé́\n"); + cm.execCommand("goLineStart"); + for (var i = 0; i < 4; ++i) cm.execCommand("goCharRight"); + eqCursorPos(cm.getCursor(), Pos(0, 0, "after")); + cm.execCommand("goCharRight"); + eqCursorPos(cm.getCursor(), Pos(1, 0, "after")); + cm.execCommand("goCharRight"); + cm.execCommand("goCharRight"); + eqCursorPos(cm.getCursor(), Pos(1, 4, "before")); + cm.execCommand("goCharRight"); + eqCursorPos(cm.getCursor(), Pos(1, 7, "before")); +}); + +testCM("lineChangeEvents", function(cm) { + addDoc(cm, 3, 5); + var log = [], want = ["ch 0", "ch 1", "del 2", "ch 0", "ch 0", "del 1", "del 3", "del 4"]; + for (var i = 0; i < 5; ++i) { + CodeMirror.on(cm.getLineHandle(i), "delete", function(i) { + return function() {log.push("del " + i);}; + }(i)); + CodeMirror.on(cm.getLineHandle(i), "change", function(i) { + return function() {log.push("ch " + i);}; + }(i)); + } + cm.replaceRange("x", Pos(0, 1)); + cm.replaceRange("xy", Pos(1, 1), Pos(2)); + cm.replaceRange("foo\nbar", Pos(0, 1)); + cm.replaceRange("", Pos(0, 0), Pos(cm.lineCount())); + eq(log.length, want.length, "same length"); + for (var i = 0; i < log.length; ++i) + eq(log[i], want[i]); +}); + +testCM("scrollEntirelyToRight", function(cm) { + if (phantom || cm.getOption("inputStyle") != "textarea") return; + addDoc(cm, 500, 2); + cm.setCursor(Pos(0, 500)); + var wrap = cm.getWrapperElement(), cur = byClassName(wrap, "CodeMirror-cursor")[0]; + is(wrap.getBoundingClientRect().right > cur.getBoundingClientRect().left); +}); + +testCM("lineWidgets", function(cm) { + addDoc(cm, 500, 3); + var last = cm.charCoords(Pos(2, 0)); + var node = document.createElement("div"); + node.innerHTML = "hi"; + var widget = cm.addLineWidget(1, node); + is(last.top < cm.charCoords(Pos(2, 0)).top, "took up space"); + cm.setCursor(Pos(1, 1)); + cm.execCommand("goLineDown"); + eqCharPos(cm.getCursor(), Pos(2, 1)); + cm.execCommand("goLineUp"); + eqCharPos(cm.getCursor(), Pos(1, 1)); +}); + +testCM("lineWidgetFocus", function(cm) { + var place = document.getElementById("testground"); + place.className = "offscreen"; + try { + addDoc(cm, 500, 10); + var node = document.createElement("input"); + var widget = cm.addLineWidget(1, node); + node.focus(); + eq(document.activeElement, node); + cm.replaceRange("new stuff", Pos(1, 0)); + eq(document.activeElement, node); + } finally { + place.className = ""; + } +}); + +testCM("lineWidgetCautiousRedraw", function(cm) { + var node = document.createElement("div"); + node.innerHTML = "hahah"; + var w = cm.addLineWidget(0, node); + var redrawn = false; + w.on("redraw", function() { redrawn = true; }); + cm.replaceSelection("0"); + is(!redrawn); +}, {value: "123\n456"}); + + +var knownScrollbarWidth; +function scrollbarWidth(measure) { + if (knownScrollbarWidth != null) return knownScrollbarWidth; + var div = document.createElement('div'); + div.style.cssText = "width: 50px; height: 50px; overflow-x: scroll"; + document.body.appendChild(div); + knownScrollbarWidth = div.offsetHeight - div.clientHeight; + document.body.removeChild(div); + return knownScrollbarWidth || 0; +} + +testCM("lineWidgetChanged", function(cm) { + addDoc(cm, 2, 300); + var halfScrollbarWidth = scrollbarWidth(cm.display.measure)/2; + cm.setOption('lineNumbers', true); + cm.setSize(600, cm.defaultTextHeight() * 50); + cm.scrollTo(null, cm.heightAtLine(125, "local")); + + var expectedWidgetHeight = 60; + var expectedLinesInWidget = 3; + function w() { + var node = document.createElement("div"); + // we use these children with just under half width of the line to check measurements are made with correct width + // when placed in the measure div. + // If the widget is measured at a width much narrower than it is displayed at, the underHalf children will span two lines and break the test. + // If the widget is measured at a width much wider than it is displayed at, the overHalf children will combine and break the test. + // Note that this test only checks widgets where coverGutter is true, because these require extra styling to get the width right. + // It may also be worthwhile to check this for non-coverGutter widgets. + // Visually: + // Good: + // | ------------- display width ------------- | + // | ------- widget-width when measured ------ | + // | | -- under-half -- | | -- under-half -- | | + // | | --- over-half --- | | + // | | --- over-half --- | | + // Height: measured as 3 lines, same as it will be when actually displayed + + // Bad (too narrow): + // | ------------- display width ------------- | + // | ------ widget-width when measured ----- | < -- uh oh + // | | -- under-half -- | | + // | | -- under-half -- | | < -- when measured, shoved to next line + // | | --- over-half --- | | + // | | --- over-half --- | | + // Height: measured as 4 lines, more than expected . Will be displayed as 3 lines! + + // Bad (too wide): + // | ------------- display width ------------- | + // | -------- widget-width when measured ------- | < -- uh oh + // | | -- under-half -- | | -- under-half -- | | + // | | --- over-half --- | | --- over-half --- | | < -- when measured, combined on one line + // Height: measured as 2 lines, less than expected. Will be displayed as 3 lines! + + var barelyUnderHalfWidthHtml = '<div style="display: inline-block; height: 1px; width: '+(285 - halfScrollbarWidth)+'px;"></div>'; + var barelyOverHalfWidthHtml = '<div style="display: inline-block; height: 1px; width: '+(305 - halfScrollbarWidth)+'px;"></div>'; + node.innerHTML = new Array(3).join(barelyUnderHalfWidthHtml) + new Array(3).join(barelyOverHalfWidthHtml); + node.style.cssText = "background: yellow;font-size:0;line-height: " + (expectedWidgetHeight/expectedLinesInWidget) + "px;"; + return node; + } + var info0 = cm.getScrollInfo(); + var w0 = cm.addLineWidget(0, w(), { coverGutter: true }); + var w150 = cm.addLineWidget(150, w(), { coverGutter: true }); + var w300 = cm.addLineWidget(300, w(), { coverGutter: true }); + var info1 = cm.getScrollInfo(); + eq(info0.height + (3 * expectedWidgetHeight), info1.height); + eq(info0.top + expectedWidgetHeight, info1.top); + expectedWidgetHeight = 12; + w0.node.style.lineHeight = w150.node.style.lineHeight = w300.node.style.lineHeight = (expectedWidgetHeight/expectedLinesInWidget) + "px"; + w0.changed(); w150.changed(); w300.changed(); + var info2 = cm.getScrollInfo(); + eq(info0.height + (3 * expectedWidgetHeight), info2.height); + eq(info0.top + expectedWidgetHeight, info2.top); +}); + +testCM("getLineNumber", function(cm) { + addDoc(cm, 2, 20); + var h1 = cm.getLineHandle(1); + eq(cm.getLineNumber(h1), 1); + cm.replaceRange("hi\nbye\n", Pos(0, 0)); + eq(cm.getLineNumber(h1), 3); + cm.setValue(""); + eq(cm.getLineNumber(h1), null); +}); + +testCM("jumpTheGap", function(cm) { + if (phantom) return; + var longLine = "abcdef ghiklmnop qrstuvw xyz "; + longLine += longLine; longLine += longLine; longLine += longLine; + cm.replaceRange(longLine, Pos(2, 0), Pos(2)); + cm.setSize("200px", null); + cm.getWrapperElement().style.lineHeight = 2; + cm.refresh(); + cm.setCursor(Pos(0, 1)); + cm.execCommand("goLineDown"); + eqCharPos(cm.getCursor(), Pos(1, 1)); + cm.execCommand("goLineDown"); + eqCharPos(cm.getCursor(), Pos(2, 1)); + cm.execCommand("goLineDown"); + eq(cm.getCursor().line, 2); + is(cm.getCursor().ch > 1); + cm.execCommand("goLineUp"); + eqCharPos(cm.getCursor(), Pos(2, 1)); + cm.execCommand("goLineUp"); + eqCharPos(cm.getCursor(), Pos(1, 1)); + var node = document.createElement("div"); + node.innerHTML = "hi"; node.style.height = "30px"; + cm.addLineWidget(0, node); + cm.addLineWidget(1, node.cloneNode(true), {above: true}); + cm.setCursor(Pos(0, 2)); + cm.execCommand("goLineDown"); + eqCharPos(cm.getCursor(), Pos(1, 2)); + cm.execCommand("goLineUp"); + eqCharPos(cm.getCursor(), Pos(0, 2)); +}, {lineWrapping: true, value: "abc\ndef\nghi\njkl\n"}); + +testCM("addLineClass", function(cm) { + function cls(line, text, bg, wrap, gutter) { + var i = cm.lineInfo(line); + eq(i.textClass, text); + eq(i.bgClass, bg); + eq(i.wrapClass, wrap); + if (typeof i.handle.gutterClass !== 'undefined') { + eq(i.handle.gutterClass, gutter); + } + } + cm.addLineClass(0, "text", "foo"); + cm.addLineClass(0, "text", "bar"); + cm.addLineClass(1, "background", "baz"); + cm.addLineClass(1, "wrap", "foo"); + cm.addLineClass(1, "gutter", "gutter-class"); + cls(0, "foo bar", null, null, null); + cls(1, null, "baz", "foo", "gutter-class"); + var lines = cm.display.lineDiv; + eq(byClassName(lines, "foo").length, 2); + eq(byClassName(lines, "bar").length, 1); + eq(byClassName(lines, "baz").length, 1); + eq(byClassName(lines, "gutter-class").length, 2); // Gutter classes are reflected in 2 nodes + cm.removeLineClass(0, "text", "foo"); + cls(0, "bar", null, null, null); + cm.removeLineClass(0, "text", "foo"); + cls(0, "bar", null, null, null); + cm.removeLineClass(0, "text", "bar"); + cls(0, null, null, null); + + cm.addLineClass(1, "wrap", "quux"); + cls(1, null, "baz", "foo quux", "gutter-class"); + cm.removeLineClass(1, "wrap"); + cls(1, null, "baz", null, "gutter-class"); + cm.removeLineClass(1, "gutter", "gutter-class"); + eq(byClassName(lines, "gutter-class").length, 0); + cls(1, null, "baz", null, null); + + cm.addLineClass(1, "gutter", "gutter-class"); + cls(1, null, "baz", null, "gutter-class"); + cm.removeLineClass(1, "gutter", "gutter-class"); + cls(1, null, "baz", null, null); + +}, {value: "hohoho\n", lineNumbers: true}); + +testCM("atomicMarker", function(cm) { + addDoc(cm, 10, 10); + function atom(ll, cl, lr, cr, li, ri) { + return cm.markText(Pos(ll, cl), Pos(lr, cr), + {atomic: true, inclusiveLeft: li, inclusiveRight: ri}); + } + var m = atom(0, 1, 0, 5); + cm.setCursor(Pos(0, 1)); + cm.execCommand("goCharRight"); + eqCursorPos(cm.getCursor(), Pos(0, 5)); + cm.execCommand("goCharLeft"); + eqCursorPos(cm.getCursor(), Pos(0, 1)); + m.clear(); + m = atom(0, 0, 0, 5, true); + eqCursorPos(cm.getCursor(), Pos(0, 5), "pushed out"); + cm.execCommand("goCharLeft"); + eqCursorPos(cm.getCursor(), Pos(0, 5)); + m.clear(); + m = atom(8, 4, 9, 10, false, true); + cm.setCursor(Pos(9, 8)); + eqCursorPos(cm.getCursor(), Pos(8, 4), "set"); + cm.execCommand("goCharRight"); + eqCursorPos(cm.getCursor(), Pos(8, 4), "char right"); + cm.execCommand("goLineDown"); + eqCursorPos(cm.getCursor(), Pos(8, 4), "line down"); + cm.execCommand("goCharLeft"); + eqCursorPos(cm.getCursor(), Pos(8, 3, "after")); + m.clear(); + m = atom(1, 1, 3, 8); + cm.setCursor(Pos(0, 0)); + cm.setCursor(Pos(2, 0)); + eqCursorPos(cm.getCursor(), Pos(3, 8)); + cm.execCommand("goCharLeft"); + eqCursorPos(cm.getCursor(), Pos(1, 1)); + cm.execCommand("goCharRight"); + eqCursorPos(cm.getCursor(), Pos(3, 8)); + cm.execCommand("goLineUp"); + eqCursorPos(cm.getCursor(), Pos(1, 1)); + cm.execCommand("goLineDown"); + eqCursorPos(cm.getCursor(), Pos(3, 8)); + cm.execCommand("delCharBefore"); + eq(cm.getValue().length, 80, "del chunk"); + m = atom(3, 0, 5, 5); + cm.setCursor(Pos(3, 0)); + cm.execCommand("delWordAfter"); + eq(cm.getValue().length, 53, "del chunk"); +}); + +testCM("selectionBias", function(cm) { + cm.markText(Pos(0, 1), Pos(0, 3), {atomic: true}); + cm.setCursor(Pos(0, 2)); + eqCursorPos(cm.getCursor(), Pos(0, 1)); + cm.setCursor(Pos(0, 2)); + eqCursorPos(cm.getCursor(), Pos(0, 3)); + cm.setCursor(Pos(0, 2)); + eqCursorPos(cm.getCursor(), Pos(0, 1)); + cm.setCursor(Pos(0, 2), null, {bias: -1}); + eqCursorPos(cm.getCursor(), Pos(0, 1)); + cm.setCursor(Pos(0, 4)); + cm.setCursor(Pos(0, 2), null, {bias: 1}); + eqCursorPos(cm.getCursor(), Pos(0, 3)); +}, {value: "12345"}); + +testCM("selectionHomeEnd", function(cm) { + cm.markText(Pos(1, 0), Pos(1, 1), {atomic: true, inclusiveLeft: true}); + cm.markText(Pos(1, 3), Pos(1, 4), {atomic: true, inclusiveRight: true}); + cm.setCursor(Pos(1, 2)); + cm.execCommand("goLineStart"); + eqCursorPos(cm.getCursor(), Pos(1, 1)); + cm.execCommand("goLineEnd"); + eqCursorPos(cm.getCursor(), Pos(1, 3)); +}, {value: "ab\ncdef\ngh"}); + +testCM("readOnlyMarker", function(cm) { + function mark(ll, cl, lr, cr, at) { + return cm.markText(Pos(ll, cl), Pos(lr, cr), + {readOnly: true, atomic: at}); + } + var m = mark(0, 1, 0, 4); + cm.setCursor(Pos(0, 2)); + cm.replaceSelection("hi", "end"); + eqCursorPos(cm.getCursor(), Pos(0, 2)); + eq(cm.getLine(0), "abcde"); + cm.execCommand("selectAll"); + cm.replaceSelection("oops", "around"); + eq(cm.getValue(), "oopsbcd"); + cm.undo(); + eqCursorPos(m.find().from, Pos(0, 1)); + eqCursorPos(m.find().to, Pos(0, 4)); + m.clear(); + cm.setCursor(Pos(0, 2)); + cm.replaceSelection("hi", "around"); + eq(cm.getLine(0), "abhicde"); + eqCursorPos(cm.getCursor(), Pos(0, 4)); + m = mark(0, 2, 2, 2, true); + cm.setSelection(Pos(1, 1), Pos(2, 4)); + cm.replaceSelection("t", "end"); + eqCursorPos(cm.getCursor(), Pos(2, 3)); + eq(cm.getLine(2), "klto"); + cm.execCommand("goCharLeft"); + cm.execCommand("goCharLeft"); + eqCursorPos(cm.getCursor(), Pos(0, 2)); + cm.setSelection(Pos(0, 1), Pos(0, 3)); + cm.replaceSelection("xx", "around"); + eqCursorPos(cm.getCursor(), Pos(0, 3)); + eq(cm.getLine(0), "axxhicde"); +}, {value: "abcde\nfghij\nklmno\n"}); + +testCM("dirtyBit", function(cm) { + eq(cm.isClean(), true); + cm.replaceSelection("boo", null, "test"); + eq(cm.isClean(), false); + cm.undo(); + eq(cm.isClean(), true); + cm.replaceSelection("boo", null, "test"); + cm.replaceSelection("baz", null, "test"); + cm.undo(); + eq(cm.isClean(), false); + cm.markClean(); + eq(cm.isClean(), true); + cm.undo(); + eq(cm.isClean(), false); + cm.redo(); + eq(cm.isClean(), true); +}); + +testCM("changeGeneration", function(cm) { + cm.replaceSelection("x"); + var softGen = cm.changeGeneration(); + cm.replaceSelection("x"); + cm.undo(); + eq(cm.getValue(), ""); + is(!cm.isClean(softGen)); + cm.replaceSelection("x"); + var hardGen = cm.changeGeneration(true); + cm.replaceSelection("x"); + cm.undo(); + eq(cm.getValue(), "x"); + is(cm.isClean(hardGen)); +}); + +testCM("addKeyMap", function(cm) { + function sendKey(code) { + cm.triggerOnKeyDown({type: "keydown", keyCode: code, + preventDefault: function(){}, stopPropagation: function(){}}); + } + + sendKey(39); + eqCursorPos(cm.getCursor(), Pos(0, 1, "before")); + var test = 0; + var map1 = {Right: function() { ++test; }}, map2 = {Right: function() { test += 10; }} + cm.addKeyMap(map1); + sendKey(39); + eqCursorPos(cm.getCursor(), Pos(0, 1, "before")); + eq(test, 1); + cm.addKeyMap(map2, true); + sendKey(39); + eq(test, 2); + cm.removeKeyMap(map1); + sendKey(39); + eq(test, 12); + cm.removeKeyMap(map2); + sendKey(39); + eq(test, 12); + eqCursorPos(cm.getCursor(), Pos(0, 2, "before")); + cm.addKeyMap({Right: function() { test = 55; }, name: "mymap"}); + sendKey(39); + eq(test, 55); + cm.removeKeyMap("mymap"); + sendKey(39); + eqCursorPos(cm.getCursor(), Pos(0, 3, "before")); +}, {value: "abc"}); + +function mouseDown(cm, button, pos, mods) { + var coords = cm.charCoords(pos, "window") + var event = {type: "mousedown", + preventDefault: Math.min, + which: button, + target: cm.display.lineDiv, + clientX: coords.left, clientY: coords.top} + if (mods) for (var prop in mods) event[prop] = mods[prop] + cm.triggerOnMouseDown(event) +} + +testCM("mouseBinding", function(cm) { + var fired = [] + cm.addKeyMap({ + "Shift-LeftClick": function(_cm, pos) { + eqCharPos(pos, Pos(1, 2)) + fired.push("a") + }, + "Shift-LeftDoubleClick": function() { fired.push("b") }, + "Shift-LeftTripleClick": function() { fired.push("c") } + }) + + function send(button, mods) { mouseDown(cm, button, Pos(1, 2), mods) } + send(1, {shiftKey: true}) + send(1, {shiftKey: true}) + send(1, {shiftKey: true}) + send(1, {}) + send(2, {ctrlKey: true}) + send(2, {ctrlKey: true}) + eq(fired.join(" "), "a b c") +}, {value: "foo\nbar\nbaz"}) + +testCM("configureMouse", function(cm) { + cm.setOption("configureMouse", function() { return {unit: "word"} }) + mouseDown(cm, 1, Pos(0, 5)) + eqCharPos(cm.getCursor("from"), Pos(0, 4)) + eqCharPos(cm.getCursor("to"), Pos(0, 7)) + cm.setOption("configureMouse", function() { return {extend: true} }) + mouseDown(cm, 1, Pos(0, 0)) + eqCharPos(cm.getCursor("from"), Pos(0, 0)) + eqCharPos(cm.getCursor("to"), Pos(0, 4)) +}, {value: "foo bar baz"}) + +testCM("findPosH", function(cm) { + forEach([{from: Pos(0, 0), to: Pos(0, 1, "before"), by: 1}, + {from: Pos(0, 0), to: Pos(0, 0), by: -1, hitSide: true}, + {from: Pos(0, 0), to: Pos(0, 4, "before"), by: 1, unit: "word"}, + {from: Pos(0, 0), to: Pos(0, 8, "before"), by: 2, unit: "word"}, + {from: Pos(0, 0), to: Pos(2, 0, "after"), by: 20, unit: "word", hitSide: true}, + {from: Pos(0, 7), to: Pos(0, 5, "after"), by: -1, unit: "word"}, + {from: Pos(0, 4), to: Pos(0, 8, "before"), by: 1, unit: "word"}, + {from: Pos(1, 0), to: Pos(1, 18, "before"), by: 3, unit: "word"}, + {from: Pos(1, 22), to: Pos(1, 5, "after"), by: -3, unit: "word"}, + {from: Pos(1, 15), to: Pos(1, 10, "after"), by: -5}, + {from: Pos(1, 15), to: Pos(1, 10, "after"), by: -5, unit: "column"}, + {from: Pos(1, 15), to: Pos(1, 0, "after"), by: -50, unit: "column", hitSide: true}, + {from: Pos(1, 15), to: Pos(1, 24, "before"), by: 50, unit: "column", hitSide: true}, + {from: Pos(1, 15), to: Pos(2, 0, "after"), by: 50, hitSide: true}], function(t) { + var r = cm.findPosH(t.from, t.by, t.unit || "char"); + eqCursorPos(r, t.to); + eq(!!r.hitSide, !!t.hitSide); + }); +}, {value: "line one\nline two.something.other\n"}); + +testCM("beforeChange", function(cm) { + cm.on("beforeChange", function(cm, change) { + var text = []; + for (var i = 0; i < change.text.length; ++i) + text.push(change.text[i].replace(/\s/g, "_")); + change.update(null, null, text); + }); + cm.setValue("hello, i am a\nnew document\n"); + eq(cm.getValue(), "hello,_i_am_a\nnew_document\n"); + CodeMirror.on(cm.getDoc(), "beforeChange", function(doc, change) { + if (change.from.line == 0) change.cancel(); + }); + cm.setValue("oops"); // Canceled + eq(cm.getValue(), "hello,_i_am_a\nnew_document\n"); + cm.replaceRange("hey hey hey", Pos(1, 0), Pos(2, 0)); + eq(cm.getValue(), "hello,_i_am_a\nhey_hey_hey"); +}, {value: "abcdefghijk"}); + +testCM("beforeChangeUndo", function(cm) { + cm.replaceRange("hi", Pos(0, 0), Pos(0)); + cm.replaceRange("bye", Pos(0, 0), Pos(0)); + eq(cm.historySize().undo, 2); + cm.on("beforeChange", function(cm, change) { + is(!change.update); + change.cancel(); + }); + cm.undo(); + eq(cm.historySize().undo, 0); + eq(cm.getValue(), "bye\ntwo"); +}, {value: "one\ntwo"}); + +testCM("beforeSelectionChange", function(cm) { + function notAtEnd(cm, pos) { + var len = cm.getLine(pos.line).length; + if (!len || pos.ch == len) return Pos(pos.line, pos.ch - 1); + return pos; + } + cm.on("beforeSelectionChange", function(cm, obj) { + obj.update([{anchor: notAtEnd(cm, obj.ranges[0].anchor), + head: notAtEnd(cm, obj.ranges[0].head)}]); + }); + + addDoc(cm, 10, 10); + cm.execCommand("goLineEnd"); + eqCursorPos(cm.getCursor(), Pos(0, 9)); + cm.execCommand("selectAll"); + eqCursorPos(cm.getCursor("start"), Pos(0, 0)); + eqCursorPos(cm.getCursor("end"), Pos(9, 9)); +}); + +testCM("change_removedText", function(cm) { + cm.setValue("abc\ndef"); + + var removedText = []; + cm.on("change", function(cm, change) { + removedText.push(change.removed); + }); + + cm.operation(function() { + cm.replaceRange("xyz", Pos(0, 0), Pos(1,1)); + cm.replaceRange("123", Pos(0,0)); + }); + + eq(removedText.length, 2); + eq(removedText[0].join("\n"), "abc\nd"); + eq(removedText[1].join("\n"), ""); + + var removedText = []; + cm.undo(); + eq(removedText.length, 2); + eq(removedText[0].join("\n"), "123"); + eq(removedText[1].join("\n"), "xyz"); + + var removedText = []; + cm.redo(); + eq(removedText.length, 2); + eq(removedText[0].join("\n"), "abc\nd"); + eq(removedText[1].join("\n"), ""); +}); + +testCM("lineStyleFromMode", function(cm) { + CodeMirror.defineMode("test_mode", function() { + return {token: function(stream) { + if (stream.match(/^\[[^\]]*\]/)) return " line-brackets "; + if (stream.match(/^\([^\)]*\)/)) return " line-background-parens "; + if (stream.match(/^<[^>]*>/)) return " span line-line line-background-bg "; + stream.match(/^\s+|^\S+/); + }}; + }); + cm.setOption("mode", "test_mode"); + var bracketElts = byClassName(cm.getWrapperElement(), "brackets"); + eq(bracketElts.length, 1, "brackets count"); + eq(bracketElts[0].nodeName, "PRE"); + is(!/brackets.*brackets/.test(bracketElts[0].className)); + var parenElts = byClassName(cm.getWrapperElement(), "parens"); + eq(parenElts.length, 1, "parens count"); + eq(parenElts[0].nodeName, "DIV"); + is(!/parens.*parens/.test(parenElts[0].className)); + eq(parenElts[0].parentElement.nodeName, "DIV"); + + is(byClassName(cm.getWrapperElement(), "bg").length > 0); + is(byClassName(cm.getWrapperElement(), "line").length > 0); + var spanElts = byClassName(cm.getWrapperElement(), "cm-span"); + eq(spanElts.length, 2); + is(/^\s*cm-span\s*$/.test(spanElts[0].className)); +}, {value: "line1: [br] [br]\nline2: (par) (par)\nline3: <tag> <tag>"}); + +testCM("lineStyleFromBlankLine", function(cm) { + CodeMirror.defineMode("lineStyleFromBlankLine_mode", function() { + return {token: function(stream) { stream.skipToEnd(); return "comment"; }, + blankLine: function() { return "line-blank"; }}; + }); + cm.setOption("mode", "lineStyleFromBlankLine_mode"); + var blankElts = byClassName(cm.getWrapperElement(), "blank"); + eq(blankElts.length, 1); + eq(blankElts[0].nodeName, "PRE"); + cm.replaceRange("x", Pos(1, 0)); + blankElts = byClassName(cm.getWrapperElement(), "blank"); + eq(blankElts.length, 0); +}, {value: "foo\n\nbar"}); + +CodeMirror.registerHelper("xxx", "a", "A"); +CodeMirror.registerHelper("xxx", "b", "B"); +CodeMirror.defineMode("yyy", function() { + return { + token: function(stream) { stream.skipToEnd(); }, + xxx: ["a", "b", "q"] + }; +}); +CodeMirror.registerGlobalHelper("xxx", "c", function(m) { return m.enableC; }, "C"); + +testCM("helpers", function(cm) { + cm.setOption("mode", "yyy"); + eq(cm.getHelpers(Pos(0, 0), "xxx").join("/"), "A/B"); + cm.setOption("mode", {name: "yyy", modeProps: {xxx: "b", enableC: true}}); + eq(cm.getHelpers(Pos(0, 0), "xxx").join("/"), "B/C"); + cm.setOption("mode", "javascript"); + eq(cm.getHelpers(Pos(0, 0), "xxx").join("/"), ""); +}); + +testCM("selectionHistory", function(cm) { + for (var i = 0; i < 3; i++) { + cm.setExtending(true); + cm.execCommand("goCharRight"); + cm.setExtending(false); + cm.execCommand("goCharRight"); + cm.execCommand("goCharRight"); + } + cm.execCommand("undoSelection"); + eq(cm.getSelection(), "c"); + cm.execCommand("undoSelection"); + eq(cm.getSelection(), ""); + eqCursorPos(cm.getCursor(), Pos(0, 4, "before")); + cm.execCommand("undoSelection"); + eq(cm.getSelection(), "b"); + cm.execCommand("redoSelection"); + eq(cm.getSelection(), ""); + eqCursorPos(cm.getCursor(), Pos(0, 4, "before")); + cm.execCommand("redoSelection"); + eq(cm.getSelection(), "c"); + cm.execCommand("redoSelection"); + eq(cm.getSelection(), ""); + eqCursorPos(cm.getCursor(), Pos(0, 6, "before")); +}, {value: "a b c d"}); + +testCM("selectionChangeReducesRedo", function(cm) { + cm.replaceSelection("X"); + cm.execCommand("goCharRight"); + cm.undoSelection(); + cm.execCommand("selectAll"); + cm.undoSelection(); + eq(cm.getValue(), "Xabc"); + eqCursorPos(cm.getCursor(), Pos(0, 1)); + cm.undoSelection(); + eq(cm.getValue(), "abc"); +}, {value: "abc"}); + +testCM("selectionHistoryNonOverlapping", function(cm) { + cm.setSelection(Pos(0, 0), Pos(0, 1)); + cm.setSelection(Pos(0, 2), Pos(0, 3)); + cm.execCommand("undoSelection"); + eqCursorPos(cm.getCursor("anchor"), Pos(0, 0)); + eqCursorPos(cm.getCursor("head"), Pos(0, 1)); +}, {value: "1234"}); + +testCM("cursorMotionSplitsHistory", function(cm) { + cm.replaceSelection("a"); + cm.execCommand("goCharRight"); + cm.replaceSelection("b"); + cm.replaceSelection("c"); + cm.undo(); + eq(cm.getValue(), "a1234"); + eqCursorPos(cm.getCursor(), Pos(0, 2, "before")); + cm.undo(); + eq(cm.getValue(), "1234"); + eqCursorPos(cm.getCursor(), Pos(0, 0)); +}, {value: "1234"}); + +testCM("selChangeInOperationDoesNotSplit", function(cm) { + for (var i = 0; i < 4; i++) { + cm.operation(function() { + cm.replaceSelection("x"); + cm.setCursor(Pos(0, cm.getCursor().ch - 1)); + }); + } + eqCursorPos(cm.getCursor(), Pos(0, 0)); + eq(cm.getValue(), "xxxxa"); + cm.undo(); + eq(cm.getValue(), "a"); +}, {value: "a"}); + +testCM("alwaysMergeSelEventWithChangeOrigin", function(cm) { + cm.replaceSelection("U", null, "foo"); + cm.setSelection(Pos(0, 0), Pos(0, 1), {origin: "foo"}); + cm.undoSelection(); + eq(cm.getValue(), "a"); + cm.replaceSelection("V", null, "foo"); + cm.setSelection(Pos(0, 0), Pos(0, 1), {origin: "bar"}); + cm.undoSelection(); + eq(cm.getValue(), "Va"); +}, {value: "a"}); + +testCM("getTokenAt", function(cm) { + var tokPlus = cm.getTokenAt(Pos(0, 2)); + eq(tokPlus.type, "operator"); + eq(tokPlus.string, "+"); + var toks = cm.getLineTokens(0); + eq(toks.length, 3); + forEach([["number", "1"], ["operator", "+"], ["number", "2"]], function(expect, i) { + eq(toks[i].type, expect[0]); + eq(toks[i].string, expect[1]); + }); +}, {value: "1+2", mode: "javascript"}); + +testCM("getTokenTypeAt", function(cm) { + eq(cm.getTokenTypeAt(Pos(0, 0)), "number"); + eq(cm.getTokenTypeAt(Pos(0, 6)), "string"); + cm.addOverlay({ + token: function(stream) { + if (stream.match("foo")) return "foo"; + else stream.next(); + } + }); + eq(byClassName(cm.getWrapperElement(), "cm-foo").length, 1); + eq(cm.getTokenTypeAt(Pos(0, 6)), "string"); +}, {value: "1 + 'foo'", mode: "javascript"}); + +testCM("addOverlay", function(cm) { + cm.addOverlay({ + token: function(stream) { + var base = stream.baseToken() + if (!/comment/.test(base.type) && stream.match(/\d+/)) return "x" + stream.next() + } + }) + var x = byClassName(cm.getWrapperElement(), "cm-x") + is(x.length, 1) + is(x[0].textContent, "233") + cm.replaceRange("", Pos(0, 4), Pos(0, 6)) + is(byClassName(cm.getWrapperElement(), "cm-x").length, 2) +}, {value: "foo /* 100 */\nbar + 233;\nbaz", mode: "javascript"}) + +testCM("resizeLineWidget", function(cm) { + addDoc(cm, 200, 3); + var widget = document.createElement("pre"); + widget.innerHTML = "imwidget"; + widget.style.background = "yellow"; + cm.addLineWidget(1, widget, {noHScroll: true}); + cm.setSize(40); + is(widget.parentNode.offsetWidth < 42); +}); + +testCM("combinedOperations", function(cm) { + var place = document.getElementById("testground"); + var other = CodeMirror(place, {value: "123"}); + try { + cm.operation(function() { + cm.addLineClass(0, "wrap", "foo"); + other.addLineClass(0, "wrap", "foo"); + }); + eq(byClassName(cm.getWrapperElement(), "foo").length, 1); + eq(byClassName(other.getWrapperElement(), "foo").length, 1); + cm.operation(function() { + cm.removeLineClass(0, "wrap", "foo"); + other.removeLineClass(0, "wrap", "foo"); + }); + eq(byClassName(cm.getWrapperElement(), "foo").length, 0); + eq(byClassName(other.getWrapperElement(), "foo").length, 0); + } finally { + place.removeChild(other.getWrapperElement()); + } +}, {value: "abc"}); + +testCM("eventOrder", function(cm) { + var seen = []; + cm.on("change", function() { + if (!seen.length) cm.replaceSelection("."); + seen.push("change"); + }); + cm.on("cursorActivity", function() { + cm.replaceSelection("!"); + seen.push("activity"); + }); + cm.replaceSelection("/"); + eq(seen.join(","), "change,change,activity,change"); +}); + +testCM("splitSpaces_nonspecial", function(cm) { + eq(byClassName(cm.getWrapperElement(), "cm-invalidchar").length, 0); +}, { + specialChars: /[\u00a0]/, + value: "spaces -> <- between" +}); + +test("core_rmClass", function() { + var node = document.createElement("div"); + node.className = "foo-bar baz-quux yadda"; + CodeMirror.rmClass(node, "quux"); + eq(node.className, "foo-bar baz-quux yadda"); + CodeMirror.rmClass(node, "baz-quux"); + eq(node.className, "foo-bar yadda"); + CodeMirror.rmClass(node, "yadda"); + eq(node.className, "foo-bar"); + CodeMirror.rmClass(node, "foo-bar"); + eq(node.className, ""); + node.className = " foo "; + CodeMirror.rmClass(node, "foo"); + eq(node.className, ""); +}); + +test("core_addClass", function() { + var node = document.createElement("div"); + CodeMirror.addClass(node, "a"); + eq(node.className, "a"); + CodeMirror.addClass(node, "a"); + eq(node.className, "a"); + CodeMirror.addClass(node, "b"); + eq(node.className, "a b"); + CodeMirror.addClass(node, "a"); + CodeMirror.addClass(node, "b"); + eq(node.className, "a b"); +}); + +testCM("lineSeparator", function(cm) { + eq(cm.lineCount(), 3); + eq(cm.getLine(1), "bar\r"); + eq(cm.getLine(2), "baz\rquux"); + cm.setOption("lineSeparator", "\r"); + eq(cm.lineCount(), 5); + eq(cm.getLine(4), "quux"); + eq(cm.getValue(), "foo\rbar\r\rbaz\rquux"); + eq(cm.getValue("\n"), "foo\nbar\n\nbaz\nquux"); + cm.setOption("lineSeparator", null); + cm.setValue("foo\nbar\r\nbaz\rquux"); + eq(cm.lineCount(), 4); +}, {value: "foo\nbar\r\nbaz\rquux", + lineSeparator: "\n"}); + +var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/ +var getChar = function (noExtending) { var res; do {res = String.fromCharCode(Math.floor(Math.random()*0x8ac)); } while ([0x90].indexOf(res.charCodeAt(0)) != -1 || (noExtending && extendingChars.test(res))); return res } +var getString = function (n) { var res = getChar(true); while (--n > 0) res += getChar(); return res } + +function makeItWrapAfter(cm, pos) { + var firstLineTop = cm.cursorCoords(Pos(0, 0)).top; + for(var w = 0, posTop; posTop != firstLineTop; ++w) { + cm.setSize(w); + posTop = cm.charCoords(pos).top; + } +} + +function countIf(arr, f) { + var result = 0 + for (var i = 0; i < arr.length; i++) if (f[arr[i]]) result++ + return result +} + +function testMoveBidi(str) { + testCM("move_bidi_" + str, function(cm) { + if (cm.getOption("inputStyle") != "textarea" || !cm.getOption("rtlMoveVisually")) return; + cm.getScrollerElement().style.fontFamily = "monospace"; + makeItWrapAfter(cm, Pos(0, 5)); + + var steps = str.length - countIf(str.split(""), function(ch) { return extendingChars.test(ch) }); + var lineBreaks = {} + lineBreaks[6 - countIf(str.substr(0, 5).split(""), function(ch) { return extendingChars.test(ch) })] = 'w'; + if (str.indexOf("\n") != -1) { + lineBreaks[steps - 2] = 'n'; + } + + // Make sure we are at the visual beginning of the first line + cm.execCommand("goLineStart"); + + var prevCoords = cm.cursorCoords(), coords; + for(var i = 0; i < steps; ++i) { + cm.execCommand("goCharRight"); + coords = cm.cursorCoords(); + if ((i >= 10 && i <= 12) && !lineBreaks[i] && coords.left < prevCoords.left && coords.top > prevCoords.top) { + // The first line wraps twice + lineBreaks[i] = 'w'; + } + if (!lineBreaks[i]) { + is(coords.left > prevCoords.left, "In step " + i + ", cursor didn't move right"); + eq(coords.top, prevCoords.top, "In step " + i + ", cursor moved out of line"); + } else { + is(coords.left < prevCoords.left, i); + is(coords.top > prevCoords.top, i); + } + prevCoords = coords; + } + + cm.execCommand("goCharRight"); + coords = cm.cursorCoords(); + eq(coords.left, prevCoords.left, "Moving " + steps + " steps right didn't reach the end"); + eq(coords.top, prevCoords.top, "Moving " + steps + " steps right didn't reach the end"); + + for(i = steps - 1; i >= 0; --i) { + cm.execCommand("goCharLeft"); + coords = cm.cursorCoords(); + if (!(lineBreaks[i] == 'n' || lineBreaks[i + 1] == 'w')) { + is(coords.left < prevCoords.left, "In step " + i + ", cursor didn't move left"); + eq(coords.top, prevCoords.top, "In step " + i + ", cursor is not at the same line anymore"); + } else { + is(coords.left > prevCoords.left, i); + is(coords.top < prevCoords.top, i); + } + prevCoords = coords; + } + + cm.execCommand("goCharLeft"); + coords = cm.cursorCoords(); + eq(coords.left, prevCoords.left, "Moving " + steps + " steps left didn't reach the beginning"); + eq(coords.top, prevCoords.top, "Moving " + steps + " steps left didn't reach the beginning"); + }, {value: str, lineWrapping: true}) +}; + +function testMoveEndBidi(str) { + testCM("move_end_bidi_" + str, function(cm) { + cm.getScrollerElement().style.fontFamily = "monospace"; + makeItWrapAfter(cm, Pos(0, 5)); + + cm.execCommand("goLineStart"); + var pos = cm.doc.getCursor(); + cm.execCommand("goCharLeft"); + eqCursorPos(pos, cm.doc.getCursor()); + + cm.execCommand("goLineEnd"); + pos = cm.doc.getCursor(); + cm.execCommand("goColumnRight"); + eqCursorPos(pos, cm.doc.getCursor()); + }, {value: str, lineWrapping: true}) +}; + +var bidiTests = []; + +// We don't correctly implement L1 UBA +// See https://bugzilla.mozilla.org/show_bug.cgi?id=1331501 +// and https://bugs.chromium.org/p/chromium/issues/detail?id=673405 +/* +bidiTests.push("Say ا ب جabj\nS"); +bidiTests.push("Sayyy ا ا ب ج"); +*/ + +if (!phantom) { + bidiTests.push("Όȝǝڪȉۥ״ۺ׆ɀҩۏ\nҳ"); + bidiTests.push("ŌӰтقȤ؁ƥ؅٣ĎȺ١\nϚ"); + bidiTests.push("ٻоҤѕѽΩ־؉ïίքdz\nٵ"); + bidiTests.push("؅؁ĆՕƿɁǞϮؠȩóć\nď"); + bidiTests.push("RŨďңŪzϢŎƏԖڇڦ\nӈ"); + bidiTests.push("ό׊۷٢ԜһОצЉيčǟ\nѩ"); + bidiTests.push("ۑÚҳҕڬġڹհяųKV\nr"); + bidiTests.push("źڻғúہ4ם1Ƞc1a\nԁ"); + bidiTests.push("ҒȨҟփƞ٦ԓȦڰғâƥ\nڤ"); + bidiTests.push("ϖسՉȏŧΔԛdžĎӟیڡ\nέ"); + bidiTests.push("۹ؼL۵ĺȧКԙػא7״\nم"); + bidiTests.push("ن (ي)\u2009أقواس"); // thin space to throw off Firefox 51's broken white-space compressing behavior +} + +bidiTests.push("քմѧǮßپüŢҍҞўڳ\nӧ"); + +//bidiTests.push("Count ١ ٢ ٣ ٤"); +//bidiTests.push("ӣאƦϰ؊ȓېÛوը٬ز\nϪ"); +//bidiTests.push("ҾճٳџIՖӻ٥׭֐؜ڏ\nێ"); +//bidiTests.push("ҬÓФ؜ڂį٦Ͽɓڐͳٵ\nՈ"); +//bidiTests.push("aѴNijȻهˇ҃ڱӧǻֵ\na"); +//bidiTests.push(" a٧ا٢ ب جa\nS"); + +for (var i = 0; i < bidiTests.length; ++i) { + testMoveBidi(bidiTests[i]); + testMoveEndBidi(bidiTests[i]); +} + +/* +for (var i = 0; i < 5; ++i) { + testMoveBidi(getString(12) + "\n" + getString(1)); +} +*/ + +function testCoordsWrappedBidi(str) { + testCM("coords_wrapped_bidi_" + str, function(cm) { + cm.getScrollerElement().style.fontFamily = "monospace"; + makeItWrapAfter(cm, Pos(0, 5)); + + // Make sure we are at the visual beginning of the first line + var pos = Pos(0, 0), lastPos; + cm.doc.setCursor(pos); + do { + lastPos = pos; + cm.execCommand("goCharLeft"); + pos = cm.doc.getCursor(); + } while (pos != lastPos) + + var top = cm.charCoords(Pos(0, 0)).top, lastTop; + for (var i = 1; i < str.length; ++i) { + lastTop = top; + top = cm.charCoords(Pos(0, i)).top; + is(top >= lastTop); + } + }, {value: str, lineWrapping: true}) +}; + +testCoordsWrappedBidi("Count ١ ٢ ٣ ٤"); +/* +for (var i = 0; i < 5; ++i) { + testCoordsWrappedBidi(getString(50)); +} +*/ + +testCM("rtl_wrapped_selection", function(cm) { + cm.setSelection(Pos(0, 10), Pos(0, 190)) + is(byClassName(cm.getWrapperElement(), "CodeMirror-selected").length >= 3) +}, {value: new Array(10).join(" فتي تم تضمينها فتي تم"), lineWrapping: true}) + +testCM("bidi_wrapped_selection", function(cm) { + if (phantom) return + cm.setSize(cm.charCoords(Pos(0, 10), "editor").left) + cm.setSelection(Pos(0, 37), Pos(0, 80)) + var blocks = byClassName(cm.getWrapperElement(), "CodeMirror-selected") + is(blocks.length >= 2) + is(blocks.length <= 3) + var boxTop = blocks[0].getBoundingClientRect(), boxBot = blocks[blocks.length - 1].getBoundingClientRect() + is(boxTop.left > cm.charCoords(Pos(0, 1)).right) + is(boxBot.right < cm.charCoords(Pos(0, cm.getLine(0).length - 2)).left) +}, {value: "<p>مفتي11 تم تضمينهفتي تم تضمينها فتي تفتي تم تضمينها فتي تفتي تم تضمينها فتي تفتي تم تضمينها فتي تا فت10ي ت</p>", lineWrapping: true}) + +testCM("delete_wrapped", function(cm) { + makeItWrapAfter(cm, Pos(0, 2)); + cm.doc.setCursor(Pos(0, 3, "after")); + cm.deleteH(-1, "char"); + eq(cm.getLine(0), "1245"); +}, {value: "12345", lineWrapping: true}) + +testCM("issue_4878", function(cm) { + if (phantom) return + cm.setCursor(Pos(1, 12, "after")); + cm.moveH(-1, "char"); + eqCursorPos(cm.getCursor(), Pos(0, 113, "before")); +}, {value: " في تطبيق السمات مرة واحدة https://github.com/codemirror/CodeMirror/issues/4878#issuecomment-330550964على سبيل المثال <code>\"foo bar\"</code>\n" + +" سيتم تعيين", direction: "rtl", lineWrapping: true}); + +CodeMirror.defineMode("lookahead_mode", function() { + // Colors text as atom if the line two lines down has an x in it + return { + token: function(stream) { + stream.skipToEnd() + return /x/.test(stream.lookAhead(2)) ? "atom" : null + } + } +}) + +testCM("mode_lookahead", function(cm) { + eq(cm.getTokenAt(Pos(0, 1)).type, "atom") + eq(cm.getTokenAt(Pos(1, 1)).type, "atom") + eq(cm.getTokenAt(Pos(2, 1)).type, null) + cm.replaceRange("\n", Pos(2, 0)) + eq(cm.getTokenAt(Pos(0, 1)).type, null) + eq(cm.getTokenAt(Pos(1, 1)).type, "atom") +}, {value: "foo\na\nx\nx\n", mode: "lookahead_mode"}) diff --git a/modules/editor/codemirror/theme/base16-light.css b/modules/editor/codemirror/theme/base16-light.css @@ -0,0 +1,38 @@ +/* + + Name: Base16 Default Light + Author: Chris Kempson (http://chriskempson.com) + + CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror) + Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16) + +*/ + +.cm-s-base16-light.CodeMirror { background: #f5f5f5; color: #202020; } +.cm-s-base16-light div.CodeMirror-selected { background: #e0e0e0; } +.cm-s-base16-light .CodeMirror-line::selection, .cm-s-base16-light .CodeMirror-line > span::selection, .cm-s-base16-light .CodeMirror-line > span > span::selection { background: #e0e0e0; } +.cm-s-base16-light .CodeMirror-line::-moz-selection, .cm-s-base16-light .CodeMirror-line > span::-moz-selection, .cm-s-base16-light .CodeMirror-line > span > span::-moz-selection { background: #e0e0e0; } +.cm-s-base16-light .CodeMirror-gutters { background: #f5f5f5; border-right: 0px; } +.cm-s-base16-light .CodeMirror-guttermarker { color: #ac4142; } +.cm-s-base16-light .CodeMirror-guttermarker-subtle { color: #b0b0b0; } +.cm-s-base16-light .CodeMirror-linenumber { color: #b0b0b0; } +.cm-s-base16-light .CodeMirror-cursor { border-left: 1px solid #505050; } + +.cm-s-base16-light span.cm-comment { color: #8f5536; } +.cm-s-base16-light span.cm-atom { color: #aa759f; } +.cm-s-base16-light span.cm-number { color: #aa759f; } + +.cm-s-base16-light span.cm-property, .cm-s-base16-light span.cm-attribute { color: #90a959; } +.cm-s-base16-light span.cm-keyword { color: #ac4142; } +.cm-s-base16-light span.cm-string { color: #f4bf75; } + +.cm-s-base16-light span.cm-variable { color: #90a959; } +.cm-s-base16-light span.cm-variable-2 { color: #6a9fb5; } +.cm-s-base16-light span.cm-def { color: #d28445; } +.cm-s-base16-light span.cm-bracket { color: #202020; } +.cm-s-base16-light span.cm-tag { color: #ac4142; } +.cm-s-base16-light span.cm-link { color: #aa759f; } +.cm-s-base16-light span.cm-error { background: #ac4142; color: #505050; } + +.cm-s-base16-light .CodeMirror-activeline-background { background: #DDDCDC; } +.cm-s-base16-light .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; } diff --git a/modules/editor/codemirror/theme/mbo.css b/modules/editor/codemirror/theme/mbo.css @@ -0,0 +1,37 @@ +/****************************************************************/ +/* Based on mbonaci's Brackets mbo theme */ +/* https://github.com/mbonaci/global/blob/master/Mbo.tmTheme */ +/* Create your own: http://tmtheme-editor.herokuapp.com */ +/****************************************************************/ + +.cm-s-mbo.CodeMirror { background: #2c2c2c; color: #ffffec; } +.cm-s-mbo div.CodeMirror-selected { background: #716C62; } +.cm-s-mbo .CodeMirror-line::selection, .cm-s-mbo .CodeMirror-line > span::selection, .cm-s-mbo .CodeMirror-line > span > span::selection { background: rgba(113, 108, 98, .99); } +.cm-s-mbo .CodeMirror-line::-moz-selection, .cm-s-mbo .CodeMirror-line > span::-moz-selection, .cm-s-mbo .CodeMirror-line > span > span::-moz-selection { background: rgba(113, 108, 98, .99); } +.cm-s-mbo .CodeMirror-gutters { background: #4e4e4e; border-right: 0px; } +.cm-s-mbo .CodeMirror-guttermarker { color: white; } +.cm-s-mbo .CodeMirror-guttermarker-subtle { color: grey; } +.cm-s-mbo .CodeMirror-linenumber { color: #dadada; } +.cm-s-mbo .CodeMirror-cursor { border-left: 1px solid #ffffec; } + +.cm-s-mbo span.cm-comment { color: #95958a; } +.cm-s-mbo span.cm-atom { color: #00a8c6; } +.cm-s-mbo span.cm-number { color: #00a8c6; } + +.cm-s-mbo span.cm-property, .cm-s-mbo span.cm-attribute { color: #9ddfe9; } +.cm-s-mbo span.cm-keyword { color: #ffb928; } +.cm-s-mbo span.cm-string { color: #ffcf6c; } +.cm-s-mbo span.cm-string.cm-property { color: #ffffec; } + +.cm-s-mbo span.cm-variable { color: #ffffec; } +.cm-s-mbo span.cm-variable-2 { color: #00a8c6; } +.cm-s-mbo span.cm-def { color: #ffffec; } +.cm-s-mbo span.cm-bracket { color: #fffffc; font-weight: bold; } +.cm-s-mbo span.cm-tag { color: #9ddfe9; } +.cm-s-mbo span.cm-link { color: #f54b07; } +.cm-s-mbo span.cm-error { border-bottom: #636363; color: #ffffec; } +.cm-s-mbo span.cm-qualifier { color: #ffffec; } + +.cm-s-mbo .CodeMirror-activeline-background { background: #494b41; } +.cm-s-mbo .CodeMirror-matchingbracket { color: #ffb928 !important; } +.cm-s-mbo .CodeMirror-matchingtag { background: rgba(255, 255, 255, .37); } diff --git a/modules/template-engine/components/html/editor/editor.css b/modules/template-engine/components/html/editor/editor.css @@ -1,31 +1,32 @@ .editor__text-editor { - width: 100%; - height: 300px; + width: 100%; + height: 300px; } /* ACE-Editor */ textarea.editor__code-editor { - display: none; - /* Textarea nicht anzeigen, da durch Editor im DIV ersetzt */ + display: none; + /* Textarea nicht anzeigen, da durch Editor im DIV ersetzt */ } div.editor__code-editor { - position: absolute; - height: 500px; - width: 100%; - font-size: 14px; - z-index: 256; + position: absolute; + height: 500px; + width: 100%; + font-size: 14px; + z-index: 256; } textarea.editor__text-editor, textarea.editor__wiki-editor, textarea.editor__html-editor { - width: 100%; + width: 100%; } a.editorlink:active, a.editorlink:hover { - font-weight: normal; - text-decoration: none; + font-weight: normal; + text-decoration: none; } a.editorlink:link, a.editorlink:visited { - font-weight: normal; - text-decoration: none; + font-weight: normal; + text-decoration: none; } +/*# sourceMappingURL=data:application/json,%7B%22version%22%3A3%2C%22sources%22%3A%5B%22editor.less%22%5D%2C%22names%22%3A%5B%5D%2C%22mappings%22%3A%22AACA%3BCACC%3BCACA%3B%3B%3BAAID%2CQAAQ%3BCACP%3B%3B%3BAAID%2CGAAG%3BCAED%3BCACE%3BCACA%3BCACA%3BCACA%3B%3BAAKJ%2CQAAQ%3BAACR%2CQAAQ%3BAACR%2CQAAQ%3BCAEP%3B%3BAAID%2CCAAC%2CWAAW%3BAACZ%2CCAAC%2CWAAW%3BCAEX%3BCACA%3B%3BAAGD%2CCAAC%2CWAAW%3BAACZ%2CCAAC%2CWAAW%3BCAEX%3BCACA%22%7D */+ \ No newline at end of file diff --git a/modules/template-engine/components/html/link/link.min.js b/modules/template-engine/components/html/link/link.min.js @@ -1 +1 @@ -;$(document).on('orViewLoaded',function(e,n){$(e.target).closest('div.panel').find('.clickable').orLinkify()});$(document).on('orHeaderLoaded',function(e,n){$('div#header .clickable').orLinkify()});function submitLink(e,n){var i=jQuery.parseJSON(n),o='./api/';i.output='json';$.ajax({'type':'POST',url:o,data:i,success:function(n,i,o){$('div.panel div.status div.loader').html('&nbsp;');doResponse(n,i,e)}})};- \ No newline at end of file +;$(document).on('orViewLoaded',function(e,n){$(e.target).closest('div.panel').find('.clickable').orLinkify()});$(document).on('orHeaderLoaded',function(e,n){$('#header .clickable').orLinkify()});function submitLink(e,n){var o=jQuery.parseJSON(n),i='./api/';o.output='json';$.ajax({'type':'POST',url:i,data:o,success:function(n,o,i){$('div.panel div.status div.loader').html('&nbsp;');doResponse(n,o,e)}})};+ \ No newline at end of file