Head and Footer Scripts Inserter - Version 3.0

Version Description

  • Plugin renamed to "Head and Footer Scripts Inserter".
  • Styles of settings page optimized for mobile devices.
  • Added the syntax highlighting (by CodeMirror).
  • Added line numbering.
  • Added active-line add-on to CodeMirror.
  • Removed the default message about successful saving.
  • Added the custom message about successful saving.
  • Added function of automatic remove the "successful" message after 3 seconds.
  • Added function of automatic add the missing lines to get 10 lines.
  • The _output function optimized.
  • The "images" catalog renamed to "img".
  • The CodeMirror library moved to "lib" catalog.
  • The style.css file renamed to admin.css and moved to "css" catalog.
  • The main.js moved to "js" catalog.
  • The settings_page.php file moved to "php" catalog.
Download this release

Release Info

Developer Arthur Gareginyan
Plugin Icon 128x128 Head and Footer Scripts Inserter
Version 3.0
Comparing to
See all releases

Code changes from version 2.0 to 3.0

header-and-footer-scripts-inserter.php CHANGED
@@ -1,31 +1,31 @@
1
  <?php
2
  /**
3
- * Plugin Name: Header and Footer Scripts Inserter
4
  * Plugin URI: https://github.com/ArthurGareginyan/header-and-footer-scripts-inserter
5
- * Description: Easily add your scripts to the WordPress website's head or/and footer section. This is a must have tool for authors and website's owners.
6
  * Author: Arthur Gareginyan
7
  * Author URI: http://www.arthurgareginyan.com
8
- * Version: 2.0
9
  * License: GPL3
10
  * Text Domain: header-and-footer-scripts-inserter
11
  * Domain Path: /languages/
12
  *
13
  * Copyright 2016 Arthur Gareginyan (email : arthurgareginyan@gmail.com)
14
  *
15
- * This file is part of "Header and Footer Scripts Inserter".
16
  *
17
- * "Header and Footer Scripts Inserter" is free software: you can redistribute it and/or modify
18
  * it under the terms of the GNU General Public License as published by
19
  * the Free Software Foundation, either version 3 of the License, or
20
  * (at your option) any later version.
21
  *
22
- * "Header and Footer Scripts Inserter" is distributed in the hope that it will be useful,
23
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
24
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25
  * GNU General Public License for more details.
26
  *
27
  * You should have received a copy of the GNU General Public License
28
- * along with "Header and Footer Scripts Inserter". If not, see <http://www.gnu.org/licenses/>.
29
  *
30
  */
31
 
@@ -37,7 +37,7 @@
37
  defined('ABSPATH') or die("Restricted access!");
38
 
39
  /**
40
- * Plugin constants
41
  *
42
  * @since 2.0
43
  */
@@ -57,10 +57,10 @@ function HFScriptsIns_textdomain() {
57
  add_action( 'init', 'HFScriptsIns_textdomain' );
58
 
59
  /**
60
- * Print direct link to Header and Footer Scripts Inserter admin page
61
  *
62
  * Fetches array of links generated by WP Plugin admin page ( Deactivate | Edit )
63
- * and inserts a link to the Header and Footer Scripts Inserter admin page
64
  *
65
  * @since 2.0
66
  * @param array $links Array of links generated by WP in Plugin Admin page.
@@ -74,12 +74,12 @@ function HFScriptsIns_settings_link( $links ) {
74
  add_filter( "plugin_action_links_".HFSINS_BASE, 'HFScriptsIns_settings_link' );
75
 
76
  /**
77
- * Register "Header and Footer Scripts Inserter" submenu in "Settings" Admin Menu
78
  *
79
  * @since 2.0
80
  */
81
  function HFScriptsIns_register_submenu_page() {
82
- add_options_page( __( 'Header and Footer Scripts Inserter', 'header-and-footer-scripts-inserter' ), __( 'Header and Footer Scripts Inserter', 'header-and-footer-scripts-inserter' ), 'manage_options', basename( __FILE__ ), 'HFScriptsIns_render_submenu_page' );
83
  }
84
  add_action( 'admin_menu', 'HFScriptsIns_register_submenu_page' );
85
 
@@ -88,23 +88,36 @@ add_action( 'admin_menu', 'HFScriptsIns_register_submenu_page' );
88
  *
89
  * @since 2.0
90
  */
91
- require_once( HFSINS_PATH . 'inc/settings_page.php' );
92
 
93
  /**
94
- * Enqueue style sheet for setting's page
95
  *
96
- * @since 2.0
97
  */
98
- function HFScriptsIns_enqueue_scripts($hook) {
99
 
100
  // Return if the page is not a settings page of this plugin
101
  if ( 'settings_page_header-and-footer-scripts-inserter' != $hook ) {
102
  return;
103
  }
104
 
105
- wp_enqueue_style('styles', HFSINS_URL . 'inc/style.css');
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  }
107
- add_action('admin_enqueue_scripts', 'HFScriptsIns_enqueue_scripts');
108
 
109
  /**
110
  * Register settings
@@ -117,7 +130,7 @@ function HFScriptsIns_register_settings() {
117
  add_action( 'admin_init', 'HFScriptsIns_register_settings' );
118
 
119
  /**
120
- * Inject scripts in the frontend header and footer
121
  *
122
  * @since 1.0
123
  */
@@ -142,7 +155,7 @@ function HFScriptsIns_inject_footer_end() { HFScriptsIns_output('footer_end'); }
142
  * @param string $option Option Name
143
  * @return output
144
  *
145
- * @since 1.0
146
  */
147
  function HFScriptsIns_output($option) {
148
 
@@ -160,11 +173,13 @@ function HFScriptsIns_output($option) {
160
  return;
161
  }
162
 
163
- // Add comments and Output
164
- echo "\n<!-- [BEGIN] Scripts added via Header-and-Footer-Scripts-Inserter plugin by Arthur Gareginyan. -->\n";
165
- echo $data;
166
- echo "\n<!-- [END] Scripts added via Header-and-Footer-Scripts-Inserter plugin by Arthur Gareginyan. -->\n\n";
167
 
 
 
168
  }
169
 
170
  /**
1
  <?php
2
  /**
3
+ * Plugin Name: Head and Footer Scripts Inserter
4
  * Plugin URI: https://github.com/ArthurGareginyan/header-and-footer-scripts-inserter
5
+ * Description: Easily add your scripts to the WordPress website's head and footer sections. This is a must have tool for authors and website's owners.
6
  * Author: Arthur Gareginyan
7
  * Author URI: http://www.arthurgareginyan.com
8
+ * Version: 3.0
9
  * License: GPL3
10
  * Text Domain: header-and-footer-scripts-inserter
11
  * Domain Path: /languages/
12
  *
13
  * Copyright 2016 Arthur Gareginyan (email : arthurgareginyan@gmail.com)
14
  *
15
+ * This file is part of "Head and Footer Scripts Inserter".
16
  *
17
+ * "Head and Footer Scripts Inserter" is free software: you can redistribute it and/or modify
18
  * it under the terms of the GNU General Public License as published by
19
  * the Free Software Foundation, either version 3 of the License, or
20
  * (at your option) any later version.
21
  *
22
+ * "Head and Footer Scripts Inserter" is distributed in the hope that it will be useful,
23
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
24
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25
  * GNU General Public License for more details.
26
  *
27
  * You should have received a copy of the GNU General Public License
28
+ * along with "Head and Footer Scripts Inserter". If not, see <http://www.gnu.org/licenses/>.
29
  *
30
  */
31
 
37
  defined('ABSPATH') or die("Restricted access!");
38
 
39
  /**
40
+ * Define constants
41
  *
42
  * @since 2.0
43
  */
57
  add_action( 'init', 'HFScriptsIns_textdomain' );
58
 
59
  /**
60
+ * Print direct link to "Head and Footer Scripts Inserter" admin page
61
  *
62
  * Fetches array of links generated by WP Plugin admin page ( Deactivate | Edit )
63
+ * and inserts a link to the "Head and Footer Scripts Inserter" admin page
64
  *
65
  * @since 2.0
66
  * @param array $links Array of links generated by WP in Plugin Admin page.
74
  add_filter( "plugin_action_links_".HFSINS_BASE, 'HFScriptsIns_settings_link' );
75
 
76
  /**
77
+ * Register "Head and Footer Scripts Inserter" submenu in "Settings" Admin Menu
78
  *
79
  * @since 2.0
80
  */
81
  function HFScriptsIns_register_submenu_page() {
82
+ add_options_page( __( 'Head and Footer Scripts Inserter', 'header-and-footer-scripts-inserter' ), __( 'Head and Footer Scripts Inserter', 'header-and-footer-scripts-inserter' ), 'manage_options', basename( __FILE__ ), 'HFScriptsIns_render_submenu_page' );
83
  }
84
  add_action( 'admin_menu', 'HFScriptsIns_register_submenu_page' );
85
 
88
  *
89
  * @since 2.0
90
  */
91
+ require_once( HFSINS_PATH . 'inc/php/settings_page.php' );
92
 
93
  /**
94
+ * Load scripts and style sheet for settings page
95
  *
96
+ * @since 3.0
97
  */
98
+ function HFScriptsIns_load_scripts($hook) {
99
 
100
  // Return if the page is not a settings page of this plugin
101
  if ( 'settings_page_header-and-footer-scripts-inserter' != $hook ) {
102
  return;
103
  }
104
 
105
+ // CodeMirror
106
+ wp_enqueue_style('codemirror_style', HFSINS_URL . 'inc/lib/codemirror/codemirror.css');
107
+ wp_enqueue_script('codemirror', HFSINS_URL . 'inc/lib/codemirror/codemirror.js');
108
+ wp_enqueue_script('codemirror-htmlmixed', HFSINS_URL . 'inc/lib/codemirror/mode/htmlmixed.js');
109
+ wp_enqueue_script('codemirror-javascript', HFSINS_URL . 'inc/lib/codemirror/mode/javascript.js');
110
+ wp_enqueue_script('codemirror-xml', HFSINS_URL . 'inc/lib/codemirror/mode/xml.js');
111
+ wp_enqueue_script('codemirror-css', HFSINS_URL . 'inc/lib/codemirror/mode/css.js');
112
+ wp_enqueue_script('codemirror-active-line', HFSINS_URL . 'inc/lib/codemirror/addons/active-line.js');
113
+
114
+ // JS functions
115
+ wp_enqueue_script('js-functions', HFSINS_URL . 'inc/js/main.js', array(), false, true);
116
+
117
+ // Style sheet
118
+ wp_enqueue_style('styles', HFSINS_URL . 'inc/css/admin.css');
119
  }
120
+ add_action('admin_enqueue_scripts', 'HFScriptsIns_load_scripts');
121
 
122
  /**
123
  * Register settings
130
  add_action( 'admin_init', 'HFScriptsIns_register_settings' );
131
 
132
  /**
133
+ * Inject scripts in the frontend head and footer
134
  *
135
  * @since 1.0
136
  */
155
  * @param string $option Option Name
156
  * @return output
157
  *
158
+ * @since 3.0
159
  */
160
  function HFScriptsIns_output($option) {
161
 
173
  return;
174
  }
175
 
176
+ // Add comments to output
177
+ $data_out = "\n<!-- [BEGIN] Scripts added via Head-and-Footer-Scripts-Inserter plugin by Arthur Gareginyan. -->\n";
178
+ $data_out .= $data;
179
+ $data_out .= "\n<!-- [END] Scripts added via Head-and-Footer-Scripts-Inserter plugin by Arthur Gareginyan. -->\n\n";
180
 
181
+ // Output
182
+ echo $data_out;
183
  }
184
 
185
  /**
inc/{style.css → css/admin.css} RENAMED
@@ -1,7 +1,7 @@
1
  /*
2
  * Header and Footer Scripts Inserter
3
  * Style sheet for plugin's page
4
- * @since 2.0
5
  * @agareginyan
6
  */
7
 
@@ -38,9 +38,19 @@ h3.title {
38
  border-bottom: 1px solid #eee;
39
  }
40
 
41
- #Header h3,
42
- #Footer h3 {
43
- font-size: 120%;
 
 
 
 
 
 
 
 
 
 
44
  }
45
 
46
  textarea {
@@ -58,8 +68,9 @@ p.help-text {
58
  color: #797979;
59
  line-height: 15px;
60
  padding-top: 0px !important;
 
61
  margin-top: 0px !important;
62
- margin-bottom: 15px !important;
63
  }
64
 
65
  .postbox a {
@@ -81,6 +92,9 @@ p.help-text {
81
  #help {
82
  text-align: center;
83
  }
 
 
 
84
 
85
  #donate {
86
  text-align: center;
@@ -88,4 +102,15 @@ p.help-text {
88
 
89
  #freelance {
90
  text-align: center;
 
 
 
 
 
 
 
 
 
 
 
91
  }
1
  /*
2
  * Header and Footer Scripts Inserter
3
  * Style sheet for plugin's page
4
+ * @since 3.0
5
  * @agareginyan
6
  */
7
 
38
  border-bottom: 1px solid #eee;
39
  }
40
 
41
+ /* Messages
42
+ -------------------------------------------------------------- */
43
+ #setting-error-settings_updated {
44
+ display: none;
45
+ }
46
+
47
+ /* CodeMirror Editor
48
+ -------------------------------------------------------------- */
49
+ .CodeMirror {
50
+ height: 100% !important;
51
+ border: 1px solid #ddd;
52
+ margin-left: 5px;
53
+ margin-right: 5px;
54
  }
55
 
56
  textarea {
68
  color: #797979;
69
  line-height: 15px;
70
  padding-top: 0px !important;
71
+ padding-left: 5px;
72
  margin-top: 0px !important;
73
+ margin-bottom: 25px !important;
74
  }
75
 
76
  .postbox a {
92
  #help {
93
  text-align: center;
94
  }
95
+ #help p {
96
+ margin: 0;
97
+ }
98
 
99
  #donate {
100
  text-align: center;
102
 
103
  #freelance {
104
  text-align: center;
105
+ }
106
+
107
+ /* Responsive
108
+ -------------------------------------------------------------- */
109
+ @media (max-width: 860px) {
110
+ .inner-sidebar {
111
+ display: none !important;
112
+ }
113
+ #post-body-content {
114
+ margin-right: 0 !important;
115
+ }
116
  }
inc/images/thanks.png DELETED
Binary file
inc/{images → img}/author.png RENAMED
File without changes
inc/{images → img}/btn_donateCC_LG.gif RENAMED
File without changes
inc/img/thanks.png ADDED
Binary file
inc/js/main.js ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Head and Footer Scripts Inserter
3
+ * JS functions
4
+ * @since 3.0
5
+ * @agareginyan
6
+ */
7
+
8
+
9
+ (function(){
10
+ "use strict";
11
+
12
+ jQuery(document).ready(function($) {
13
+
14
+ // Find all textareas on page
15
+ $('textarea').each(function(index, elements) {
16
+
17
+ // Change textarea to CodeMirror editor
18
+ var editor = CodeMirror.fromTextArea( elements , {
19
+ lineNumbers: true,
20
+ firstLineNumber: 1,
21
+ matchBrackets: true,
22
+ indentUnit: 4,
23
+ mode: 'text/html',
24
+ styleActiveLine: true
25
+ });
26
+
27
+ // Refresh CodeMirror editor after 1 second
28
+ setTimeout(function() {
29
+ editor.refresh();
30
+ },1);
31
+ });
32
+
33
+ // Remove the "successful" message after 3 seconds
34
+ if (".updated") {
35
+ setTimeout(function() {
36
+ $(".updated").fadeOut();
37
+ }, 3000);
38
+ }
39
+ });
40
+
41
+ }());
inc/lib/codemirror/LICENSE ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (C) 2016 by Marijn Haverbeke <marijnh@gmail.com> and others
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in
11
+ all copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
+ THE SOFTWARE.
inc/lib/codemirror/README.md ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CodeMirror
2
+ [![Build Status](https://travis-ci.org/codemirror/CodeMirror.svg)](https://travis-ci.org/codemirror/CodeMirror)
3
+ [![NPM version](https://img.shields.io/npm/v/codemirror.svg)](https://www.npmjs.org/package/codemirror)
4
+ [![Join the chat at https://gitter.im/codemirror/CodeMirror](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/codemirror/CodeMirror)
5
+ [Funding status: ![maintainer happiness](https://marijnhaverbeke.nl/fund/status_s.png?again)](https://marijnhaverbeke.nl/fund/)
6
+
7
+ CodeMirror is a versatile text editor implemented in JavaScript for
8
+ the browser. It is specialized for editing code, and comes with over
9
+ 100 language modes and various addons that implement more advanced
10
+ editing functionality.
11
+
12
+ A rich programming API and a CSS theming system are available for
13
+ customizing CodeMirror to fit your application, and extending it with
14
+ new functionality.
15
+
16
+ You can find more information (and the
17
+ [manual](http://codemirror.net/doc/manual.html)) on the [project
18
+ page](http://codemirror.net). For questions and discussion, use the
19
+ [discussion forum](https://discuss.codemirror.net/).
20
+
21
+ See
22
+ [CONTRIBUTING.md](https://github.com/codemirror/CodeMirror/blob/master/CONTRIBUTING.md)
23
+ for contributing guidelines.
24
+
25
+ The CodeMirror community aims to be welcoming to everybody. We use the
26
+ [Contributor Covenant
27
+ (1.1)](http://contributor-covenant.org/version/1/1/0/) as our code of
28
+ conduct.
inc/lib/codemirror/addons/active-line.js ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // CodeMirror, copyright (c) by Marijn Haverbeke and others
2
+ // Distributed under an MIT license: http://codemirror.net/LICENSE
3
+
4
+ // Because sometimes you need to style the cursor's line.
5
+ //
6
+ // Adds an option 'styleActiveLine' which, when enabled, gives the
7
+ // active line's wrapping <div> the CSS class "CodeMirror-activeline",
8
+ // and gives its background <div> the class "CodeMirror-activeline-background".
9
+
10
+ (function(mod) {
11
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
12
+ mod(require("../../lib/codemirror"));
13
+ else if (typeof define == "function" && define.amd) // AMD
14
+ define(["../../lib/codemirror"], mod);
15
+ else // Plain browser env
16
+ mod(CodeMirror);
17
+ })(function(CodeMirror) {
18
+ "use strict";
19
+ var WRAP_CLASS = "CodeMirror-activeline";
20
+ var BACK_CLASS = "CodeMirror-activeline-background";
21
+ var GUTT_CLASS = "CodeMirror-activeline-gutter";
22
+
23
+ CodeMirror.defineOption("styleActiveLine", false, function(cm, val, old) {
24
+ var prev = old && old != CodeMirror.Init;
25
+ if (val && !prev) {
26
+ cm.state.activeLines = [];
27
+ updateActiveLines(cm, cm.listSelections());
28
+ cm.on("beforeSelectionChange", selectionChange);
29
+ } else if (!val && prev) {
30
+ cm.off("beforeSelectionChange", selectionChange);
31
+ clearActiveLines(cm);
32
+ delete cm.state.activeLines;
33
+ }
34
+ });
35
+
36
+ function clearActiveLines(cm) {
37
+ for (var i = 0; i < cm.state.activeLines.length; i++) {
38
+ cm.removeLineClass(cm.state.activeLines[i], "wrap", WRAP_CLASS);
39
+ cm.removeLineClass(cm.state.activeLines[i], "background", BACK_CLASS);
40
+ cm.removeLineClass(cm.state.activeLines[i], "gutter", GUTT_CLASS);
41
+ }
42
+ }
43
+
44
+ function sameArray(a, b) {
45
+ if (a.length != b.length) return false;
46
+ for (var i = 0; i < a.length; i++)
47
+ if (a[i] != b[i]) return false;
48
+ return true;
49
+ }
50
+
51
+ function updateActiveLines(cm, ranges) {
52
+ var active = [];
53
+ for (var i = 0; i < ranges.length; i++) {
54
+ var range = ranges[i];
55
+ if (!range.empty()) continue;
56
+ var line = cm.getLineHandleVisualStart(range.head.line);
57
+ if (active[active.length - 1] != line) active.push(line);
58
+ }
59
+ if (sameArray(cm.state.activeLines, active)) return;
60
+ cm.operation(function() {
61
+ clearActiveLines(cm);
62
+ for (var i = 0; i < active.length; i++) {
63
+ cm.addLineClass(active[i], "wrap", WRAP_CLASS);
64
+ cm.addLineClass(active[i], "background", BACK_CLASS);
65
+ cm.addLineClass(active[i], "gutter", GUTT_CLASS);
66
+ }
67
+ cm.state.activeLines = active;
68
+ });
69
+ }
70
+
71
+ function selectionChange(cm, sel) {
72
+ updateActiveLines(cm, sel.ranges);
73
+ }
74
+ });
inc/lib/codemirror/codemirror.css ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* BASICS */
2
+
3
+ .CodeMirror {
4
+ /* Set height, width, borders, and global font properties here */
5
+ font-family: monospace;
6
+ height: 300px;
7
+ color: black;
8
+ }
9
+
10
+ /* PADDING */
11
+
12
+ .CodeMirror-lines {
13
+ padding: 4px 0; /* Vertical padding around content */
14
+ }
15
+ .CodeMirror pre {
16
+ padding: 0 4px; /* Horizontal padding of content */
17
+ }
18
+
19
+ .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
20
+ background-color: white; /* The little square between H and V scrollbars */
21
+ }
22
+
23
+ /* GUTTER */
24
+
25
+ .CodeMirror-gutters {
26
+ border-right: 1px solid #ddd;
27
+ background-color: #f7f7f7;
28
+ white-space: nowrap;
29
+ }
30
+ .CodeMirror-linenumbers {}
31
+ .CodeMirror-linenumber {
32
+ padding: 0 3px 0 5px;
33
+ min-width: 20px;
34
+ text-align: right;
35
+ color: #999;
36
+ white-space: nowrap;
37
+ }
38
+
39
+ .CodeMirror-guttermarker { color: black; }
40
+ .CodeMirror-guttermarker-subtle { color: #999; }
41
+
42
+ /* CURSOR */
43
+
44
+ .CodeMirror-cursor {
45
+ border-left: 1px solid black;
46
+ border-right: none;
47
+ width: 0;
48
+ }
49
+ /* Shown when moving in bi-directional text */
50
+ .CodeMirror div.CodeMirror-secondarycursor {
51
+ border-left: 1px solid silver;
52
+ }
53
+ .cm-fat-cursor .CodeMirror-cursor {
54
+ width: auto;
55
+ border: 0 !important;
56
+ background: #7e7;
57
+ }
58
+ .cm-fat-cursor div.CodeMirror-cursors {
59
+ z-index: 1;
60
+ }
61
+
62
+ .cm-animate-fat-cursor {
63
+ width: auto;
64
+ border: 0;
65
+ -webkit-animation: blink 1.06s steps(1) infinite;
66
+ -moz-animation: blink 1.06s steps(1) infinite;
67
+ animation: blink 1.06s steps(1) infinite;
68
+ background-color: #7e7;
69
+ }
70
+ @-moz-keyframes blink {
71
+ 0% {}
72
+ 50% { background-color: transparent; }
73
+ 100% {}
74
+ }
75
+ @-webkit-keyframes blink {
76
+ 0% {}
77
+ 50% { background-color: transparent; }
78
+ 100% {}
79
+ }
80
+ @keyframes blink {
81
+ 0% {}
82
+ 50% { background-color: transparent; }
83
+ 100% {}
84
+ }
85
+
86
+ /* Can style cursor different in overwrite (non-insert) mode */
87
+ .CodeMirror-overwrite .CodeMirror-cursor {}
88
+
89
+ .cm-tab { display: inline-block; text-decoration: inherit; }
90
+
91
+ .CodeMirror-rulers {
92
+ position: absolute;
93
+ left: 0; right: 0; top: -50px; bottom: -20px;
94
+ overflow: hidden;
95
+ }
96
+ .CodeMirror-ruler {
97
+ border-left: 1px solid #ccc;
98
+ top: 0; bottom: 0;
99
+ position: absolute;
100
+ }
101
+
102
+ /* DEFAULT THEME */
103
+
104
+ .cm-s-default .cm-header {color: blue;}
105
+ .cm-s-default .cm-quote {color: #090;}
106
+ .cm-negative {color: #d44;}
107
+ .cm-positive {color: #292;}
108
+ .cm-header, .cm-strong {font-weight: bold;}
109
+ .cm-em {font-style: italic;}
110
+ .cm-link {text-decoration: underline;}
111
+ .cm-strikethrough {text-decoration: line-through;}
112
+
113
+ .cm-s-default .cm-keyword {color: #708;}
114
+ .cm-s-default .cm-atom {color: #219;}
115
+ .cm-s-default .cm-number {color: #164;}
116
+ .cm-s-default .cm-def {color: #00f;}
117
+ .cm-s-default .cm-variable,
118
+ .cm-s-default .cm-punctuation,
119
+ .cm-s-default .cm-property,
120
+ .cm-s-default .cm-operator {}
121
+ .cm-s-default .cm-variable-2 {color: #05a;}
122
+ .cm-s-default .cm-variable-3 {color: #085;}
123
+ .cm-s-default .cm-comment {color: #a50;}
124
+ .cm-s-default .cm-string {color: #a11;}
125
+ .cm-s-default .cm-string-2 {color: #f50;}
126
+ .cm-s-default .cm-meta {color: #555;}
127
+ .cm-s-default .cm-qualifier {color: #555;}
128
+ .cm-s-default .cm-builtin {color: #30a;}
129
+ .cm-s-default .cm-bracket {color: #997;}
130
+ .cm-s-default .cm-tag {color: #170;}
131
+ .cm-s-default .cm-attribute {color: #00c;}
132
+ .cm-s-default .cm-hr {color: #999;}
133
+ .cm-s-default .cm-link {color: #00c;}
134
+
135
+ .cm-s-default .cm-error {color: #f00;}
136
+ .cm-invalidchar {color: #f00;}
137
+
138
+ .CodeMirror-composing { border-bottom: 2px solid; }
139
+
140
+ /* Default styles for common addons */
141
+
142
+ div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;}
143
+ div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;}
144
+ .CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); }
145
+ .CodeMirror-activeline-background {background: #e8f2ff;}
146
+
147
+ /* STOP */
148
+
149
+ /* The rest of this file contains styles related to the mechanics of
150
+ the editor. You probably shouldn't touch them. */
151
+
152
+ .CodeMirror {
153
+ position: relative;
154
+ overflow: hidden;
155
+ background: white;
156
+ }
157
+
158
+ .CodeMirror-scroll {
159
+ overflow: scroll !important; /* Things will break if this is overridden */
160
+ /* 30px is the magic margin used to hide the element's real scrollbars */
161
+ /* See overflow: hidden in .CodeMirror */
162
+ margin-bottom: -30px; margin-right: -30px;
163
+ padding-bottom: 30px;
164
+ height: 100%;
165
+ outline: none; /* Prevent dragging from highlighting the element */
166
+ position: relative;
167
+ }
168
+ .CodeMirror-sizer {
169
+ position: relative;
170
+ border-right: 30px solid transparent;
171
+ }
172
+
173
+ /* The fake, visible scrollbars. Used to force redraw during scrolling
174
+ before actual scrolling happens, thus preventing shaking and
175
+ flickering artifacts. */
176
+ .CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
177
+ position: absolute;
178
+ z-index: 6;
179
+ display: none;
180
+ }
181
+ .CodeMirror-vscrollbar {
182
+ right: 0; top: 0;
183
+ overflow-x: hidden;
184
+ overflow-y: scroll;
185
+ }
186
+ .CodeMirror-hscrollbar {
187
+ bottom: 0; left: 0;
188
+ overflow-y: hidden;
189
+ overflow-x: scroll;
190
+ }
191
+ .CodeMirror-scrollbar-filler {
192
+ right: 0; bottom: 0;
193
+ }
194
+ .CodeMirror-gutter-filler {
195
+ left: 0; bottom: 0;
196
+ }
197
+
198
+ .CodeMirror-gutters {
199
+ position: absolute; left: 0; top: 0;
200
+ min-height: 100%;
201
+ z-index: 3;
202
+ }
203
+ .CodeMirror-gutter {
204
+ white-space: normal;
205
+ height: 100%;
206
+ display: inline-block;
207
+ vertical-align: top;
208
+ margin-bottom: -30px;
209
+ /* Hack to make IE7 behave */
210
+ *zoom:1;
211
+ *display:inline;
212
+ }
213
+ .CodeMirror-gutter-wrapper {
214
+ position: absolute;
215
+ z-index: 4;
216
+ background: none !important;
217
+ border: none !important;
218
+ }
219
+ .CodeMirror-gutter-background {
220
+ position: absolute;
221
+ top: 0; bottom: 0;
222
+ z-index: 4;
223
+ }
224
+ .CodeMirror-gutter-elt {
225
+ position: absolute;
226
+ cursor: default;
227
+ z-index: 4;
228
+ }
229
+ .CodeMirror-gutter-wrapper {
230
+ -webkit-user-select: none;
231
+ -moz-user-select: none;
232
+ user-select: none;
233
+ }
234
+
235
+ .CodeMirror-lines {
236
+ cursor: text;
237
+ min-height: 1px; /* prevents collapsing before first draw */
238
+ }
239
+ .CodeMirror pre {
240
+ /* Reset some styles that the rest of the page might have set */
241
+ -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;
242
+ border-width: 0;
243
+ background: transparent;
244
+ font-family: inherit;
245
+ font-size: inherit;
246
+ margin: 0;
247
+ white-space: pre;
248
+ word-wrap: normal;
249
+ line-height: inherit;
250
+ color: inherit;
251
+ z-index: 2;
252
+ position: relative;
253
+ overflow: visible;
254
+ -webkit-tap-highlight-color: transparent;
255
+ -webkit-font-variant-ligatures: none;
256
+ font-variant-ligatures: none;
257
+ }
258
+ .CodeMirror-wrap pre {
259
+ word-wrap: break-word;
260
+ white-space: pre-wrap;
261
+ word-break: normal;
262
+ }
263
+
264
+ .CodeMirror-linebackground {
265
+ position: absolute;
266
+ left: 0; right: 0; top: 0; bottom: 0;
267
+ z-index: 0;
268
+ }
269
+
270
+ .CodeMirror-linewidget {
271
+ position: relative;
272
+ z-index: 2;
273
+ overflow: auto;
274
+ }
275
+
276
+ .CodeMirror-widget {}
277
+
278
+ .CodeMirror-code {
279
+ outline: none;
280
+ }
281
+
282
+ /* Force content-box sizing for the elements where we expect it */
283
+ .CodeMirror-scroll,
284
+ .CodeMirror-sizer,
285
+ .CodeMirror-gutter,
286
+ .CodeMirror-gutters,
287
+ .CodeMirror-linenumber {
288
+ -moz-box-sizing: content-box;
289
+ box-sizing: content-box;
290
+ }
291
+
292
+ .CodeMirror-measure {
293
+ position: absolute;
294
+ width: 100%;
295
+ height: 0;
296
+ overflow: hidden;
297
+ visibility: hidden;
298
+ }
299
+
300
+ .CodeMirror-cursor {
301
+ position: absolute;
302
+ pointer-events: none;
303
+ }
304
+ .CodeMirror-measure pre { position: static; }
305
+
306
+ div.CodeMirror-cursors {
307
+ visibility: hidden;
308
+ position: relative;
309
+ z-index: 3;
310
+ }
311
+ div.CodeMirror-dragcursors {
312
+ visibility: visible;
313
+ }
314
+
315
+ .CodeMirror-focused div.CodeMirror-cursors {
316
+ visibility: visible;
317
+ }
318
+
319
+ .CodeMirror-selected { background: #d9d9d9; }
320
+ .CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }
321
+ .CodeMirror-crosshair { cursor: crosshair; }
322
+ .CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; }
323
+ .CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; }
324
+
325
+ .cm-searching {
326
+ background: #ffa;
327
+ background: rgba(255, 255, 0, .4);
328
+ }
329
+
330
+ /* IE7 hack to prevent it from returning funny offsetTops on the spans */
331
+ .CodeMirror span { *vertical-align: text-bottom; }
332
+
333
+ /* Used to force a border model for a node */
334
+ .cm-force-border { padding-right: .1px; }
335
+
336
+ @media print {
337
+ /* Hide the cursor when printing */
338
+ .CodeMirror div.CodeMirror-cursors {
339
+ visibility: hidden;
340
+ }
341
+ }
342
+
343
+ /* See issue #2901 */
344
+ .cm-tab-wrap-hack:after { content: ''; }
345
+
346
+ /* Help users use markselection to safely style text background */
347
+ span.CodeMirror-selectedtext { background: none; }
inc/lib/codemirror/codemirror.js ADDED
@@ -0,0 +1,8935 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // CodeMirror, copyright (c) by Marijn Haverbeke and others
2
+ // Distributed under an MIT license: http://codemirror.net/LICENSE
3
+
4
+ // This is CodeMirror (http://codemirror.net), a code editor
5
+ // implemented in JavaScript on top of the browser's DOM.
6
+ //
7
+ // You can find some technical background for some of the code below
8
+ // at http://marijnhaverbeke.nl/blog/#cm-internals .
9
+
10
+ (function(mod) {
11
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
12
+ module.exports = mod();
13
+ else if (typeof define == "function" && define.amd) // AMD
14
+ return define([], mod);
15
+ else // Plain browser env
16
+ (this || window).CodeMirror = mod();
17
+ })(function() {
18
+ "use strict";
19
+
20
+ // BROWSER SNIFFING
21
+
22
+ // Kludges for bugs and behavior differences that can't be feature
23
+ // detected are enabled based on userAgent etc sniffing.
24
+ var userAgent = navigator.userAgent;
25
+ var platform = navigator.platform;
26
+
27
+ var gecko = /gecko\/\d/i.test(userAgent);
28
+ var ie_upto10 = /MSIE \d/.test(userAgent);
29
+ var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
30
+ var ie = ie_upto10 || ie_11up;
31
+ var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]);
32
+ var webkit = /WebKit\//.test(userAgent);
33
+ var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
34
+ var chrome = /Chrome\//.test(userAgent);
35
+ var presto = /Opera\//.test(userAgent);
36
+ var safari = /Apple Computer/.test(navigator.vendor);
37
+ var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
38
+ var phantom = /PhantomJS/.test(userAgent);
39
+
40
+ var ios = /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent);
41
+ // This is woefully incomplete. Suggestions for alternative methods welcome.
42
+ var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
43
+ var mac = ios || /Mac/.test(platform);
44
+ var chromeOS = /\bCrOS\b/.test(userAgent);
45
+ var windows = /win/i.test(platform);
46
+
47
+ var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/);
48
+ if (presto_version) presto_version = Number(presto_version[1]);
49
+ if (presto_version && presto_version >= 15) { presto = false; webkit = true; }
50
+ // Some browsers use the wrong event properties to signal cmd/ctrl on OS X
51
+ var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11));
52
+ var captureRightClick = gecko || (ie && ie_version >= 9);
53
+
54
+ // Optimize some code when these features are not used.
55
+ var sawReadOnlySpans = false, sawCollapsedSpans = false;
56
+
57
+ // EDITOR CONSTRUCTOR
58
+
59
+ // A CodeMirror instance represents an editor. This is the object
60
+ // that user code is usually dealing with.
61
+
62
+ function CodeMirror(place, options) {
63
+ if (!(this instanceof CodeMirror)) return new CodeMirror(place, options);
64
+
65
+ this.options = options = options ? copyObj(options) : {};
66
+ // Determine effective options based on given values and defaults.
67
+ copyObj(defaults, options, false);
68
+ setGuttersForLineNumbers(options);
69
+
70
+ var doc = options.value;
71
+ if (typeof doc == "string") doc = new Doc(doc, options.mode, null, options.lineSeparator);
72
+ this.doc = doc;
73
+
74
+ var input = new CodeMirror.inputStyles[options.inputStyle](this);
75
+ var display = this.display = new Display(place, doc, input);
76
+ display.wrapper.CodeMirror = this;
77
+ updateGutters(this);
78
+ themeChanged(this);
79
+ if (options.lineWrapping)
80
+ this.display.wrapper.className += " CodeMirror-wrap";
81
+ if (options.autofocus && !mobile) display.input.focus();
82
+ initScrollbars(this);
83
+
84
+ this.state = {
85
+ keyMaps: [], // stores maps added by addKeyMap
86
+ overlays: [], // highlighting overlays, as added by addOverlay
87
+ modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
88
+ overwrite: false,
89
+ delayingBlurEvent: false,
90
+ focused: false,
91
+ suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
92
+ pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
93
+ selectingText: false,
94
+ draggingText: false,
95
+ highlight: new Delayed(), // stores highlight worker timeout
96
+ keySeq: null, // Unfinished key sequence
97
+ specialChars: null
98
+ };
99
+
100
+ var cm = this;
101
+
102
+ // Override magic textarea content restore that IE sometimes does
103
+ // on our hidden textarea on reload
104
+ if (ie && ie_version < 11) setTimeout(function() { cm.display.input.reset(true); }, 20);
105
+
106
+ registerEventHandlers(this);
107
+ ensureGlobalHandlers();
108
+
109
+ startOperation(this);
110
+ this.curOp.forceUpdate = true;
111
+ attachDoc(this, doc);
112
+
113
+ if ((options.autofocus && !mobile) || cm.hasFocus())
114
+ setTimeout(bind(onFocus, this), 20);
115
+ else
116
+ onBlur(this);
117
+
118
+ for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt))
119
+ optionHandlers[opt](this, options[opt], Init);
120
+ maybeUpdateLineNumberWidth(this);
121
+ if (options.finishInit) options.finishInit(this);
122
+ for (var i = 0; i < initHooks.length; ++i) initHooks[i](this);
123
+ endOperation(this);
124
+ // Suppress optimizelegibility in Webkit, since it breaks text
125
+ // measuring on line wrapping boundaries.
126
+ if (webkit && options.lineWrapping &&
127
+ getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
128
+ display.lineDiv.style.textRendering = "auto";
129
+ }
130
+
131
+ // DISPLAY CONSTRUCTOR
132
+
133
+ // The display handles the DOM integration, both for input reading
134
+ // and content drawing. It holds references to DOM nodes and
135
+ // display-related state.
136
+
137
+ function Display(place, doc, input) {
138
+ var d = this;
139
+ this.input = input;
140
+
141
+ // Covers bottom-right square when both scrollbars are present.
142
+ d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
143
+ d.scrollbarFiller.setAttribute("cm-not-content", "true");
144
+ // Covers bottom of gutter when coverGutterNextToScrollbar is on
145
+ // and h scrollbar is present.
146
+ d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
147
+ d.gutterFiller.setAttribute("cm-not-content", "true");
148
+ // Will contain the actual code, positioned to cover the viewport.
149
+ d.lineDiv = elt("div", null, "CodeMirror-code");
150
+ // Elements are added to these to represent selection and cursors.
151
+ d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1");
152
+ d.cursorDiv = elt("div", null, "CodeMirror-cursors");
153
+ // A visibility: hidden element used to find the size of things.
154
+ d.measure = elt("div", null, "CodeMirror-measure");
155
+ // When lines outside of the viewport are measured, they are drawn in this.
156
+ d.lineMeasure = elt("div", null, "CodeMirror-measure");
157
+ // Wraps everything that needs to exist inside the vertically-padded coordinate system
158
+ d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
159
+ null, "position: relative; outline: none");
160
+ // Moved around its parent to cover visible view.
161
+ d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative");
162
+ // Set to the height of the document, allowing scrolling.
163
+ d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
164
+ d.sizerWidth = null;
165
+ // Behavior of elts with overflow: auto and padding is
166
+ // inconsistent across browsers. This is used to ensure the
167
+ // scrollable area is big enough.
168
+ d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;");
169
+ // Will contain the gutters, if any.
170
+ d.gutters = elt("div", null, "CodeMirror-gutters");
171
+ d.lineGutter = null;
172
+ // Actual scrollable element.
173
+ d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll");
174
+ d.scroller.setAttribute("tabIndex", "-1");
175
+ // The element in which the editor lives.
176
+ d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
177
+
178
+ // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
179
+ if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
180
+ if (!webkit && !(gecko && mobile)) d.scroller.draggable = true;
181
+
182
+ if (place) {
183
+ if (place.appendChild) place.appendChild(d.wrapper);
184
+ else place(d.wrapper);
185
+ }
186
+
187
+ // Current rendered range (may be bigger than the view window).
188
+ d.viewFrom = d.viewTo = doc.first;
189
+ d.reportedViewFrom = d.reportedViewTo = doc.first;
190
+ // Information about the rendered lines.
191
+ d.view = [];
192
+ d.renderedView = null;
193
+ // Holds info about a single rendered line when it was rendered
194
+ // for measurement, while not in view.
195
+ d.externalMeasured = null;
196
+ // Empty space (in pixels) above the view
197
+ d.viewOffset = 0;
198
+ d.lastWrapHeight = d.lastWrapWidth = 0;
199
+ d.updateLineNumbers = null;
200
+
201
+ d.nativeBarWidth = d.barHeight = d.barWidth = 0;
202
+ d.scrollbarsClipped = false;
203
+
204
+ // Used to only resize the line number gutter when necessary (when
205
+ // the amount of lines crosses a boundary that makes its width change)
206
+ d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null;
207
+ // Set to true when a non-horizontal-scrolling line widget is
208
+ // added. As an optimization, line widget aligning is skipped when
209
+ // this is false.
210
+ d.alignWidgets = false;
211
+
212
+ d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
213
+
214
+ // Tracks the maximum line length so that the horizontal scrollbar
215
+ // can be kept static when scrolling.
216
+ d.maxLine = null;
217
+ d.maxLineLength = 0;
218
+ d.maxLineChanged = false;
219
+
220
+ // Used for measuring wheel scrolling granularity
221
+ d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null;
222
+
223
+ // True when shift is held down.
224
+ d.shift = false;
225
+
226
+ // Used to track whether anything happened since the context menu
227
+ // was opened.
228
+ d.selForContextMenu = null;
229
+
230
+ d.activeTouch = null;
231
+
232
+ input.init(d);
233
+ }
234
+
235
+ // STATE UPDATES
236
+
237
+ // Used to get the editor into a consistent state again when options change.
238
+
239
+ function loadMode(cm) {
240
+ cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption);
241
+ resetModeState(cm);
242
+ }
243
+
244
+ function resetModeState(cm) {
245
+ cm.doc.iter(function(line) {
246
+ if (line.stateAfter) line.stateAfter = null;
247
+ if (line.styles) line.styles = null;
248
+ });
249
+ cm.doc.frontier = cm.doc.first;
250
+ startWorker(cm, 100);
251
+ cm.state.modeGen++;
252
+ if (cm.curOp) regChange(cm);
253
+ }
254
+
255
+ function wrappingChanged(cm) {
256
+ if (cm.options.lineWrapping) {
257
+ addClass(cm.display.wrapper, "CodeMirror-wrap");
258
+ cm.display.sizer.style.minWidth = "";
259
+ cm.display.sizerWidth = null;
260
+ } else {
261
+ rmClass(cm.display.wrapper, "CodeMirror-wrap");
262
+ findMaxLine(cm);
263
+ }
264
+ estimateLineHeights(cm);
265
+ regChange(cm);
266
+ clearCaches(cm);
267
+ setTimeout(function(){updateScrollbars(cm);}, 100);
268
+ }
269
+
270
+ // Returns a function that estimates the height of a line, to use as
271
+ // first approximation until the line becomes visible (and is thus
272
+ // properly measurable).
273
+ function estimateHeight(cm) {
274
+ var th = textHeight(cm.display), wrapping = cm.options.lineWrapping;
275
+ var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3);
276
+ return function(line) {
277
+ if (lineIsHidden(cm.doc, line)) return 0;
278
+
279
+ var widgetsHeight = 0;
280
+ if (line.widgets) for (var i = 0; i < line.widgets.length; i++) {
281
+ if (line.widgets[i].height) widgetsHeight += line.widgets[i].height;
282
+ }
283
+
284
+ if (wrapping)
285
+ return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;
286
+ else
287
+ return widgetsHeight + th;
288
+ };
289
+ }
290
+
291
+ function estimateLineHeights(cm) {
292
+ var doc = cm.doc, est = estimateHeight(cm);
293
+ doc.iter(function(line) {
294
+ var estHeight = est(line);
295
+ if (estHeight != line.height) updateLineHeight(line, estHeight);
296
+ });
297
+ }
298
+
299
+ function themeChanged(cm) {
300
+ cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") +
301
+ cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-");
302
+ clearCaches(cm);
303
+ }
304
+
305
+ function guttersChanged(cm) {
306
+ updateGutters(cm);
307
+ regChange(cm);
308
+ setTimeout(function(){alignHorizontally(cm);}, 20);
309
+ }
310
+
311
+ // Rebuild the gutter elements, ensure the margin to the left of the
312
+ // code matches their width.
313
+ function updateGutters(cm) {
314
+ var gutters = cm.display.gutters, specs = cm.options.gutters;
315
+ removeChildren(gutters);
316
+ for (var i = 0; i < specs.length; ++i) {
317
+ var gutterClass = specs[i];
318
+ var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass));
319
+ if (gutterClass == "CodeMirror-linenumbers") {
320
+ cm.display.lineGutter = gElt;
321
+ gElt.style.width = (cm.display.lineNumWidth || 1) + "px";
322
+ }
323
+ }
324
+ gutters.style.display = i ? "" : "none";
325
+ updateGutterSpace(cm);
326
+ }
327
+
328
+ function updateGutterSpace(cm) {
329
+ var width = cm.display.gutters.offsetWidth;
330
+ cm.display.sizer.style.marginLeft = width + "px";
331
+ }
332
+
333
+ // Compute the character length of a line, taking into account
334
+ // collapsed ranges (see markText) that might hide parts, and join
335
+ // other lines onto it.
336
+ function lineLength(line) {
337
+ if (line.height == 0) return 0;
338
+ var len = line.text.length, merged, cur = line;
339
+ while (merged = collapsedSpanAtStart(cur)) {
340
+ var found = merged.find(0, true);
341
+ cur = found.from.line;
342
+ len += found.from.ch - found.to.ch;
343
+ }
344
+ cur = line;
345
+ while (merged = collapsedSpanAtEnd(cur)) {
346
+ var found = merged.find(0, true);
347
+ len -= cur.text.length - found.from.ch;
348
+ cur = found.to.line;
349
+ len += cur.text.length - found.to.ch;
350
+ }
351
+ return len;
352
+ }
353
+
354
+ // Find the longest line in the document.
355
+ function findMaxLine(cm) {
356
+ var d = cm.display, doc = cm.doc;
357
+ d.maxLine = getLine(doc, doc.first);
358
+ d.maxLineLength = lineLength(d.maxLine);
359
+ d.maxLineChanged = true;
360
+ doc.iter(function(line) {
361
+ var len = lineLength(line);
362
+ if (len > d.maxLineLength) {
363
+ d.maxLineLength = len;
364
+ d.maxLine = line;
365
+ }
366
+ });
367
+ }
368
+
369
+ // Make sure the gutters options contains the element
370
+ // "CodeMirror-linenumbers" when the lineNumbers option is true.
371
+ function setGuttersForLineNumbers(options) {
372
+ var found = indexOf(options.gutters, "CodeMirror-linenumbers");
373
+ if (found == -1 && options.lineNumbers) {
374
+ options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]);
375
+ } else if (found > -1 && !options.lineNumbers) {
376
+ options.gutters = options.gutters.slice(0);
377
+ options.gutters.splice(found, 1);
378
+ }
379
+ }
380
+
381
+ // SCROLLBARS
382
+
383
+ // Prepare DOM reads needed to update the scrollbars. Done in one
384
+ // shot to minimize update/measure roundtrips.
385
+ function measureForScrollbars(cm) {
386
+ var d = cm.display, gutterW = d.gutters.offsetWidth;
387
+ var docH = Math.round(cm.doc.height + paddingVert(cm.display));
388
+ return {
389
+ clientHeight: d.scroller.clientHeight,
390
+ viewHeight: d.wrapper.clientHeight,
391
+ scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
392
+ viewWidth: d.wrapper.clientWidth,
393
+ barLeft: cm.options.fixedGutter ? gutterW : 0,
394
+ docHeight: docH,
395
+ scrollHeight: docH + scrollGap(cm) + d.barHeight,
396
+ nativeBarWidth: d.nativeBarWidth,
397
+ gutterWidth: gutterW
398
+ };
399
+ }
400
+
401
+ function NativeScrollbars(place, scroll, cm) {
402
+ this.cm = cm;
403
+ var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
404
+ var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
405
+ place(vert); place(horiz);
406
+
407
+ on(vert, "scroll", function() {
408
+ if (vert.clientHeight) scroll(vert.scrollTop, "vertical");
409
+ });
410
+ on(horiz, "scroll", function() {
411
+ if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal");
412
+ });
413
+
414
+ this.checkedZeroWidth = false;
415
+ // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
416
+ if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px";
417
+ }
418
+
419
+ NativeScrollbars.prototype = copyObj({
420
+ update: function(measure) {
421
+ var needsH = measure.scrollWidth > measure.clientWidth + 1;
422
+ var needsV = measure.scrollHeight > measure.clientHeight + 1;
423
+ var sWidth = measure.nativeBarWidth;
424
+
425
+ if (needsV) {
426
+ this.vert.style.display = "block";
427
+ this.vert.style.bottom = needsH ? sWidth + "px" : "0";
428
+ var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
429
+ // A bug in IE8 can cause this value to be negative, so guard it.
430
+ this.vert.firstChild.style.height =
431
+ Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
432
+ } else {
433
+ this.vert.style.display = "";
434
+ this.vert.firstChild.style.height = "0";
435
+ }
436
+
437
+ if (needsH) {
438
+ this.horiz.style.display = "block";
439
+ this.horiz.style.right = needsV ? sWidth + "px" : "0";
440
+ this.horiz.style.left = measure.barLeft + "px";
441
+ var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
442
+ this.horiz.firstChild.style.width =
443
+ (measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
444
+ } else {
445
+ this.horiz.style.display = "";
446
+ this.horiz.firstChild.style.width = "0";
447
+ }
448
+
449
+ if (!this.checkedZeroWidth && measure.clientHeight > 0) {
450
+ if (sWidth == 0) this.zeroWidthHack();
451
+ this.checkedZeroWidth = true;
452
+ }
453
+
454
+ return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0};
455
+ },
456
+ setScrollLeft: function(pos) {
457
+ if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos;
458
+ if (this.disableHoriz) this.enableZeroWidthBar(this.horiz, this.disableHoriz);
459
+ },
460
+ setScrollTop: function(pos) {
461
+ if (this.vert.scrollTop != pos) this.vert.scrollTop = pos;
462
+ if (this.disableVert) this.enableZeroWidthBar(this.vert, this.disableVert);
463
+ },
464
+ zeroWidthHack: function() {
465
+ var w = mac && !mac_geMountainLion ? "12px" : "18px";
466
+ this.horiz.style.height = this.vert.style.width = w;
467
+ this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
468
+ this.disableHoriz = new Delayed;
469
+ this.disableVert = new Delayed;
470
+ },
471
+ enableZeroWidthBar: function(bar, delay) {
472
+ bar.style.pointerEvents = "auto";
473
+ function maybeDisable() {
474
+ // To find out whether the scrollbar is still visible, we
475
+ // check whether the element under the pixel in the bottom
476
+ // left corner of the scrollbar box is the scrollbar box
477
+ // itself (when the bar is still visible) or its filler child
478
+ // (when the bar is hidden). If it is still visible, we keep
479
+ // it enabled, if it's hidden, we disable pointer events.
480
+ var box = bar.getBoundingClientRect();
481
+ var elt = document.elementFromPoint(box.left + 1, box.bottom - 1);
482
+ if (elt != bar) bar.style.pointerEvents = "none";
483
+ else delay.set(1000, maybeDisable);
484
+ }
485
+ delay.set(1000, maybeDisable);
486
+ },
487
+ clear: function() {
488
+ var parent = this.horiz.parentNode;
489
+ parent.removeChild(this.horiz);
490
+ parent.removeChild(this.vert);
491
+ }
492
+ }, NativeScrollbars.prototype);
493
+
494
+ function NullScrollbars() {}
495
+
496
+ NullScrollbars.prototype = copyObj({
497
+ update: function() { return {bottom: 0, right: 0}; },
498
+ setScrollLeft: function() {},
499
+ setScrollTop: function() {},
500
+ clear: function() {}
501
+ }, NullScrollbars.prototype);
502
+
503
+ CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
504
+
505
+ function initScrollbars(cm) {
506
+ if (cm.display.scrollbars) {
507
+ cm.display.scrollbars.clear();
508
+ if (cm.display.scrollbars.addClass)
509
+ rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);
510
+ }
511
+
512
+ cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) {
513
+ cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
514
+ // Prevent clicks in the scrollbars from killing focus
515
+ on(node, "mousedown", function() {
516
+ if (cm.state.focused) setTimeout(function() { cm.display.input.focus(); }, 0);
517
+ });
518
+ node.setAttribute("cm-not-content", "true");
519
+ }, function(pos, axis) {
520
+ if (axis == "horizontal") setScrollLeft(cm, pos);
521
+ else setScrollTop(cm, pos);
522
+ }, cm);
523
+ if (cm.display.scrollbars.addClass)
524
+ addClass(cm.display.wrapper, cm.display.scrollbars.addClass);
525
+ }
526
+
527
+ function updateScrollbars(cm, measure) {
528
+ if (!measure) measure = measureForScrollbars(cm);
529
+ var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
530
+ updateScrollbarsInner(cm, measure);
531
+ for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
532
+ if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
533
+ updateHeightsInViewport(cm);
534
+ updateScrollbarsInner(cm, measureForScrollbars(cm));
535
+ startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
536
+ }
537
+ }
538
+
539
+ // Re-synchronize the fake scrollbars with the actual size of the
540
+ // content.
541
+ function updateScrollbarsInner(cm, measure) {
542
+ var d = cm.display;
543
+ var sizes = d.scrollbars.update(measure);
544
+
545
+ d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
546
+ d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
547
+ d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"
548
+
549
+ if (sizes.right && sizes.bottom) {
550
+ d.scrollbarFiller.style.display = "block";
551
+ d.scrollbarFiller.style.height = sizes.bottom + "px";
552
+ d.scrollbarFiller.style.width = sizes.right + "px";
553
+ } else d.scrollbarFiller.style.display = "";
554
+ if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
555
+ d.gutterFiller.style.display = "block";
556
+ d.gutterFiller.style.height = sizes.bottom + "px";
557
+ d.gutterFiller.style.width = measure.gutterWidth + "px";
558
+ } else d.gutterFiller.style.display = "";
559
+ }
560
+
561
+ // Compute the lines that are visible in a given viewport (defaults
562
+ // the the current scroll position). viewport may contain top,
563
+ // height, and ensure (see op.scrollToPos) properties.
564
+ function visibleLines(display, doc, viewport) {
565
+ var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop;
566
+ top = Math.floor(top - paddingTop(display));
567
+ var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight;
568
+
569
+ var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom);
570
+ // Ensure is a {from: {line, ch}, to: {line, ch}} object, and
571
+ // forces those lines into the viewport (if possible).
572
+ if (viewport && viewport.ensure) {
573
+ var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line;
574
+ if (ensureFrom < from) {
575
+ from = ensureFrom;
576
+ to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
577
+ } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
578
+ from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
579
+ to = ensureTo;
580
+ }
581
+ }
582
+ return {from: from, to: Math.max(to, from + 1)};
583
+ }
584
+
585
+ // LINE NUMBERS
586
+
587
+ // Re-align line numbers and gutter marks to compensate for
588
+ // horizontal scrolling.
589
+ function alignHorizontally(cm) {
590
+ var display = cm.display, view = display.view;
591
+ if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return;
592
+ var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft;
593
+ var gutterW = display.gutters.offsetWidth, left = comp + "px";
594
+ for (var i = 0; i < view.length; i++) if (!view[i].hidden) {
595
+ if (cm.options.fixedGutter && view[i].gutter)
596
+ view[i].gutter.style.left = left;
597
+ var align = view[i].alignable;
598
+ if (align) for (var j = 0; j < align.length; j++)
599
+ align[j].style.left = left;
600
+ }
601
+ if (cm.options.fixedGutter)
602
+ display.gutters.style.left = (comp + gutterW) + "px";
603
+ }
604
+
605
+ // Used to ensure that the line number gutter is still the right
606
+ // size for the current document size. Returns true when an update
607
+ // is needed.
608
+ function maybeUpdateLineNumberWidth(cm) {
609
+ if (!cm.options.lineNumbers) return false;
610
+ var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display;
611
+ if (last.length != display.lineNumChars) {
612
+ var test = display.measure.appendChild(elt("div", [elt("div", last)],
613
+ "CodeMirror-linenumber CodeMirror-gutter-elt"));
614
+ var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
615
+ display.lineGutter.style.width = "";
616
+ display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
617
+ display.lineNumWidth = display.lineNumInnerWidth + padding;
618
+ display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
619
+ display.lineGutter.style.width = display.lineNumWidth + "px";
620
+ updateGutterSpace(cm);
621
+ return true;
622
+ }
623
+ return false;
624
+ }
625
+
626
+ function lineNumberFor(options, i) {
627
+ return String(options.lineNumberFormatter(i + options.firstLineNumber));
628
+ }
629
+
630
+ // Computes display.scroller.scrollLeft + display.gutters.offsetWidth,
631
+ // but using getBoundingClientRect to get a sub-pixel-accurate
632
+ // result.
633
+ function compensateForHScroll(display) {
634
+ return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left;
635
+ }
636
+
637
+ // DISPLAY DRAWING
638
+
639
+ function DisplayUpdate(cm, viewport, force) {
640
+ var display = cm.display;
641
+
642
+ this.viewport = viewport;
643
+ // Store some values that we'll need later (but don't want to force a relayout for)
644
+ this.visible = visibleLines(display, cm.doc, viewport);
645
+ this.editorIsHidden = !display.wrapper.offsetWidth;
646
+ this.wrapperHeight = display.wrapper.clientHeight;
647
+ this.wrapperWidth = display.wrapper.clientWidth;
648
+ this.oldDisplayWidth = displayWidth(cm);
649
+ this.force = force;
650
+ this.dims = getDimensions(cm);
651
+ this.events = [];
652
+ }
653
+
654
+ DisplayUpdate.prototype.signal = function(emitter, type) {
655
+ if (hasHandler(emitter, type))
656
+ this.events.push(arguments);
657
+ };
658
+ DisplayUpdate.prototype.finish = function() {
659
+ for (var i = 0; i < this.events.length; i++)
660
+ signal.apply(null, this.events[i]);
661
+ };
662
+
663
+ function maybeClipScrollbars(cm) {
664
+ var display = cm.display;
665
+ if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
666
+ display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
667
+ display.heightForcer.style.height = scrollGap(cm) + "px";
668
+ display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
669
+ display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
670
+ display.scrollbarsClipped = true;
671
+ }
672
+ }
673
+
674
+ // Does the actual updating of the line display. Bails out
675
+ // (returning false) when there is nothing to be done and forced is
676
+ // false.
677
+ function updateDisplayIfNeeded(cm, update) {
678
+ var display = cm.display, doc = cm.doc;
679
+
680
+ if (update.editorIsHidden) {
681
+ resetView(cm);
682
+ return false;
683
+ }
684
+
685
+ // Bail out if the visible area is already rendered and nothing changed.
686
+ if (!update.force &&
687
+ update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
688
+ (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
689
+ display.renderedView == display.view && countDirtyView(cm) == 0)
690
+ return false;
691
+
692
+ if (maybeUpdateLineNumberWidth(cm)) {
693
+ resetView(cm);
694
+ update.dims = getDimensions(cm);
695
+ }
696
+
697
+ // Compute a suitable new viewport (from & to)
698
+ var end = doc.first + doc.size;
699
+ var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
700
+ var to = Math.min(end, update.visible.to + cm.options.viewportMargin);
701
+ if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom);
702
+ if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo);
703
+ if (sawCollapsedSpans) {
704
+ from = visualLineNo(cm.doc, from);
705
+ to = visualLineEndNo(cm.doc, to);
706
+ }
707
+
708
+ var different = from != display.viewFrom || to != display.viewTo ||
709
+ display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
710
+ adjustView(cm, from, to);
711
+
712
+ display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom));
713
+ // Position the mover div to align with the current scroll position
714
+ cm.display.mover.style.top = display.viewOffset + "px";
715
+
716
+ var toUpdate = countDirtyView(cm);
717
+ if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view &&
718
+ (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
719
+ return false;
720
+
721
+ // For big changes, we hide the enclosing element during the
722
+ // update, since that speeds up the operations on most browsers.
723
+ var focused = activeElt();
724
+ if (toUpdate > 4) display.lineDiv.style.display = "none";
725
+ patchDisplay(cm, display.updateLineNumbers, update.dims);
726
+ if (toUpdate > 4) display.lineDiv.style.display = "";
727
+ display.renderedView = display.view;
728
+ // There might have been a widget with a focused element that got
729
+ // hidden or updated, if so re-focus it.
730
+ if (focused && activeElt() != focused && focused.offsetHeight) focused.focus();
731
+
732
+ // Prevent selection and cursors from interfering with the scroll
733
+ // width and height.
734
+ removeChildren(display.cursorDiv);
735
+ removeChildren(display.selectionDiv);
736
+ display.gutters.style.height = display.sizer.style.minHeight = 0;
737
+
738
+ if (different) {
739
+ display.lastWrapHeight = update.wrapperHeight;
740
+ display.lastWrapWidth = update.wrapperWidth;
741
+ startWorker(cm, 400);
742
+ }
743
+
744
+ display.updateLineNumbers = null;
745
+
746
+ return true;
747
+ }
748
+
749
+ function postUpdateDisplay(cm, update) {
750
+ var viewport = update.viewport;
751
+
752
+ for (var first = true;; first = false) {
753
+ if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
754
+ // Clip forced viewport to actual scrollable area.
755
+ if (viewport && viewport.top != null)
756
+ viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)};
757
+ // Updated line heights might result in the drawn area not
758
+ // actually covering the viewport. Keep looping until it does.
759
+ update.visible = visibleLines(cm.display, cm.doc, viewport);
760
+ if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
761
+ break;
762
+ }
763
+ if (!updateDisplayIfNeeded(cm, update)) break;
764
+ updateHeightsInViewport(cm);
765
+ var barMeasure = measureForScrollbars(cm);
766
+ updateSelection(cm);
767
+ updateScrollbars(cm, barMeasure);
768
+ setDocumentHeight(cm, barMeasure);
769
+ }
770
+
771
+ update.signal(cm, "update", cm);
772
+ if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
773
+ update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
774
+ cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
775
+ }
776
+ }
777
+
778
+ function updateDisplaySimple(cm, viewport) {
779
+ var update = new DisplayUpdate(cm, viewport);
780
+ if (updateDisplayIfNeeded(cm, update)) {
781
+ updateHeightsInViewport(cm);
782
+ postUpdateDisplay(cm, update);
783
+ var barMeasure = measureForScrollbars(cm);
784
+ updateSelection(cm);
785
+ updateScrollbars(cm, barMeasure);
786
+ setDocumentHeight(cm, barMeasure);
787
+ update.finish();
788
+ }
789
+ }
790
+
791
+ function setDocumentHeight(cm, measure) {
792
+ cm.display.sizer.style.minHeight = measure.docHeight + "px";
793
+ cm.display.heightForcer.style.top = measure.docHeight + "px";
794
+ cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
795
+ }
796
+
797
+ // Read the actual heights of the rendered lines, and update their
798
+ // stored heights to match.
799
+ function updateHeightsInViewport(cm) {
800
+ var display = cm.display;
801
+ var prevBottom = display.lineDiv.offsetTop;
802
+ for (var i = 0; i < display.view.length; i++) {
803
+ var cur = display.view[i], height;
804
+ if (cur.hidden) continue;
805
+ if (ie && ie_version < 8) {
806
+ var bot = cur.node.offsetTop + cur.node.offsetHeight;
807
+ height = bot - prevBottom;
808
+ prevBottom = bot;
809
+ } else {
810
+ var box = cur.node.getBoundingClientRect();
811
+ height = box.bottom - box.top;
812
+ }
813
+ var diff = cur.line.height - height;
814
+ if (height < 2) height = textHeight(display);
815
+ if (diff > .001 || diff < -.001) {
816
+ updateLineHeight(cur.line, height);
817
+ updateWidgetHeight(cur.line);
818
+ if (cur.rest) for (var j = 0; j < cur.rest.length; j++)
819
+ updateWidgetHeight(cur.rest[j]);
820
+ }
821
+ }
822
+ }
823
+
824
+ // Read and store the height of line widgets associated with the
825
+ // given line.
826
+ function updateWidgetHeight(line) {
827
+ if (line.widgets) for (var i = 0; i < line.widgets.length; ++i)
828
+ line.widgets[i].height = line.widgets[i].node.parentNode.offsetHeight;
829
+ }
830
+
831
+ // Do a bulk-read of the DOM positions and sizes needed to draw the
832
+ // view, so that we don't interleave reading and writing to the DOM.
833
+ function getDimensions(cm) {
834
+ var d = cm.display, left = {}, width = {};
835
+ var gutterLeft = d.gutters.clientLeft;
836
+ for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
837
+ left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft;
838
+ width[cm.options.gutters[i]] = n.clientWidth;
839
+ }
840
+ return {fixedPos: compensateForHScroll(d),
841
+ gutterTotalWidth: d.gutters.offsetWidth,
842
+ gutterLeft: left,
843
+ gutterWidth: width,
844
+ wrapperWidth: d.wrapper.clientWidth};
845
+ }
846
+
847
+ // Sync the actual display DOM structure with display.view, removing
848
+ // nodes for lines that are no longer in view, and creating the ones
849
+ // that are not there yet, and updating the ones that are out of
850
+ // date.
851
+ function patchDisplay(cm, updateNumbersFrom, dims) {
852
+ var display = cm.display, lineNumbers = cm.options.lineNumbers;
853
+ var container = display.lineDiv, cur = container.firstChild;
854
+
855
+ function rm(node) {
856
+ var next = node.nextSibling;
857
+ // Works around a throw-scroll bug in OS X Webkit
858
+ if (webkit && mac && cm.display.currentWheelTarget == node)
859
+ node.style.display = "none";
860
+ else
861
+ node.parentNode.removeChild(node);
862
+ return next;
863
+ }
864
+
865
+ var view = display.view, lineN = display.viewFrom;
866
+ // Loop over the elements in the view, syncing cur (the DOM nodes
867
+ // in display.lineDiv) with the view as we go.
868
+ for (var i = 0; i < view.length; i++) {
869
+ var lineView = view[i];
870
+ if (lineView.hidden) {
871
+ } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet
872
+ var node = buildLineElement(cm, lineView, lineN, dims);
873
+ container.insertBefore(node, cur);
874
+ } else { // Already drawn
875
+ while (cur != lineView.node) cur = rm(cur);
876
+ var updateNumber = lineNumbers && updateNumbersFrom != null &&
877
+ updateNumbersFrom <= lineN && lineView.lineNumber;
878
+ if (lineView.changes) {
879
+ if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false;
880
+ updateLineForChanges(cm, lineView, lineN, dims);
881
+ }
882
+ if (updateNumber) {
883
+ removeChildren(lineView.lineNumber);
884
+ lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN)));
885
+ }
886
+ cur = lineView.node.nextSibling;
887
+ }
888
+ lineN += lineView.size;
889
+ }
890
+ while (cur) cur = rm(cur);
891
+ }
892
+
893
+ // When an aspect of a line changes, a string is added to
894
+ // lineView.changes. This updates the relevant part of the line's
895
+ // DOM structure.
896
+ function updateLineForChanges(cm, lineView, lineN, dims) {
897
+ for (var j = 0; j < lineView.changes.length; j++) {
898
+ var type = lineView.changes[j];
899
+ if (type == "text") updateLineText(cm, lineView);
900
+ else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims);
901
+ else if (type == "class") updateLineClasses(lineView);
902
+ else if (type == "widget") updateLineWidgets(cm, lineView, dims);
903
+ }
904
+ lineView.changes = null;
905
+ }
906
+
907
+ // Lines with gutter elements, widgets or a background class need to
908
+ // be wrapped, and have the extra elements added to the wrapper div
909
+ function ensureLineWrapped(lineView) {
910
+ if (lineView.node == lineView.text) {
911
+ lineView.node = elt("div", null, null, "position: relative");
912
+ if (lineView.text.parentNode)
913
+ lineView.text.parentNode.replaceChild(lineView.node, lineView.text);
914
+ lineView.node.appendChild(lineView.text);
915
+ if (ie && ie_version < 8) lineView.node.style.zIndex = 2;
916
+ }
917
+ return lineView.node;
918
+ }
919
+
920
+ function updateLineBackground(lineView) {
921
+ var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass;
922
+ if (cls) cls += " CodeMirror-linebackground";
923
+ if (lineView.background) {
924
+ if (cls) lineView.background.className = cls;
925
+ else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; }
926
+ } else if (cls) {
927
+ var wrap = ensureLineWrapped(lineView);
928
+ lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild);
929
+ }
930
+ }
931
+
932
+ // Wrapper around buildLineContent which will reuse the structure
933
+ // in display.externalMeasured when possible.
934
+ function getLineContent(cm, lineView) {
935
+ var ext = cm.display.externalMeasured;
936
+ if (ext && ext.line == lineView.line) {
937
+ cm.display.externalMeasured = null;
938
+ lineView.measure = ext.measure;
939
+ return ext.built;
940
+ }
941
+ return buildLineContent(cm, lineView);
942
+ }
943
+
944
+ // Redraw the line's text. Interacts with the background and text
945
+ // classes because the mode may output tokens that influence these
946
+ // classes.
947
+ function updateLineText(cm, lineView) {
948
+ var cls = lineView.text.className;
949
+ var built = getLineContent(cm, lineView);
950
+ if (lineView.text == lineView.node) lineView.node = built.pre;
951
+ lineView.text.parentNode.replaceChild(built.pre, lineView.text);
952
+ lineView.text = built.pre;
953
+ if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) {
954
+ lineView.bgClass = built.bgClass;
955
+ lineView.textClass = built.textClass;
956
+ updateLineClasses(lineView);
957
+ } else if (cls) {
958
+ lineView.text.className = cls;
959
+ }
960
+ }
961
+
962
+ function updateLineClasses(lineView) {
963
+ updateLineBackground(lineView);
964
+ if (lineView.line.wrapClass)
965
+ ensureLineWrapped(lineView).className = lineView.line.wrapClass;
966
+ else if (lineView.node != lineView.text)
967
+ lineView.node.className = "";
968
+ var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass;
969
+ lineView.text.className = textClass || "";
970
+ }
971
+
972
+ function updateLineGutter(cm, lineView, lineN, dims) {
973
+ if (lineView.gutter) {
974
+ lineView.node.removeChild(lineView.gutter);
975
+ lineView.gutter = null;
976
+ }
977
+ if (lineView.gutterBackground) {
978
+ lineView.node.removeChild(lineView.gutterBackground);
979
+ lineView.gutterBackground = null;
980
+ }
981
+ if (lineView.line.gutterClass) {
982
+ var wrap = ensureLineWrapped(lineView);
983
+ lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
984
+ "left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) +
985
+ "px; width: " + dims.gutterTotalWidth + "px");
986
+ wrap.insertBefore(lineView.gutterBackground, lineView.text);
987
+ }
988
+ var markers = lineView.line.gutterMarkers;
989
+ if (cm.options.lineNumbers || markers) {
990
+ var wrap = ensureLineWrapped(lineView);
991
+ var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " +
992
+ (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px");
993
+ cm.display.input.setUneditable(gutterWrap);
994
+ wrap.insertBefore(gutterWrap, lineView.text);
995
+ if (lineView.line.gutterClass)
996
+ gutterWrap.className += " " + lineView.line.gutterClass;
997
+ if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"]))
998
+ lineView.lineNumber = gutterWrap.appendChild(
999
+ elt("div", lineNumberFor(cm.options, lineN),
1000
+ "CodeMirror-linenumber CodeMirror-gutter-elt",
1001
+ "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: "
1002
+ + cm.display.lineNumInnerWidth + "px"));
1003
+ if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) {
1004
+ var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id];
1005
+ if (found)
1006
+ gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " +
1007
+ dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px"));
1008
+ }
1009
+ }
1010
+ }
1011
+
1012
+ function updateLineWidgets(cm, lineView, dims) {
1013
+ if (lineView.alignable) lineView.alignable = null;
1014
+ for (var node = lineView.node.firstChild, next; node; node = next) {
1015
+ var next = node.nextSibling;
1016
+ if (node.className == "CodeMirror-linewidget")
1017
+ lineView.node.removeChild(node);
1018
+ }
1019
+ insertLineWidgets(cm, lineView, dims);
1020
+ }
1021
+
1022
+ // Build a line's DOM representation from scratch
1023
+ function buildLineElement(cm, lineView, lineN, dims) {
1024
+ var built = getLineContent(cm, lineView);
1025
+ lineView.text = lineView.node = built.pre;
1026
+ if (built.bgClass) lineView.bgClass = built.bgClass;
1027
+ if (built.textClass) lineView.textClass = built.textClass;
1028
+
1029
+ updateLineClasses(lineView);
1030
+ updateLineGutter(cm, lineView, lineN, dims);
1031
+ insertLineWidgets(cm, lineView, dims);
1032
+ return lineView.node;
1033
+ }
1034
+
1035
+ // A lineView may contain multiple logical lines (when merged by
1036
+ // collapsed spans). The widgets for all of them need to be drawn.
1037
+ function insertLineWidgets(cm, lineView, dims) {
1038
+ insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
1039
+ if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
1040
+ insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false);
1041
+ }
1042
+
1043
+ function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) {
1044
+ if (!line.widgets) return;
1045
+ var wrap = ensureLineWrapped(lineView);
1046
+ for (var i = 0, ws = line.widgets; i < ws.length; ++i) {
1047
+ var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget");
1048
+ if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true");
1049
+ positionLineWidget(widget, node, lineView, dims);
1050
+ cm.display.input.setUneditable(node);
1051
+ if (allowAbove && widget.above)
1052
+ wrap.insertBefore(node, lineView.gutter || lineView.text);
1053
+ else
1054
+ wrap.appendChild(node);
1055
+ signalLater(widget, "redraw");
1056
+ }
1057
+ }
1058
+
1059
+ function positionLineWidget(widget, node, lineView, dims) {
1060
+ if (widget.noHScroll) {
1061
+ (lineView.alignable || (lineView.alignable = [])).push(node);
1062
+ var width = dims.wrapperWidth;
1063
+ node.style.left = dims.fixedPos + "px";
1064
+ if (!widget.coverGutter) {
1065
+ width -= dims.gutterTotalWidth;
1066
+ node.style.paddingLeft = dims.gutterTotalWidth + "px";
1067
+ }
1068
+ node.style.width = width + "px";
1069
+ }
1070
+ if (widget.coverGutter) {
1071
+ node.style.zIndex = 5;
1072
+ node.style.position = "relative";
1073
+ if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px";
1074
+ }
1075
+ }
1076
+
1077
+ // POSITION OBJECT
1078
+
1079
+ // A Pos instance represents a position within the text.
1080
+ var Pos = CodeMirror.Pos = function(line, ch) {
1081
+ if (!(this instanceof Pos)) return new Pos(line, ch);
1082
+ this.line = line; this.ch = ch;
1083
+ };
1084
+
1085
+ // Compare two positions, return 0 if they are the same, a negative
1086
+ // number when a is less, and a positive number otherwise.
1087
+ var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; };
1088
+
1089
+ function copyPos(x) {return Pos(x.line, x.ch);}
1090
+ function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; }
1091
+ function minPos(a, b) { return cmp(a, b) < 0 ? a : b; }
1092
+
1093
+ // INPUT HANDLING
1094
+
1095
+ function ensureFocus(cm) {
1096
+ if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
1097
+ }
1098
+
1099
+ // This will be set to a {lineWise: bool, text: [string]} object, so
1100
+ // that, when pasting, we know what kind of selections the copied
1101
+ // text was made out of.
1102
+ var lastCopied = null;
1103
+
1104
+ function applyTextInput(cm, inserted, deleted, sel, origin) {
1105
+ var doc = cm.doc;
1106
+ cm.display.shift = false;
1107
+ if (!sel) sel = doc.sel;
1108
+
1109
+ var paste = cm.state.pasteIncoming || origin == "paste";
1110
+ var textLines = doc.splitLines(inserted), multiPaste = null
1111
+ // When pasing N lines into N selections, insert one line per selection
1112
+ if (paste && sel.ranges.length > 1) {
1113
+ if (lastCopied && lastCopied.text.join("\n") == inserted) {
1114
+ if (sel.ranges.length % lastCopied.text.length == 0) {
1115
+ multiPaste = [];
1116
+ for (var i = 0; i < lastCopied.text.length; i++)
1117
+ multiPaste.push(doc.splitLines(lastCopied.text[i]));
1118
+ }
1119
+ } else if (textLines.length == sel.ranges.length) {
1120
+ multiPaste = map(textLines, function(l) { return [l]; });
1121
+ }
1122
+ }
1123
+
1124
+ // Normal behavior is to insert the new text into every selection
1125
+ for (var i = sel.ranges.length - 1; i >= 0; i--) {
1126
+ var range = sel.ranges[i];
1127
+ var from = range.from(), to = range.to();
1128
+ if (range.empty()) {
1129
+ if (deleted && deleted > 0) // Handle deletion
1130
+ from = Pos(from.line, from.ch - deleted);
1131
+ else if (cm.state.overwrite && !paste) // Handle overwrite
1132
+ to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
1133
+ else if (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted)
1134
+ from = to = Pos(from.line, 0)
1135
+ }
1136
+ var updateInput = cm.curOp.updateInput;
1137
+ var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines,
1138
+ origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
1139
+ makeChange(cm.doc, changeEvent);
1140
+ signalLater(cm, "inputRead", cm, changeEvent);
1141
+ }
1142
+ if (inserted && !paste)
1143
+ triggerElectric(cm, inserted);
1144
+
1145
+ ensureCursorVisible(cm);
1146
+ cm.curOp.updateInput = updateInput;
1147
+ cm.curOp.typing = true;
1148
+ cm.state.pasteIncoming = cm.state.cutIncoming = false;
1149
+ }
1150
+
1151
+ function handlePaste(e, cm) {
1152
+ var pasted = e.clipboardData && e.clipboardData.getData("text/plain");
1153
+ if (pasted) {
1154
+ e.preventDefault();
1155
+ if (!cm.isReadOnly() && !cm.options.disableInput)
1156
+ runInOp(cm, function() { applyTextInput(cm, pasted, 0, null, "paste"); });
1157
+ return true;
1158
+ }
1159
+ }
1160
+
1161
+ function triggerElectric(cm, inserted) {
1162
+ // When an 'electric' character is inserted, immediately trigger a reindent
1163
+ if (!cm.options.electricChars || !cm.options.smartIndent) return;
1164
+ var sel = cm.doc.sel;
1165
+
1166
+ for (var i = sel.ranges.length - 1; i >= 0; i--) {
1167
+ var range = sel.ranges[i];
1168
+ if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue;
1169
+ var mode = cm.getModeAt(range.head);
1170
+ var indented = false;
1171
+ if (mode.electricChars) {
1172
+ for (var j = 0; j < mode.electricChars.length; j++)
1173
+ if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
1174
+ indented = indentLine(cm, range.head.line, "smart");
1175
+ break;
1176
+ }
1177
+ } else if (mode.electricInput) {
1178
+ if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
1179
+ indented = indentLine(cm, range.head.line, "smart");
1180
+ }
1181
+ if (indented) signalLater(cm, "electricInput", cm, range.head.line);
1182
+ }
1183
+ }
1184
+
1185
+ function copyableRanges(cm) {
1186
+ var text = [], ranges = [];
1187
+ for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
1188
+ var line = cm.doc.sel.ranges[i].head.line;
1189
+ var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
1190
+ ranges.push(lineRange);
1191
+ text.push(cm.getRange(lineRange.anchor, lineRange.head));
1192
+ }
1193
+ return {text: text, ranges: ranges};
1194
+ }
1195
+
1196
+ function disableBrowserMagic(field) {
1197
+ field.setAttribute("autocorrect", "off");
1198
+ field.setAttribute("autocapitalize", "off");
1199
+ field.setAttribute("spellcheck", "false");
1200
+ }
1201
+
1202
+ // TEXTAREA INPUT STYLE
1203
+
1204
+ function TextareaInput(cm) {
1205
+ this.cm = cm;
1206
+ // See input.poll and input.reset
1207
+ this.prevInput = "";
1208
+
1209
+ // Flag that indicates whether we expect input to appear real soon
1210
+ // now (after some event like 'keypress' or 'input') and are
1211
+ // polling intensively.
1212
+ this.pollingFast = false;
1213
+ // Self-resetting timeout for the poller
1214
+ this.polling = new Delayed();
1215
+ // Tracks when input.reset has punted to just putting a short
1216
+ // string into the textarea instead of the full selection.
1217
+ this.inaccurateSelection = false;
1218
+ // Used to work around IE issue with selection being forgotten when focus moves away from textarea
1219
+ this.hasSelection = false;
1220
+ this.composing = null;
1221
+ };
1222
+
1223
+ function hiddenTextarea() {
1224
+ var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none");
1225
+ var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
1226
+ // The textarea is kept positioned near the cursor to prevent the
1227
+ // fact that it'll be scrolled into view on input from scrolling
1228
+ // our fake cursor out of view. On webkit, when wrap=off, paste is
1229
+ // very slow. So make the area wide instead.
1230
+ if (webkit) te.style.width = "1000px";
1231
+ else te.setAttribute("wrap", "off");
1232
+ // If border: 0; -- iOS fails to open keyboard (issue #1287)
1233
+ if (ios) te.style.border = "1px solid black";
1234
+ disableBrowserMagic(te);
1235
+ return div;
1236
+ }
1237
+
1238
+ TextareaInput.prototype = copyObj({
1239
+ init: function(display) {
1240
+ var input = this, cm = this.cm;
1241
+
1242
+ // Wraps and hides input textarea
1243
+ var div = this.wrapper = hiddenTextarea();
1244
+ // The semihidden textarea that is focused when the editor is
1245
+ // focused, and receives input.
1246
+ var te = this.textarea = div.firstChild;
1247
+ display.wrapper.insertBefore(div, display.wrapper.firstChild);
1248
+
1249
+ // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
1250
+ if (ios) te.style.width = "0px";
1251
+
1252
+ on(te, "input", function() {
1253
+ if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null;
1254
+ input.poll();
1255
+ });
1256
+
1257
+ on(te, "paste", function(e) {
1258
+ if (signalDOMEvent(cm, e) || handlePaste(e, cm)) return
1259
+
1260
+ cm.state.pasteIncoming = true;
1261
+ input.fastPoll();
1262
+ });
1263
+
1264
+ function prepareCopyCut(e) {
1265
+ if (signalDOMEvent(cm, e)) return
1266
+ if (cm.somethingSelected()) {
1267
+ lastCopied = {lineWise: false, text: cm.getSelections()};
1268
+ if (input.inaccurateSelection) {
1269
+ input.prevInput = "";
1270
+ input.inaccurateSelection = false;
1271
+ te.value = lastCopied.text.join("\n");
1272
+ selectInput(te);
1273
+ }
1274
+ } else if (!cm.options.lineWiseCopyCut) {
1275
+ return;
1276
+ } else {
1277
+ var ranges = copyableRanges(cm);
1278
+ lastCopied = {lineWise: true, text: ranges.text};
1279
+ if (e.type == "cut") {
1280
+ cm.setSelections(ranges.ranges, null, sel_dontScroll);
1281
+ } else {
1282
+ input.prevInput = "";
1283
+ te.value = ranges.text.join("\n");
1284
+ selectInput(te);
1285
+ }
1286
+ }
1287
+ if (e.type == "cut") cm.state.cutIncoming = true;
1288
+ }
1289
+ on(te, "cut", prepareCopyCut);
1290
+ on(te, "copy", prepareCopyCut);
1291
+
1292
+ on(display.scroller, "paste", function(e) {
1293
+ if (eventInWidget(display, e) || signalDOMEvent(cm, e)) return;
1294
+ cm.state.pasteIncoming = true;
1295
+ input.focus();
1296
+ });
1297
+
1298
+ // Prevent normal selection in the editor (we handle our own)
1299
+ on(display.lineSpace, "selectstart", function(e) {
1300
+ if (!eventInWidget(display, e)) e_preventDefault(e);
1301
+ });
1302
+
1303
+ on(te, "compositionstart", function() {
1304
+ var start = cm.getCursor("from");
1305
+ if (input.composing) input.composing.range.clear()
1306
+ input.composing = {
1307
+ start: start,
1308
+ range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
1309
+ };
1310
+ });
1311
+ on(te, "compositionend", function() {
1312
+ if (input.composing) {
1313
+ input.poll();
1314
+ input.composing.range.clear();
1315
+ input.composing = null;
1316
+ }
1317
+ });
1318
+ },
1319
+
1320
+ prepareSelection: function() {
1321
+ // Redraw the selection and/or cursor
1322
+ var cm = this.cm, display = cm.display, doc = cm.doc;
1323
+ var result = prepareSelection(cm);
1324
+
1325
+ // Move the hidden textarea near the cursor to prevent scrolling artifacts
1326
+ if (cm.options.moveInputWithCursor) {
1327
+ var headPos = cursorCoords(cm, doc.sel.primary().head, "div");
1328
+ var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect();
1329
+ result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
1330
+ headPos.top + lineOff.top - wrapOff.top));
1331
+ result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
1332
+ headPos.left + lineOff.left - wrapOff.left));
1333
+ }
1334
+
1335
+ return result;
1336
+ },
1337
+
1338
+ showSelection: function(drawn) {
1339
+ var cm = this.cm, display = cm.display;
1340
+ removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
1341
+ removeChildrenAndAdd(display.selectionDiv, drawn.selection);
1342
+ if (drawn.teTop != null) {
1343
+ this.wrapper.style.top = drawn.teTop + "px";
1344
+ this.wrapper.style.left = drawn.teLeft + "px";
1345
+ }
1346
+ },
1347
+
1348
+ // Reset the input to correspond to the selection (or to be empty,
1349
+ // when not typing and nothing is selected)
1350
+ reset: function(typing) {
1351
+ if (this.contextMenuPending) return;
1352
+ var minimal, selected, cm = this.cm, doc = cm.doc;
1353
+ if (cm.somethingSelected()) {
1354
+ this.prevInput = "";
1355
+ var range = doc.sel.primary();
1356
+ minimal = hasCopyEvent &&
1357
+ (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000);
1358
+ var content = minimal ? "-" : selected || cm.getSelection();
1359
+ this.textarea.value = content;
1360
+ if (cm.state.focused) selectInput(this.textarea);
1361
+ if (ie && ie_version >= 9) this.hasSelection = content;
1362
+ } else if (!typing) {
1363
+ this.prevInput = this.textarea.value = "";
1364
+ if (ie && ie_version >= 9) this.hasSelection = null;
1365
+ }
1366
+ this.inaccurateSelection = minimal;
1367
+ },
1368
+
1369
+ getField: function() { return this.textarea; },
1370
+
1371
+ supportsTouch: function() { return false; },
1372
+
1373
+ focus: function() {
1374
+ if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
1375
+ try { this.textarea.focus(); }
1376
+ catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
1377
+ }
1378
+ },
1379
+
1380
+ blur: function() { this.textarea.blur(); },
1381
+
1382
+ resetPosition: function() {
1383
+ this.wrapper.style.top = this.wrapper.style.left = 0;
1384
+ },
1385
+
1386
+ receivedFocus: function() { this.slowPoll(); },
1387
+
1388
+ // Poll for input changes, using the normal rate of polling. This
1389
+ // runs as long as the editor is focused.
1390
+ slowPoll: function() {
1391
+ var input = this;
1392
+ if (input.pollingFast) return;
1393
+ input.polling.set(this.cm.options.pollInterval, function() {
1394
+ input.poll();
1395
+ if (input.cm.state.focused) input.slowPoll();
1396
+ });
1397
+ },
1398
+
1399
+ // When an event has just come in that is likely to add or change
1400
+ // something in the input textarea, we poll faster, to ensure that
1401
+ // the change appears on the screen quickly.
1402
+ fastPoll: function() {
1403
+ var missed = false, input = this;
1404
+ input.pollingFast = true;
1405
+ function p() {
1406
+ var changed = input.poll();
1407
+ if (!changed && !missed) {missed = true; input.polling.set(60, p);}
1408
+ else {input.pollingFast = false; input.slowPoll();}
1409
+ }
1410
+ input.polling.set(20, p);
1411
+ },
1412
+
1413
+ // Read input from the textarea, and update the document to match.
1414
+ // When something is selected, it is present in the textarea, and
1415
+ // selected (unless it is huge, in which case a placeholder is
1416
+ // used). When nothing is selected, the cursor sits after previously
1417
+ // seen text (can be empty), which is stored in prevInput (we must
1418
+ // not reset the textarea when typing, because that breaks IME).
1419
+ poll: function() {
1420
+ var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
1421
+ // Since this is called a *lot*, try to bail out as cheaply as
1422
+ // possible when it is clear that nothing happened. hasSelection
1423
+ // will be the case when there is a lot of text in the textarea,
1424
+ // in which case reading its value would be expensive.
1425
+ if (this.contextMenuPending || !cm.state.focused ||
1426
+ (hasSelection(input) && !prevInput && !this.composing) ||
1427
+ cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
1428
+ return false;
1429
+
1430
+ var text = input.value;
1431
+ // If nothing changed, bail.
1432
+ if (text == prevInput && !cm.somethingSelected()) return false;
1433
+ // Work around nonsensical selection resetting in IE9/10, and
1434
+ // inexplicable appearance of private area unicode characters on
1435
+ // some key combos in Mac (#2689).
1436
+ if (ie && ie_version >= 9 && this.hasSelection === text ||
1437
+ mac && /[\uf700-\uf7ff]/.test(text)) {
1438
+ cm.display.input.reset();
1439
+ return false;
1440
+ }
1441
+
1442
+ if (cm.doc.sel == cm.display.selForContextMenu) {
1443
+ var first = text.charCodeAt(0);
1444
+ if (first == 0x200b && !prevInput) prevInput = "\u200b";
1445
+ if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); }
1446
+ }
1447
+ // Find the part of the input that is actually new
1448
+ var same = 0, l = Math.min(prevInput.length, text.length);
1449
+ while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
1450
+
1451
+ var self = this;
1452
+ runInOp(cm, function() {
1453
+ applyTextInput(cm, text.slice(same), prevInput.length - same,
1454
+ null, self.composing ? "*compose" : null);
1455
+
1456
+ // Don't leave long text in the textarea, since it makes further polling slow
1457
+ if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = "";
1458
+ else self.prevInput = text;
1459
+
1460
+ if (self.composing) {
1461
+ self.composing.range.clear();
1462
+ self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"),
1463
+ {className: "CodeMirror-composing"});
1464
+ }
1465
+ });
1466
+ return true;
1467
+ },
1468
+
1469
+ ensurePolled: function() {
1470
+ if (this.pollingFast && this.poll()) this.pollingFast = false;
1471
+ },
1472
+
1473
+ onKeyPress: function() {
1474
+ if (ie && ie_version >= 9) this.hasSelection = null;
1475
+ this.fastPoll();
1476
+ },
1477
+
1478
+ onContextMenu: function(e) {
1479
+ var input = this, cm = input.cm, display = cm.display, te = input.textarea;
1480
+ var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop;
1481
+ if (!pos || presto) return; // Opera is difficult.
1482
+
1483
+ // Reset the current text selection only if the click is done outside of the selection
1484
+ // and 'resetSelectionOnContextMenu' option is true.
1485
+ var reset = cm.options.resetSelectionOnContextMenu;
1486
+ if (reset && cm.doc.sel.contains(pos) == -1)
1487
+ operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);
1488
+
1489
+ var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
1490
+ input.wrapper.style.cssText = "position: absolute"
1491
+ var wrapperBox = input.wrapper.getBoundingClientRect()
1492
+ te.style.cssText = "position: absolute; width: 30px; height: 30px; top: " + (e.clientY - wrapperBox.top - 5) +
1493
+ "px; left: " + (e.clientX - wrapperBox.left - 5) + "px; z-index: 1000; background: " +
1494
+ (ie ? "rgba(255, 255, 255, .05)" : "transparent") +
1495
+ "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
1496
+ if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712)
1497
+ display.input.focus();
1498
+ if (webkit) window.scrollTo(null, oldScrollY);
1499
+ display.input.reset();
1500
+ // Adds "Select all" to context menu in FF
1501
+ if (!cm.somethingSelected()) te.value = input.prevInput = " ";
1502
+ input.contextMenuPending = true;
1503
+ display.selForContextMenu = cm.doc.sel;
1504
+ clearTimeout(display.detectingSelectAll);
1505
+
1506
+ // Select-all will be greyed out if there's nothing to select, so
1507
+ // this adds a zero-width space so that we can later check whether
1508
+ // it got selected.
1509
+ function prepareSelectAllHack() {
1510
+ if (te.selectionStart != null) {
1511
+ var selected = cm.somethingSelected();
1512
+ var extval = "\u200b" + (selected ? te.value : "");
1513
+ te.value = "\u21da"; // Used to catch context-menu undo
1514
+ te.value = extval;
1515
+ input.prevInput = selected ? "" : "\u200b";
1516
+ te.selectionStart = 1; te.selectionEnd = extval.length;
1517
+ // Re-set this, in case some other handler touched the
1518
+ // selection in the meantime.
1519
+ display.selForContextMenu = cm.doc.sel;
1520
+ }
1521
+ }
1522
+ function rehide() {
1523
+ input.contextMenuPending = false;
1524
+ input.wrapper.style.cssText = oldWrapperCSS
1525
+ te.style.cssText = oldCSS;
1526
+ if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos);
1527
+
1528
+ // Try to detect the user choosing select-all
1529
+ if (te.selectionStart != null) {
1530
+ if (!ie || (ie && ie_version < 9)) prepareSelectAllHack();
1531
+ var i = 0, poll = function() {
1532
+ if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
1533
+ te.selectionEnd > 0 && input.prevInput == "\u200b")
1534
+ operation(cm, commands.selectAll)(cm);
1535
+ else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500);
1536
+ else display.input.reset();
1537
+ };
1538
+ display.detectingSelectAll = setTimeout(poll, 200);
1539
+ }
1540
+ }
1541
+
1542
+ if (ie && ie_version >= 9) prepareSelectAllHack();
1543
+ if (captureRightClick) {
1544
+ e_stop(e);
1545
+ var mouseup = function() {
1546
+ off(window, "mouseup", mouseup);
1547
+ setTimeout(rehide, 20);
1548
+ };
1549
+ on(window, "mouseup", mouseup);
1550
+ } else {
1551
+ setTimeout(rehide, 50);
1552
+ }
1553
+ },
1554
+
1555
+ readOnlyChanged: function(val) {
1556
+ if (!val) this.reset();
1557
+ },
1558
+
1559
+ setUneditable: nothing,
1560
+
1561
+ needsContentAttribute: false
1562
+ }, TextareaInput.prototype);
1563
+
1564
+ // CONTENTEDITABLE INPUT STYLE
1565
+
1566
+ function ContentEditableInput(cm) {
1567
+ this.cm = cm;
1568
+ this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
1569
+ this.polling = new Delayed();
1570
+ this.gracePeriod = false;
1571
+ }
1572
+
1573
+ ContentEditableInput.prototype = copyObj({
1574
+ init: function(display) {
1575
+ var input = this, cm = input.cm;
1576
+ var div = input.div = display.lineDiv;
1577
+ disableBrowserMagic(div);
1578
+
1579
+ on(div, "paste", function(e) {
1580
+ if (!signalDOMEvent(cm, e)) handlePaste(e, cm);
1581
+ })
1582
+
1583
+ on(div, "compositionstart", function(e) {
1584
+ var data = e.data;
1585
+ input.composing = {sel: cm.doc.sel, data: data, startData: data};
1586
+ if (!data) return;
1587
+ var prim = cm.doc.sel.primary();
1588
+ var line = cm.getLine(prim.head.line);
1589
+ var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length));
1590
+ if (found > -1 && found <= prim.head.ch)
1591
+ input.composing.sel = simpleSelection(Pos(prim.head.line, found),
1592
+ Pos(prim.head.line, found + data.length));
1593
+ });
1594
+ on(div, "compositionupdate", function(e) {
1595
+ input.composing.data = e.data;
1596
+ });
1597
+ on(div, "compositionend", function(e) {
1598
+ var ours = input.composing;
1599
+ if (!ours) return;
1600
+ if (e.data != ours.startData && !/\u200b/.test(e.data))
1601
+ ours.data = e.data;
1602
+ // Need a small delay to prevent other code (input event,
1603
+ // selection polling) from doing damage when fired right after
1604
+ // compositionend.
1605
+ setTimeout(function() {
1606
+ if (!ours.handled)
1607
+ input.applyComposition(ours);
1608
+ if (input.composing == ours)
1609
+ input.composing = null;
1610
+ }, 50);
1611
+ });
1612
+
1613
+ on(div, "touchstart", function() {
1614
+ input.forceCompositionEnd();
1615
+ });
1616
+
1617
+ on(div, "input", function() {
1618
+ if (input.composing) return;
1619
+ if (cm.isReadOnly() || !input.pollContent())
1620
+ runInOp(input.cm, function() {regChange(cm);});
1621
+ });
1622
+
1623
+ function onCopyCut(e) {
1624
+ if (signalDOMEvent(cm, e)) return
1625
+ if (cm.somethingSelected()) {
1626
+ lastCopied = {lineWise: false, text: cm.getSelections()};
1627
+ if (e.type == "cut") cm.replaceSelection("", null, "cut");
1628
+ } else if (!cm.options.lineWiseCopyCut) {
1629
+ return;
1630
+ } else {
1631
+ var ranges = copyableRanges(cm);
1632
+ lastCopied = {lineWise: true, text: ranges.text};
1633
+ if (e.type == "cut") {
1634
+ cm.operation(function() {
1635
+ cm.setSelections(ranges.ranges, 0, sel_dontScroll);
1636
+ cm.replaceSelection("", null, "cut");
1637
+ });
1638
+ }
1639
+ }
1640
+ // iOS exposes the clipboard API, but seems to discard content inserted into it
1641
+ if (e.clipboardData && !ios) {
1642
+ e.preventDefault();
1643
+ e.clipboardData.clearData();
1644
+ e.clipboardData.setData("text/plain", lastCopied.text.join("\n"));
1645
+ } else {
1646
+ // Old-fashioned briefly-focus-a-textarea hack
1647
+ var kludge = hiddenTextarea(), te = kludge.firstChild;
1648
+ cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
1649
+ te.value = lastCopied.text.join("\n");
1650
+ var hadFocus = document.activeElement;
1651
+ selectInput(te);
1652
+ setTimeout(function() {
1653
+ cm.display.lineSpace.removeChild(kludge);
1654
+ hadFocus.focus();
1655
+ }, 50);
1656
+ }
1657
+ }
1658
+ on(div, "copy", onCopyCut);
1659
+ on(div, "cut", onCopyCut);
1660
+ },
1661
+
1662
+ prepareSelection: function() {
1663
+ var result = prepareSelection(this.cm, false);
1664
+ result.focus = this.cm.state.focused;
1665
+ return result;
1666
+ },
1667
+
1668
+ showSelection: function(info, takeFocus) {
1669
+ if (!info || !this.cm.display.view.length) return;
1670
+ if (info.focus || takeFocus) this.showPrimarySelection();
1671
+ this.showMultipleSelections(info);
1672
+ },
1673
+
1674
+ showPrimarySelection: function() {
1675
+ var sel = window.getSelection(), prim = this.cm.doc.sel.primary();
1676
+ var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset);
1677
+ var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset);
1678
+ if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
1679
+ cmp(minPos(curAnchor, curFocus), prim.from()) == 0 &&
1680
+ cmp(maxPos(curAnchor, curFocus), prim.to()) == 0)
1681
+ return;
1682
+
1683
+ var start = posToDOM(this.cm, prim.from());
1684
+ var end = posToDOM(this.cm, prim.to());
1685
+ if (!start && !end) return;
1686
+
1687
+ var view = this.cm.display.view;
1688
+ var old = sel.rangeCount && sel.getRangeAt(0);
1689
+ if (!start) {
1690
+ start = {node: view[0].measure.map[2], offset: 0};
1691
+ } else if (!end) { // FIXME dangerously hacky
1692
+ var measure = view[view.length - 1].measure;
1693
+ var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
1694
+ end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
1695
+ }
1696
+
1697
+ try { var rng = range(start.node, start.offset, end.offset, end.node); }
1698
+ catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
1699
+ if (rng) {
1700
+ if (!gecko && this.cm.state.focused) {
1701
+ sel.collapse(start.node, start.offset);
1702
+ if (!rng.collapsed) sel.addRange(rng);
1703
+ } else {
1704
+ sel.removeAllRanges();
1705
+ sel.addRange(rng);
1706
+ }
1707
+ if (old && sel.anchorNode == null) sel.addRange(old);
1708
+ else if (gecko) this.startGracePeriod();
1709
+ }
1710
+ this.rememberSelection();
1711
+ },
1712
+
1713
+ startGracePeriod: function() {
1714
+ var input = this;
1715
+ clearTimeout(this.gracePeriod);
1716
+ this.gracePeriod = setTimeout(function() {
1717
+ input.gracePeriod = false;
1718
+ if (input.selectionChanged())
1719
+ input.cm.operation(function() { input.cm.curOp.selectionChanged = true; });
1720
+ }, 20);
1721
+ },
1722
+
1723
+ showMultipleSelections: function(info) {
1724
+ removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
1725
+ removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
1726
+ },
1727
+
1728
+ rememberSelection: function() {
1729
+ var sel = window.getSelection();
1730
+ this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
1731
+ this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
1732
+ },
1733
+
1734
+ selectionInEditor: function() {
1735
+ var sel = window.getSelection();
1736
+ if (!sel.rangeCount) return false;
1737
+ var node = sel.getRangeAt(0).commonAncestorContainer;
1738
+ return contains(this.div, node);
1739
+ },
1740
+
1741
+ focus: function() {
1742
+ if (this.cm.options.readOnly != "nocursor") this.div.focus();
1743
+ },
1744
+ blur: function() { this.div.blur(); },
1745
+ getField: function() { return this.div; },
1746
+
1747
+ supportsTouch: function() { return true; },
1748
+
1749
+ receivedFocus: function() {
1750
+ var input = this;
1751
+ if (this.selectionInEditor())
1752
+ this.pollSelection();
1753
+ else
1754
+ runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; });
1755
+
1756
+ function poll() {
1757
+ if (input.cm.state.focused) {
1758
+ input.pollSelection();
1759
+ input.polling.set(input.cm.options.pollInterval, poll);
1760
+ }
1761
+ }
1762
+ this.polling.set(this.cm.options.pollInterval, poll);
1763
+ },
1764
+
1765
+ selectionChanged: function() {
1766
+ var sel = window.getSelection();
1767
+ return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
1768
+ sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset;
1769
+ },
1770
+
1771
+ pollSelection: function() {
1772
+ if (!this.composing && !this.gracePeriod && this.selectionChanged()) {
1773
+ var sel = window.getSelection(), cm = this.cm;
1774
+ this.rememberSelection();
1775
+ var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
1776
+ var head = domToPos(cm, sel.focusNode, sel.focusOffset);
1777
+ if (anchor && head) runInOp(cm, function() {
1778
+ setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
1779
+ if (anchor.bad || head.bad) cm.curOp.selectionChanged = true;
1780
+ });
1781
+ }
1782
+ },
1783
+
1784
+ pollContent: function() {
1785
+ var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
1786
+ var from = sel.from(), to = sel.to();
1787
+ if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false;
1788
+
1789
+ var fromIndex;
1790
+ if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
1791
+ var fromLine = lineNo(display.view[0].line);
1792
+ var fromNode = display.view[0].node;
1793
+ } else {
1794
+ var fromLine = lineNo(display.view[fromIndex].line);
1795
+ var fromNode = display.view[fromIndex - 1].node.nextSibling;
1796
+ }
1797
+ var toIndex = findViewIndex(cm, to.line);
1798
+ if (toIndex == display.view.length - 1) {
1799
+ var toLine = display.viewTo - 1;
1800
+ var toNode = display.lineDiv.lastChild;
1801
+ } else {
1802
+ var toLine = lineNo(display.view[toIndex + 1].line) - 1;
1803
+ var toNode = display.view[toIndex + 1].node.previousSibling;
1804
+ }
1805
+
1806
+ var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
1807
+ var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
1808
+ while (newText.length > 1 && oldText.length > 1) {
1809
+ if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
1810
+ else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
1811
+ else break;
1812
+ }
1813
+
1814
+ var cutFront = 0, cutEnd = 0;
1815
+ var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
1816
+ while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
1817
+ ++cutFront;
1818
+ var newBot = lst(newText), oldBot = lst(oldText);
1819
+ var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
1820
+ oldBot.length - (oldText.length == 1 ? cutFront : 0));
1821
+ while (cutEnd < maxCutEnd &&
1822
+ newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
1823
+ ++cutEnd;
1824
+
1825
+ newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd);
1826
+ newText[0] = newText[0].slice(cutFront);
1827
+
1828
+ var chFrom = Pos(fromLine, cutFront);
1829
+ var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
1830
+ if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
1831
+ replaceRange(cm.doc, newText, chFrom, chTo, "+input");
1832
+ return true;
1833
+ }
1834
+ },
1835
+
1836
+ ensurePolled: function() {
1837
+ this.forceCompositionEnd();
1838
+ },
1839
+ reset: function() {
1840
+ this.forceCompositionEnd();
1841
+ },
1842
+ forceCompositionEnd: function() {
1843
+ if (!this.composing || this.composing.handled) return;
1844
+ this.applyComposition(this.composing);
1845
+ this.composing.handled = true;
1846
+ this.div.blur();
1847
+ this.div.focus();
1848
+ },
1849
+ applyComposition: function(composing) {
1850
+ if (this.cm.isReadOnly())
1851
+ operation(this.cm, regChange)(this.cm)
1852
+ else if (composing.data && composing.data != composing.startData)
1853
+ operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel);
1854
+ },
1855
+
1856
+ setUneditable: function(node) {
1857
+ node.contentEditable = "false"
1858
+ },
1859
+
1860
+ onKeyPress: function(e) {
1861
+ e.preventDefault();
1862
+ if (!this.cm.isReadOnly())
1863
+ operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0);
1864
+ },
1865
+
1866
+ readOnlyChanged: function(val) {
1867
+ this.div.contentEditable = String(val != "nocursor")
1868
+ },
1869
+
1870
+ onContextMenu: nothing,
1871
+ resetPosition: nothing,
1872
+
1873
+ needsContentAttribute: true
1874
+ }, ContentEditableInput.prototype);
1875
+
1876
+ function posToDOM(cm, pos) {
1877
+ var view = findViewForLine(cm, pos.line);
1878
+ if (!view || view.hidden) return null;
1879
+ var line = getLine(cm.doc, pos.line);
1880
+ var info = mapFromLineView(view, line, pos.line);
1881
+
1882
+ var order = getOrder(line), side = "left";
1883
+ if (order) {
1884
+ var partPos = getBidiPartAt(order, pos.ch);
1885
+ side = partPos % 2 ? "right" : "left";
1886
+ }
1887
+ var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
1888
+ result.offset = result.collapse == "right" ? result.end : result.start;
1889
+ return result;
1890
+ }
1891
+
1892
+ function badPos(pos, bad) { if (bad) pos.bad = true; return pos; }
1893
+
1894
+ function domToPos(cm, node, offset) {
1895
+ var lineNode;
1896
+ if (node == cm.display.lineDiv) {
1897
+ lineNode = cm.display.lineDiv.childNodes[offset];
1898
+ if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true);
1899
+ node = null; offset = 0;
1900
+ } else {
1901
+ for (lineNode = node;; lineNode = lineNode.parentNode) {
1902
+ if (!lineNode || lineNode == cm.display.lineDiv) return null;
1903
+ if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break;
1904
+ }
1905
+ }
1906
+ for (var i = 0; i < cm.display.view.length; i++) {
1907
+ var lineView = cm.display.view[i];
1908
+ if (lineView.node == lineNode)
1909
+ return locateNodeInLineView(lineView, node, offset);
1910
+ }
1911
+ }
1912
+
1913
+ function locateNodeInLineView(lineView, node, offset) {
1914
+ var wrapper = lineView.text.firstChild, bad = false;
1915
+ if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true);
1916
+ if (node == wrapper) {
1917
+ bad = true;
1918
+ node = wrapper.childNodes[offset];
1919
+ offset = 0;
1920
+ if (!node) {
1921
+ var line = lineView.rest ? lst(lineView.rest) : lineView.line;
1922
+ return badPos(Pos(lineNo(line), line.text.length), bad);
1923
+ }
1924
+ }
1925
+
1926
+ var textNode = node.nodeType == 3 ? node : null, topNode = node;
1927
+ if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
1928
+ textNode = node.firstChild;
1929
+ if (offset) offset = textNode.nodeValue.length;
1930
+ }
1931
+ while (topNode.parentNode != wrapper) topNode = topNode.parentNode;
1932
+ var measure = lineView.measure, maps = measure.maps;
1933
+
1934
+ function find(textNode, topNode, offset) {
1935
+ for (var i = -1; i < (maps ? maps.length : 0); i++) {
1936
+ var map = i < 0 ? measure.map : maps[i];
1937
+ for (var j = 0; j < map.length; j += 3) {
1938
+ var curNode = map[j + 2];
1939
+ if (curNode == textNode || curNode == topNode) {
1940
+ var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
1941
+ var ch = map[j] + offset;
1942
+ if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)];
1943
+ return Pos(line, ch);
1944
+ }
1945
+ }
1946
+ }
1947
+ }
1948
+ var found = find(textNode, topNode, offset);
1949
+ if (found) return badPos(found, bad);
1950
+
1951
+ // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
1952
+ for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
1953
+ found = find(after, after.firstChild, 0);
1954
+ if (found)
1955
+ return badPos(Pos(found.line, found.ch - dist), bad);
1956
+ else
1957
+ dist += after.textContent.length;
1958
+ }
1959
+ for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) {
1960
+ found = find(before, before.firstChild, -1);
1961
+ if (found)
1962
+ return badPos(Pos(found.line, found.ch + dist), bad);
1963
+ else
1964
+ dist += after.textContent.length;
1965
+ }
1966
+ }
1967
+
1968
+ function domTextBetween(cm, from, to, fromLine, toLine) {
1969
+ var text = "", closing = false, lineSep = cm.doc.lineSeparator();
1970
+ function recognizeMarker(id) { return function(marker) { return marker.id == id; }; }
1971
+ function walk(node) {
1972
+ if (node.nodeType == 1) {
1973
+ var cmText = node.getAttribute("cm-text");
1974
+ if (cmText != null) {
1975
+ if (cmText == "") cmText = node.textContent.replace(/\u200b/g, "");
1976
+ text += cmText;
1977
+ return;
1978
+ }
1979
+ var markerID = node.getAttribute("cm-marker"), range;
1980
+ if (markerID) {
1981
+ var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
1982
+ if (found.length && (range = found[0].find()))
1983
+ text += getBetween(cm.doc, range.from, range.to).join(lineSep);
1984
+ return;
1985
+ }
1986
+ if (node.getAttribute("contenteditable") == "false") return;
1987
+ for (var i = 0; i < node.childNodes.length; i++)
1988
+ walk(node.childNodes[i]);
1989
+ if (/^(pre|div|p)$/i.test(node.nodeName))
1990
+ closing = true;
1991
+ } else if (node.nodeType == 3) {
1992
+ var val = node.nodeValue;
1993
+ if (!val) return;
1994
+ if (closing) {
1995
+ text += lineSep;
1996
+ closing = false;
1997
+ }
1998
+ text += val;
1999
+ }
2000
+ }
2001
+ for (;;) {
2002
+ walk(from);
2003
+ if (from == to) break;
2004
+ from = from.nextSibling;
2005
+ }
2006
+ return text;
2007
+ }
2008
+
2009
+ CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
2010
+
2011
+ // SELECTION / CURSOR
2012
+
2013
+ // Selection objects are immutable. A new one is created every time
2014
+ // the selection changes. A selection is one or more non-overlapping
2015
+ // (and non-touching) ranges, sorted, and an integer that indicates
2016
+ // which one is the primary selection (the one that's scrolled into
2017
+ // view, that getCursor returns, etc).
2018
+ function Selection(ranges, primIndex) {
2019
+ this.ranges = ranges;
2020
+ this.primIndex = primIndex;
2021
+ }
2022
+
2023
+ Selection.prototype = {
2024
+ primary: function() { return this.ranges[this.primIndex]; },
2025
+ equals: function(other) {
2026
+ if (other == this) return true;
2027
+ if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false;
2028
+ for (var i = 0; i < this.ranges.length; i++) {
2029
+ var here = this.ranges[i], there = other.ranges[i];
2030
+ if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false;
2031
+ }
2032
+ return true;
2033
+ },
2034
+ deepCopy: function() {
2035
+ for (var out = [], i = 0; i < this.ranges.length; i++)
2036
+ out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));
2037
+ return new Selection(out, this.primIndex);
2038
+ },
2039
+ somethingSelected: function() {
2040
+ for (var i = 0; i < this.ranges.length; i++)
2041
+ if (!this.ranges[i].empty()) return true;
2042
+ return false;
2043
+ },
2044
+ contains: function(pos, end) {
2045
+ if (!end) end = pos;
2046
+ for (var i = 0; i < this.ranges.length; i++) {
2047
+ var range = this.ranges[i];
2048
+ if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0)
2049
+ return i;
2050
+ }
2051
+ return -1;
2052
+ }
2053
+ };
2054
+
2055
+ function Range(anchor, head) {
2056
+ this.anchor = anchor; this.head = head;
2057
+ }
2058
+
2059
+ Range.prototype = {
2060
+ from: function() { return minPos(this.anchor, this.head); },
2061
+ to: function() { return maxPos(this.anchor, this.head); },
2062
+ empty: function() {
2063
+ return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch;
2064
+ }
2065
+ };
2066
+
2067
+ // Take an unsorted, potentially overlapping set of ranges, and
2068
+ // build a selection out of it. 'Consumes' ranges array (modifying
2069
+ // it).
2070
+ function normalizeSelection(ranges, primIndex) {
2071
+ var prim = ranges[primIndex];
2072
+ ranges.sort(function(a, b) { return cmp(a.from(), b.from()); });
2073
+ primIndex = indexOf(ranges, prim);
2074
+ for (var i = 1; i < ranges.length; i++) {
2075
+ var cur = ranges[i], prev = ranges[i - 1];
2076
+ if (cmp(prev.to(), cur.from()) >= 0) {
2077
+ var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to());
2078
+ var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head;
2079
+ if (i <= primIndex) --primIndex;
2080
+ ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to));
2081
+ }
2082
+ }
2083
+ return new Selection(ranges, primIndex);
2084
+ }
2085
+
2086
+ function simpleSelection(anchor, head) {
2087
+ return new Selection([new Range(anchor, head || anchor)], 0);
2088
+ }
2089
+
2090
+ // Most of the external API clips given positions to make sure they
2091
+ // actually exist within the document.
2092
+ function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));}
2093
+ function clipPos(doc, pos) {
2094
+ if (pos.line < doc.first) return Pos(doc.first, 0);
2095
+ var last = doc.first + doc.size - 1;
2096
+ if (pos.line > last) return Pos(last, getLine(doc, last).text.length);
2097
+ return clipToLen(pos, getLine(doc, pos.line).text.length);
2098
+ }
2099
+ function clipToLen(pos, linelen) {
2100
+ var ch = pos.ch;
2101
+ if (ch == null || ch > linelen) return Pos(pos.line, linelen);
2102
+ else if (ch < 0) return Pos(pos.line, 0);
2103
+ else return pos;
2104
+ }
2105
+ function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;}
2106
+ function clipPosArray(doc, array) {
2107
+ for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]);
2108
+ return out;
2109
+ }
2110
+
2111
+ // SELECTION UPDATES
2112
+
2113
+ // The 'scroll' parameter given to many of these indicated whether
2114
+ // the new cursor position should be scrolled into view after
2115
+ // modifying the selection.
2116
+
2117
+ // If shift is held or the extend flag is set, extends a range to
2118
+ // include a given position (and optionally a second position).
2119
+ // Otherwise, simply returns the range between the given positions.
2120
+ // Used for cursor motion and such.
2121
+ function extendRange(doc, range, head, other) {
2122
+ if (doc.cm && doc.cm.display.shift || doc.extend) {
2123
+ var anchor = range.anchor;
2124
+ if (other) {
2125
+ var posBefore = cmp(head, anchor) < 0;
2126
+ if (posBefore != (cmp(other, anchor) < 0)) {
2127
+ anchor = head;
2128
+ head = other;
2129
+ } else if (posBefore != (cmp(head, other) < 0)) {
2130
+ head = other;
2131
+ }
2132
+ }
2133
+ return new Range(anchor, head);
2134
+ } else {
2135
+ return new Range(other || head, head);
2136
+ }
2137
+ }
2138
+
2139
+ // Extend the primary selection range, discard the rest.
2140
+ function extendSelection(doc, head, other, options) {
2141
+ setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options);
2142
+ }
2143
+
2144
+ // Extend all selections (pos is an array of selections with length
2145
+ // equal the number of selections)
2146
+ function extendSelections(doc, heads, options) {
2147
+ for (var out = [], i = 0; i < doc.sel.ranges.length; i++)
2148
+ out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);
2149
+ var newSel = normalizeSelection(out, doc.sel.primIndex);
2150
+ setSelection(doc, newSel, options);
2151
+ }
2152
+
2153
+ // Updates a single range in the selection.
2154
+ function replaceOneSelection(doc, i, range, options) {
2155
+ var ranges = doc.sel.ranges.slice(0);
2156
+ ranges[i] = range;
2157
+ setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options);
2158
+ }
2159
+
2160
+ // Reset the selection to a single range.
2161
+ function setSimpleSelection(doc, anchor, head, options) {
2162
+ setSelection(doc, simpleSelection(anchor, head), options);
2163
+ }
2164
+
2165
+ // Give beforeSelectionChange handlers a change to influence a
2166
+ // selection update.
2167
+ function filterSelectionChange(doc, sel, options) {
2168
+ var obj = {
2169
+ ranges: sel.ranges,
2170
+ update: function(ranges) {
2171
+ this.ranges = [];
2172
+ for (var i = 0; i < ranges.length; i++)
2173
+ this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor),
2174
+ clipPos(doc, ranges[i].head));
2175
+ },
2176
+ origin: options && options.origin
2177
+ };
2178
+ signal(doc, "beforeSelectionChange", doc, obj);
2179
+ if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj);
2180
+ if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1);
2181
+ else return sel;
2182
+ }
2183
+
2184
+ function setSelectionReplaceHistory(doc, sel, options) {
2185
+ var done = doc.history.done, last = lst(done);
2186
+ if (last && last.ranges) {
2187
+ done[done.length - 1] = sel;
2188
+ setSelectionNoUndo(doc, sel, options);
2189
+ } else {
2190
+ setSelection(doc, sel, options);
2191
+ }
2192
+ }
2193
+
2194
+ // Set a new selection.
2195
+ function setSelection(doc, sel, options) {
2196
+ setSelectionNoUndo(doc, sel, options);
2197
+ addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options);
2198
+ }
2199
+
2200
+ function setSelectionNoUndo(doc, sel, options) {
2201
+ if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange"))
2202
+ sel = filterSelectionChange(doc, sel, options);
2203
+
2204
+ var bias = options && options.bias ||
2205
+ (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1);
2206
+ setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true));
2207
+
2208
+ if (!(options && options.scroll === false) && doc.cm)
2209
+ ensureCursorVisible(doc.cm);
2210
+ }
2211
+
2212
+ function setSelectionInner(doc, sel) {
2213
+ if (sel.equals(doc.sel)) return;
2214
+
2215
+ doc.sel = sel;
2216
+
2217
+ if (doc.cm) {
2218
+ doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true;
2219
+ signalCursorActivity(doc.cm);
2220
+ }
2221
+ signalLater(doc, "cursorActivity", doc);
2222
+ }
2223
+
2224
+ // Verify that the selection does not partially select any atomic
2225
+ // marked ranges.
2226
+ function reCheckSelection(doc) {
2227
+ setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll);
2228
+ }
2229
+
2230
+ // Return a selection that does not partially select any atomic
2231
+ // ranges.
2232
+ function skipAtomicInSelection(doc, sel, bias, mayClear) {
2233
+ var out;
2234
+ for (var i = 0; i < sel.ranges.length; i++) {
2235
+ var range = sel.ranges[i];
2236
+ var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
2237
+ var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
2238
+ var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear);
2239
+ if (out || newAnchor != range.anchor || newHead != range.head) {
2240
+ if (!out) out = sel.ranges.slice(0, i);
2241
+ out[i] = new Range(newAnchor, newHead);
2242
+ }
2243
+ }
2244
+ return out ? normalizeSelection(out, sel.primIndex) : sel;
2245
+ }
2246
+
2247
+ function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
2248
+ var line = getLine(doc, pos.line);
2249
+ if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
2250
+ var sp = line.markedSpans[i], m = sp.marker;
2251
+ if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
2252
+ (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
2253
+ if (mayClear) {
2254
+ signal(m, "beforeCursorEnter");
2255
+ if (m.explicitlyCleared) {
2256
+ if (!line.markedSpans) break;
2257
+ else {--i; continue;}
2258
+ }
2259
+ }
2260
+ if (!m.atomic) continue;
2261
+
2262
+ if (oldPos) {
2263
+ var near = m.find(dir < 0 ? 1 : -1), diff;
2264
+ if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft)
2265
+ near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null);
2266
+ if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
2267
+ return skipAtomicInner(doc, near, pos, dir, mayClear);
2268
+ }
2269
+
2270
+ var far = m.find(dir < 0 ? -1 : 1);
2271
+ if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight)
2272
+ far = movePos(doc, far, dir, far.line == pos.line ? line : null);
2273
+ return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null;
2274
+ }
2275
+ }
2276
+ return pos;
2277
+ }
2278
+
2279
+ // Ensure a given position is not inside an atomic range.
2280
+ function skipAtomic(doc, pos, oldPos, bias, mayClear) {
2281
+ var dir = bias || 1;
2282
+ var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
2283
+ (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
2284
+ skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
2285
+ (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
2286
+ if (!found) {
2287
+ doc.cantEdit = true;
2288
+ return Pos(doc.first, 0);
2289
+ }
2290
+ return found;
2291
+ }
2292
+
2293
+ function movePos(doc, pos, dir, line) {
2294
+ if (dir < 0 && pos.ch == 0) {
2295
+ if (pos.line > doc.first) return clipPos(doc, Pos(pos.line - 1));
2296
+ else return null;
2297
+ } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
2298
+ if (pos.line < doc.first + doc.size - 1) return Pos(pos.line + 1, 0);
2299
+ else return null;
2300
+ } else {
2301
+ return new Pos(pos.line, pos.ch + dir);
2302
+ }
2303
+ }
2304
+
2305
+ // SELECTION DRAWING
2306
+
2307
+ function updateSelection(cm) {
2308
+ cm.display.input.showSelection(cm.display.input.prepareSelection());
2309
+ }
2310
+
2311
+ function prepareSelection(cm, primary) {
2312
+ var doc = cm.doc, result = {};
2313
+ var curFragment = result.cursors = document.createDocumentFragment();
2314
+ var selFragment = result.selection = document.createDocumentFragment();
2315
+
2316
+ for (var i = 0; i < doc.sel.ranges.length; i++) {
2317
+ if (primary === false && i == doc.sel.primIndex) continue;
2318
+ var range = doc.sel.ranges[i];
2319
+ if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) continue;
2320
+ var collapsed = range.empty();
2321
+ if (collapsed || cm.options.showCursorWhenSelecting)
2322
+ drawSelectionCursor(cm, range.head, curFragment);
2323
+ if (!collapsed)
2324
+ drawSelectionRange(cm, range, selFragment);
2325
+ }
2326
+ return result;
2327
+ }
2328
+
2329
+ // Draws a cursor for the given range
2330
+ function drawSelectionCursor(cm, head, output) {
2331
+ var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
2332
+
2333
+ var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor"));
2334
+ cursor.style.left = pos.left + "px";
2335
+ cursor.style.top = pos.top + "px";
2336
+ cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px";
2337
+
2338
+ if (pos.other) {
2339
+ // Secondary cursor, shown when on a 'jump' in bi-directional text
2340
+ var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor"));
2341
+ otherCursor.style.display = "";
2342
+ otherCursor.style.left = pos.other.left + "px";
2343
+ otherCursor.style.top = pos.other.top + "px";
2344
+ otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px";
2345
+ }
2346
+ }
2347
+
2348
+ // Draws the given range as a highlighted selection
2349
+ function drawSelectionRange(cm, range, output) {
2350
+ var display = cm.display, doc = cm.doc;
2351
+ var fragment = document.createDocumentFragment();
2352
+ var padding = paddingH(cm.display), leftSide = padding.left;
2353
+ var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
2354
+
2355
+ function add(left, top, width, bottom) {
2356
+ if (top < 0) top = 0;
2357
+ top = Math.round(top);
2358
+ bottom = Math.round(bottom);
2359
+ fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left +
2360
+ "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) +
2361
+ "px; height: " + (bottom - top) + "px"));
2362
+ }
2363
+
2364
+ function drawForLine(line, fromArg, toArg) {
2365
+ var lineObj = getLine(doc, line);
2366
+ var lineLen = lineObj.text.length;
2367
+ var start, end;
2368
+ function coords(ch, bias) {
2369
+ return charCoords(cm, Pos(line, ch), "div", lineObj, bias);
2370
+ }
2371
+
2372
+ iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) {
2373
+ var leftPos = coords(from, "left"), rightPos, left, right;
2374
+ if (from == to) {
2375
+ rightPos = leftPos;
2376
+ left = right = leftPos.left;
2377
+ } else {
2378
+ rightPos = coords(to - 1, "right");
2379
+ if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; }
2380
+ left = leftPos.left;
2381
+ right = rightPos.right;
2382
+ }
2383
+ if (fromArg == null && from == 0) left = leftSide;
2384
+ if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part
2385
+ add(left, leftPos.top, null, leftPos.bottom);
2386
+ left = leftSide;
2387
+ if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top);
2388
+ }
2389
+ if (toArg == null && to == lineLen) right = rightSide;
2390
+ if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left)
2391
+ start = leftPos;
2392
+ if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right)
2393
+ end = rightPos;
2394
+ if (left < leftSide + 1) left = leftSide;
2395
+ add(left, rightPos.top, right - left, rightPos.bottom);
2396
+ });
2397
+ return {start: start, end: end};
2398
+ }
2399
+
2400
+ var sFrom = range.from(), sTo = range.to();
2401
+ if (sFrom.line == sTo.line) {
2402
+ drawForLine(sFrom.line, sFrom.ch, sTo.ch);
2403
+ } else {
2404
+ var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);
2405
+ var singleVLine = visualLine(fromLine) == visualLine(toLine);
2406
+ var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;
2407
+ var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;
2408
+ if (singleVLine) {
2409
+ if (leftEnd.top < rightStart.top - 2) {
2410
+ add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);
2411
+ add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);
2412
+ } else {
2413
+ add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);
2414
+ }
2415
+ }
2416
+ if (leftEnd.bottom < rightStart.top)
2417
+ add(leftSide, leftEnd.bottom, null, rightStart.top);
2418
+ }
2419
+
2420
+ output.appendChild(fragment);
2421
+ }
2422
+
2423
+ // Cursor-blinking
2424
+ function restartBlink(cm) {
2425
+ if (!cm.state.focused) return;
2426
+ var display = cm.display;
2427
+ clearInterval(display.blinker);
2428
+ var on = true;
2429
+ display.cursorDiv.style.visibility = "";
2430
+ if (cm.options.cursorBlinkRate > 0)
2431
+ display.blinker = setInterval(function() {
2432
+ display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
2433
+ }, cm.options.cursorBlinkRate);
2434
+ else if (cm.options.cursorBlinkRate < 0)
2435
+ display.cursorDiv.style.visibility = "hidden";
2436
+ }
2437
+
2438
+ // HIGHLIGHT WORKER
2439
+
2440
+ function startWorker(cm, time) {
2441
+ if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo)
2442
+ cm.state.highlight.set(time, bind(highlightWorker, cm));
2443
+ }
2444
+
2445
+ function highlightWorker(cm) {
2446
+ var doc = cm.doc;
2447
+ if (doc.frontier < doc.first) doc.frontier = doc.first;
2448
+ if (doc.frontier >= cm.display.viewTo) return;
2449
+ var end = +new Date + cm.options.workTime;
2450
+ var state = copyState(doc.mode, getStateBefore(cm, doc.frontier));
2451
+ var changedLines = [];
2452
+
2453
+ doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) {
2454
+ if (doc.frontier >= cm.display.viewFrom) { // Visible
2455
+ var oldStyles = line.styles, tooLong = line.text.length > cm.options.maxHighlightLength;
2456
+ var highlighted = highlightLine(cm, line, tooLong ? copyState(doc.mode, state) : state, true);
2457
+ line.styles = highlighted.styles;
2458
+ var oldCls = line.styleClasses, newCls = highlighted.classes;
2459
+ if (newCls) line.styleClasses = newCls;
2460
+ else if (oldCls) line.styleClasses = null;
2461
+ var ischange = !oldStyles || oldStyles.length != line.styles.length ||
2462
+ oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
2463
+ for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i];
2464
+ if (ischange) changedLines.push(doc.frontier);
2465
+ line.stateAfter = tooLong ? state : copyState(doc.mode, state);
2466
+ } else {
2467
+ if (line.text.length <= cm.options.maxHighlightLength)
2468
+ processLine(cm, line.text, state);
2469
+ line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null;
2470
+ }
2471
+ ++doc.frontier;
2472
+ if (+new Date > end) {
2473
+ startWorker(cm, cm.options.workDelay);
2474
+ return true;
2475
+ }
2476
+ });
2477
+ if (changedLines.length) runInOp(cm, function() {
2478
+ for (var i = 0; i < changedLines.length; i++)
2479
+ regLineChange(cm, changedLines[i], "text");
2480
+ });
2481
+ }
2482
+
2483
+ // Finds the line to start with when starting a parse. Tries to
2484
+ // find a line with a stateAfter, so that it can start with a
2485
+ // valid state. If that fails, it returns the line with the
2486
+ // smallest indentation, which tends to need the least context to
2487
+ // parse correctly.
2488
+ function findStartLine(cm, n, precise) {
2489
+ var minindent, minline, doc = cm.doc;
2490
+ var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100);
2491
+ for (var search = n; search > lim; --search) {
2492
+ if (search <= doc.first) return doc.first;
2493
+ var line = getLine(doc, search - 1);
2494
+ if (line.stateAfter && (!precise || search <= doc.frontier)) return search;
2495
+ var indented = countColumn(line.text, null, cm.options.tabSize);
2496
+ if (minline == null || minindent > indented) {
2497
+ minline = search - 1;
2498
+ minindent = indented;
2499
+ }
2500
+ }
2501
+ return minline;
2502
+ }
2503
+
2504
+ function getStateBefore(cm, n, precise) {
2505
+ var doc = cm.doc, display = cm.display;
2506
+ if (!doc.mode.startState) return true;
2507
+ var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter;
2508
+ if (!state) state = startState(doc.mode);
2509
+ else state = copyState(doc.mode, state);
2510
+ doc.iter(pos, n, function(line) {
2511
+ processLine(cm, line.text, state);
2512
+ var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo;
2513
+ line.stateAfter = save ? copyState(doc.mode, state) : null;
2514
+ ++pos;
2515
+ });
2516
+ if (precise) doc.frontier = pos;
2517
+ return state;
2518
+ }
2519
+
2520
+ // POSITION MEASUREMENT
2521
+
2522
+ function paddingTop(display) {return display.lineSpace.offsetTop;}
2523
+ function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;}
2524
+ function paddingH(display) {
2525
+ if (display.cachedPaddingH) return display.cachedPaddingH;
2526
+ var e = removeChildrenAndAdd(display.measure, elt("pre", "x"));
2527
+ var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
2528
+ var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
2529
+ if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data;
2530
+ return data;
2531
+ }
2532
+
2533
+ function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; }
2534
+ function displayWidth(cm) {
2535
+ return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth;
2536
+ }
2537
+ function displayHeight(cm) {
2538
+ return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight;
2539
+ }
2540
+
2541
+ // Ensure the lineView.wrapping.heights array is populated. This is
2542
+ // an array of bottom offsets for the lines that make up a drawn
2543
+ // line. When lineWrapping is on, there might be more than one
2544
+ // height.
2545
+ function ensureLineHeights(cm, lineView, rect) {
2546
+ var wrapping = cm.options.lineWrapping;
2547
+ var curWidth = wrapping && displayWidth(cm);
2548
+ if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) {
2549
+ var heights = lineView.measure.heights = [];
2550
+ if (wrapping) {
2551
+ lineView.measure.width = curWidth;
2552
+ var rects = lineView.text.firstChild.getClientRects();
2553
+ for (var i = 0; i < rects.length - 1; i++) {
2554
+ var cur = rects[i], next = rects[i + 1];
2555
+ if (Math.abs(cur.bottom - next.bottom) > 2)
2556
+ heights.push((cur.bottom + next.top) / 2 - rect.top);
2557
+ }
2558
+ }
2559
+ heights.push(rect.bottom - rect.top);
2560
+ }
2561
+ }
2562
+
2563
+ // Find a line map (mapping character offsets to text nodes) and a
2564
+ // measurement cache for the given line number. (A line view might
2565
+ // contain multiple lines when collapsed ranges are present.)
2566
+ function mapFromLineView(lineView, line, lineN) {
2567
+ if (lineView.line == line)
2568
+ return {map: lineView.measure.map, cache: lineView.measure.cache};
2569
+ for (var i = 0; i < lineView.rest.length; i++)
2570
+ if (lineView.rest[i] == line)
2571
+ return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};
2572
+ for (var i = 0; i < lineView.rest.length; i++)
2573
+ if (lineNo(lineView.rest[i]) > lineN)
2574
+ return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};
2575
+ }
2576
+
2577
+ // Render a line into the hidden node display.externalMeasured. Used
2578
+ // when measurement is needed for a line that's not in the viewport.
2579
+ function updateExternalMeasurement(cm, line) {
2580
+ line = visualLine(line);
2581
+ var lineN = lineNo(line);
2582
+ var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN);
2583
+ view.lineN = lineN;
2584
+ var built = view.built = buildLineContent(cm, view);
2585
+ view.text = built.pre;
2586
+ removeChildrenAndAdd(cm.display.lineMeasure, built.pre);
2587
+ return view;
2588
+ }
2589
+
2590
+ // Get a {top, bottom, left, right} box (in line-local coordinates)
2591
+ // for a given character.
2592
+ function measureChar(cm, line, ch, bias) {
2593
+ return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias);
2594
+ }
2595
+
2596
+ // Find a line view that corresponds to the given line number.
2597
+ function findViewForLine(cm, lineN) {
2598
+ if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo)
2599
+ return cm.display.view[findViewIndex(cm, lineN)];
2600
+ var ext = cm.display.externalMeasured;
2601
+ if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size)
2602
+ return ext;
2603
+ }
2604
+
2605
+ // Measurement can be split in two steps, the set-up work that
2606
+ // applies to the whole line, and the measurement of the actual
2607
+ // character. Functions like coordsChar, that need to do a lot of
2608
+ // measurements in a row, can thus ensure that the set-up work is
2609
+ // only done once.
2610
+ function prepareMeasureForLine(cm, line) {
2611
+ var lineN = lineNo(line);
2612
+ var view = findViewForLine(cm, lineN);
2613
+ if (view && !view.text) {
2614
+ view = null;
2615
+ } else if (view && view.changes) {
2616
+ updateLineForChanges(cm, view, lineN, getDimensions(cm));
2617
+ cm.curOp.forceUpdate = true;
2618
+ }
2619
+ if (!view)
2620
+ view = updateExternalMeasurement(cm, line);
2621
+
2622
+ var info = mapFromLineView(view, line, lineN);
2623
+ return {
2624
+ line: line, view: view, rect: null,
2625
+ map: info.map, cache: info.cache, before: info.before,
2626
+ hasHeights: false
2627
+ };
2628
+ }
2629
+
2630
+ // Given a prepared measurement object, measures the position of an
2631
+ // actual character (or fetches it from the cache).
2632
+ function measureCharPrepared(cm, prepared, ch, bias, varHeight) {
2633
+ if (prepared.before) ch = -1;
2634
+ var key = ch + (bias || ""), found;
2635
+ if (prepared.cache.hasOwnProperty(key)) {
2636
+ found = prepared.cache[key];
2637
+ } else {
2638
+ if (!prepared.rect)
2639
+ prepared.rect = prepared.view.text.getBoundingClientRect();
2640
+ if (!prepared.hasHeights) {
2641
+ ensureLineHeights(cm, prepared.view, prepared.rect);
2642
+ prepared.hasHeights = true;
2643
+ }
2644
+ found = measureCharInner(cm, prepared, ch, bias);
2645
+ if (!found.bogus) prepared.cache[key] = found;
2646
+ }
2647
+ return {left: found.left, right: found.right,
2648
+ top: varHeight ? found.rtop : found.top,
2649
+ bottom: varHeight ? found.rbottom : found.bottom};
2650
+ }
2651
+
2652
+ var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
2653
+
2654
+ function nodeAndOffsetInLineMap(map, ch, bias) {
2655
+ var node, start, end, collapse;
2656
+ // First, search the line map for the text node corresponding to,
2657
+ // or closest to, the target character.
2658
+ for (var i = 0; i < map.length; i += 3) {
2659
+ var mStart = map[i], mEnd = map[i + 1];
2660
+ if (ch < mStart) {
2661
+ start = 0; end = 1;
2662
+ collapse = "left";
2663
+ } else if (ch < mEnd) {
2664
+ start = ch - mStart;
2665
+ end = start + 1;
2666
+ } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) {
2667
+ end = mEnd - mStart;
2668
+ start = end - 1;
2669
+ if (ch >= mEnd) collapse = "right";
2670
+ }
2671
+ if (start != null) {
2672
+ node = map[i + 2];
2673
+ if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right"))
2674
+ collapse = bias;
2675
+ if (bias == "left" && start == 0)
2676
+ while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) {
2677
+ node = map[(i -= 3) + 2];
2678
+ collapse = "left";
2679
+ }
2680
+ if (bias == "right" && start == mEnd - mStart)
2681
+ while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) {
2682
+ node = map[(i += 3) + 2];
2683
+ collapse = "right";
2684
+ }
2685
+ break;
2686
+ }
2687
+ }
2688
+ return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd};
2689
+ }
2690
+
2691
+ function getUsefulRect(rects, bias) {
2692
+ var rect = nullRect
2693
+ if (bias == "left") for (var i = 0; i < rects.length; i++) {
2694
+ if ((rect = rects[i]).left != rect.right) break
2695
+ } else for (var i = rects.length - 1; i >= 0; i--) {
2696
+ if ((rect = rects[i]).left != rect.right) break
2697
+ }
2698
+ return rect
2699
+ }
2700
+
2701
+ function measureCharInner(cm, prepared, ch, bias) {
2702
+ var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
2703
+ var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
2704
+
2705
+ var rect;
2706
+ if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
2707
+ for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned
2708
+ while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start;
2709
+ while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end;
2710
+ if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
2711
+ rect = node.parentNode.getBoundingClientRect();
2712
+ else
2713
+ rect = getUsefulRect(range(node, start, end).getClientRects(), bias)
2714
+ if (rect.left || rect.right || start == 0) break;
2715
+ end = start;
2716
+ start = start - 1;
2717
+ collapse = "right";
2718
+ }
2719
+ if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect);
2720
+ } else { // If it is a widget, simply get the box for the whole widget.
2721
+ if (start > 0) collapse = bias = "right";
2722
+ var rects;
2723
+ if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1)
2724
+ rect = rects[bias == "right" ? rects.length - 1 : 0];
2725
+ else
2726
+ rect = node.getBoundingClientRect();
2727
+ }
2728
+ if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) {
2729
+ var rSpan = node.parentNode.getClientRects()[0];
2730
+ if (rSpan)
2731
+ rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};
2732
+ else
2733
+ rect = nullRect;
2734
+ }
2735
+
2736
+ var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
2737
+ var mid = (rtop + rbot) / 2;
2738
+ var heights = prepared.view.measure.heights;
2739
+ for (var i = 0; i < heights.length - 1; i++)
2740
+ if (mid < heights[i]) break;
2741
+ var top = i ? heights[i - 1] : 0, bot = heights[i];
2742
+ var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left,
2743
+ right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left,
2744
+ top: top, bottom: bot};
2745
+ if (!rect.left && !rect.right) result.bogus = true;
2746
+ if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
2747
+
2748
+ return result;
2749
+ }
2750
+
2751
+ // Work around problem with bounding client rects on ranges being
2752
+ // returned incorrectly when zoomed on IE10 and below.
2753
+ function maybeUpdateRectForZooming(measure, rect) {
2754
+ if (!window.screen || screen.logicalXDPI == null ||
2755
+ screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
2756
+ return rect;
2757
+ var scaleX = screen.logicalXDPI / screen.deviceXDPI;
2758
+ var scaleY = screen.logicalYDPI / screen.deviceYDPI;
2759
+ return {left: rect.left * scaleX, right: rect.right * scaleX,
2760
+ top: rect.top * scaleY, bottom: rect.bottom * scaleY};
2761
+ }
2762
+
2763
+ function clearLineMeasurementCacheFor(lineView) {
2764
+ if (lineView.measure) {
2765
+ lineView.measure.cache = {};
2766
+ lineView.measure.heights = null;
2767
+ if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++)
2768
+ lineView.measure.caches[i] = {};
2769
+ }
2770
+ }
2771
+
2772
+ function clearLineMeasurementCache(cm) {
2773
+ cm.display.externalMeasure = null;
2774
+ removeChildren(cm.display.lineMeasure);
2775
+ for (var i = 0; i < cm.display.view.length; i++)
2776
+ clearLineMeasurementCacheFor(cm.display.view[i]);
2777
+ }
2778
+
2779
+ function clearCaches(cm) {
2780
+ clearLineMeasurementCache(cm);
2781
+ cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null;
2782
+ if (!cm.options.lineWrapping) cm.display.maxLineChanged = true;
2783
+ cm.display.lineNumChars = null;
2784
+ }
2785
+
2786
+ function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; }
2787
+ function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; }
2788
+
2789
+ // Converts a {top, bottom, left, right} box from line-local
2790
+ // coordinates into another coordinate system. Context may be one of
2791
+ // "line", "div" (display.lineDiv), "local"/null (editor), "window",
2792
+ // or "page".
2793
+ function intoCoordSystem(cm, lineObj, rect, context) {
2794
+ if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) {
2795
+ var size = widgetHeight(lineObj.widgets[i]);
2796
+ rect.top += size; rect.bottom += size;
2797
+ }
2798
+ if (context == "line") return rect;
2799
+ if (!context) context = "local";
2800
+ var yOff = heightAtLine(lineObj);
2801
+ if (context == "local") yOff += paddingTop(cm.display);
2802
+ else yOff -= cm.display.viewOffset;
2803
+ if (context == "page" || context == "window") {
2804
+ var lOff = cm.display.lineSpace.getBoundingClientRect();
2805
+ yOff += lOff.top + (context == "window" ? 0 : pageScrollY());
2806
+ var xOff = lOff.left + (context == "window" ? 0 : pageScrollX());
2807
+ rect.left += xOff; rect.right += xOff;
2808
+ }
2809
+ rect.top += yOff; rect.bottom += yOff;
2810
+ return rect;
2811
+ }
2812
+
2813
+ // Coverts a box from "div" coords to another coordinate system.
2814
+ // Context may be "window", "page", "div", or "local"/null.
2815
+ function fromCoordSystem(cm, coords, context) {
2816
+ if (context == "div") return coords;
2817
+ var left = coords.left, top = coords.top;
2818
+ // First move into "page" coordinate system
2819
+ if (context == "page") {
2820
+ left -= pageScrollX();
2821
+ top -= pageScrollY();
2822
+ } else if (context == "local" || !context) {
2823
+ var localBox = cm.display.sizer.getBoundingClientRect();
2824
+ left += localBox.left;
2825
+ top += localBox.top;
2826
+ }
2827
+
2828
+ var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect();
2829
+ return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top};
2830
+ }
2831
+
2832
+ function charCoords(cm, pos, context, lineObj, bias) {
2833
+ if (!lineObj) lineObj = getLine(cm.doc, pos.line);
2834
+ return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context);
2835
+ }
2836
+
2837
+ // Returns a box for a given cursor position, which may have an
2838
+ // 'other' property containing the position of the secondary cursor
2839
+ // on a bidi boundary.
2840
+ function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
2841
+ lineObj = lineObj || getLine(cm.doc, pos.line);
2842
+ if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj);
2843
+ function get(ch, right) {
2844
+ var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight);
2845
+ if (right) m.left = m.right; else m.right = m.left;
2846
+ return intoCoordSystem(cm, lineObj, m, context);
2847
+ }
2848
+ function getBidi(ch, partPos) {
2849
+ var part = order[partPos], right = part.level % 2;
2850
+ if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) {
2851
+ part = order[--partPos];
2852
+ ch = bidiRight(part) - (part.level % 2 ? 0 : 1);
2853
+ right = true;
2854
+ } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) {
2855
+ part = order[++partPos];
2856
+ ch = bidiLeft(part) - part.level % 2;
2857
+ right = false;
2858
+ }
2859
+ if (right && ch == part.to && ch > part.from) return get(ch - 1);
2860
+ return get(ch, right);
2861
+ }
2862
+ var order = getOrder(lineObj), ch = pos.ch;
2863
+ if (!order) return get(ch);
2864
+ var partPos = getBidiPartAt(order, ch);
2865
+ var val = getBidi(ch, partPos);
2866
+ if (bidiOther != null) val.other = getBidi(ch, bidiOther);
2867
+ return val;
2868
+ }
2869
+
2870
+ // Used to cheaply estimate the coordinates for a position. Used for
2871
+ // intermediate scroll updates.
2872
+ function estimateCoords(cm, pos) {
2873
+ var left = 0, pos = clipPos(cm.doc, pos);
2874
+ if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch;
2875
+ var lineObj = getLine(cm.doc, pos.line);
2876
+ var top = heightAtLine(lineObj) + paddingTop(cm.display);
2877
+ return {left: left, right: left, top: top, bottom: top + lineObj.height};
2878
+ }
2879
+
2880
+ // Positions returned by coordsChar contain some extra information.
2881
+ // xRel is the relative x position of the input coordinates compared
2882
+ // to the found position (so xRel > 0 means the coordinates are to
2883
+ // the right of the character position, for example). When outside
2884
+ // is true, that means the coordinates lie outside the line's
2885
+ // vertical range.
2886
+ function PosWithInfo(line, ch, outside, xRel) {
2887
+ var pos = Pos(line, ch);
2888
+ pos.xRel = xRel;
2889
+ if (outside) pos.outside = true;
2890
+ return pos;
2891
+ }
2892
+
2893
+ // Compute the character position closest to the given coordinates.
2894
+ // Input must be lineSpace-local ("div" coordinate system).
2895
+ function coordsChar(cm, x, y) {
2896
+ var doc = cm.doc;
2897
+ y += cm.display.viewOffset;
2898
+ if (y < 0) return PosWithInfo(doc.first, 0, true, -1);
2899
+ var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;
2900
+ if (lineN > last)
2901
+ return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);
2902
+ if (x < 0) x = 0;
2903
+
2904
+ var lineObj = getLine(doc, lineN);
2905
+ for (;;) {
2906
+ var found = coordsCharInner(cm, lineObj, lineN, x, y);
2907
+ var merged = collapsedSpanAtEnd(lineObj);
2908
+ var mergedPos = merged && merged.find(0, true);
2909
+ if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0))
2910
+ lineN = lineNo(lineObj = mergedPos.to.line);
2911
+ else
2912
+ return found;
2913
+ }
2914
+ }
2915
+
2916
+ function coordsCharInner(cm, lineObj, lineNo, x, y) {
2917
+ var innerOff = y - heightAtLine(lineObj);
2918
+ var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth;
2919
+ var preparedMeasure = prepareMeasureForLine(cm, lineObj);
2920
+
2921
+ function getX(ch) {
2922
+ var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure);
2923
+ wrongLine = true;
2924
+ if (innerOff > sp.bottom) return sp.left - adjust;
2925
+ else if (innerOff < sp.top) return sp.left + adjust;
2926
+ else wrongLine = false;
2927
+ return sp.left;
2928
+ }
2929
+
2930
+ var bidi = getOrder(lineObj), dist = lineObj.text.length;
2931
+ var from = lineLeft(lineObj), to = lineRight(lineObj);
2932
+ var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine;
2933
+
2934
+ if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1);
2935
+ // Do a binary search between these bounds.
2936
+ for (;;) {
2937
+ if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) {
2938
+ var ch = x < fromX || x - fromX <= toX - x ? from : to;
2939
+ var outside = ch == from ? fromOutside : toOutside
2940
+ var xDiff = x - (ch == from ? fromX : toX);
2941
+ // This is a kludge to handle the case where the coordinates
2942
+ // are after a line-wrapped line. We should replace it with a
2943
+ // more general handling of cursor positions around line
2944
+ // breaks. (Issue #4078)
2945
+ if (toOutside && !bidi && !/\s/.test(lineObj.text.charAt(ch)) && xDiff > 0 &&
2946
+ ch < lineObj.text.length && preparedMeasure.view.measure.heights.length > 1) {
2947
+ var charSize = measureCharPrepared(cm, preparedMeasure, ch, "right");
2948
+ if (innerOff <= charSize.bottom && innerOff >= charSize.top && Math.abs(x - charSize.right) < xDiff) {
2949
+ outside = false
2950
+ ch++
2951
+ xDiff = x - charSize.right
2952
+ }
2953
+ }
2954
+ while (isExtendingChar(lineObj.text.charAt(ch))) ++ch;
2955
+ var pos = PosWithInfo(lineNo, ch, outside, xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0);
2956
+ return pos;
2957
+ }
2958
+ var step = Math.ceil(dist / 2), middle = from + step;
2959
+ if (bidi) {
2960
+ middle = from;
2961
+ for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1);
2962
+ }
2963
+ var middleX = getX(middle);
2964
+ if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;}
2965
+ else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;}
2966
+ }
2967
+ }
2968
+
2969
+ var measureText;
2970
+ // Compute the default text height.
2971
+ function textHeight(display) {
2972
+ if (display.cachedTextHeight != null) return display.cachedTextHeight;
2973
+ if (measureText == null) {
2974
+ measureText = elt("pre");
2975
+ // Measure a bunch of lines, for browsers that compute
2976
+ // fractional heights.
2977
+ for (var i = 0; i < 49; ++i) {
2978
+ measureText.appendChild(document.createTextNode("x"));
2979
+ measureText.appendChild(elt("br"));
2980
+ }
2981
+ measureText.appendChild(document.createTextNode("x"));
2982
+ }
2983
+ removeChildrenAndAdd(display.measure, measureText);
2984
+ var height = measureText.offsetHeight / 50;
2985
+ if (height > 3) display.cachedTextHeight = height;
2986
+ removeChildren(display.measure);
2987
+ return height || 1;
2988
+ }
2989
+
2990
+ // Compute the default character width.
2991
+ function charWidth(display) {
2992
+ if (display.cachedCharWidth != null) return display.cachedCharWidth;
2993
+ var anchor = elt("span", "xxxxxxxxxx");
2994
+ var pre = elt("pre", [anchor]);
2995
+ removeChildrenAndAdd(display.measure, pre);
2996
+ var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
2997
+ if (width > 2) display.cachedCharWidth = width;
2998
+ return width || 10;
2999
+ }
3000
+
3001
+ // OPERATIONS
3002
+
3003
+ // Operations are used to wrap a series of changes to the editor
3004
+ // state in such a way that each change won't have to update the
3005
+ // cursor and display (which would be awkward, slow, and
3006
+ // error-prone). Instead, display updates are batched and then all
3007
+ // combined and executed at once.
3008
+
3009
+ var operationGroup = null;
3010
+
3011
+ var nextOpId = 0;
3012
+ // Start a new operation.
3013
+ function startOperation(cm) {
3014
+ cm.curOp = {
3015
+ cm: cm,
3016
+ viewChanged: false, // Flag that indicates that lines might need to be redrawn
3017
+ startHeight: cm.doc.height, // Used to detect need to update scrollbar
3018
+ forceUpdate: false, // Used to force a redraw
3019
+ updateInput: null, // Whether to reset the input textarea
3020
+ typing: false, // Whether this reset should be careful to leave existing text (for compositing)
3021
+ changeObjs: null, // Accumulated changes, for firing change events
3022
+ cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
3023
+ cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
3024
+ selectionChanged: false, // Whether the selection needs to be redrawn
3025
+ updateMaxLine: false, // Set when the widest line needs to be determined anew
3026
+ scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
3027
+ scrollToPos: null, // Used to scroll to a specific position
3028
+ focus: false,
3029
+ id: ++nextOpId // Unique ID
3030
+ };
3031
+ if (operationGroup) {
3032
+ operationGroup.ops.push(cm.curOp);
3033
+ } else {
3034
+ cm.curOp.ownsGroup = operationGroup = {
3035
+ ops: [cm.curOp],
3036
+ delayedCallbacks: []
3037
+ };
3038
+ }
3039
+ }
3040
+
3041
+ function fireCallbacksForOps(group) {
3042
+ // Calls delayed callbacks and cursorActivity handlers until no
3043
+ // new ones appear
3044
+ var callbacks = group.delayedCallbacks, i = 0;
3045
+ do {
3046
+ for (; i < callbacks.length; i++)
3047
+ callbacks[i].call(null);
3048
+ for (var j = 0; j < group.ops.length; j++) {
3049
+ var op = group.ops[j];
3050
+ if (op.cursorActivityHandlers)
3051
+ while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
3052
+ op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm);
3053
+ }
3054
+ } while (i < callbacks.length);
3055
+ }
3056
+
3057
+ // Finish an operation, updating the display and signalling delayed events
3058
+ function endOperation(cm) {
3059
+ var op = cm.curOp, group = op.ownsGroup;
3060
+ if (!group) return;
3061
+
3062
+ try { fireCallbacksForOps(group); }
3063
+ finally {
3064
+ operationGroup = null;
3065
+ for (var i = 0; i < group.ops.length; i++)
3066
+ group.ops[i].cm.curOp = null;
3067
+ endOperations(group);
3068
+ }
3069
+ }
3070
+
3071
+ // The DOM updates done when an operation finishes are batched so
3072
+ // that the minimum number of relayouts are required.
3073
+ function endOperations(group) {
3074
+ var ops = group.ops;
3075
+ for (var i = 0; i < ops.length; i++) // Read DOM
3076
+ endOperation_R1(ops[i]);
3077
+ for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
3078
+ endOperation_W1(ops[i]);
3079
+ for (var i = 0; i < ops.length; i++) // Read DOM
3080
+ endOperation_R2(ops[i]);
3081
+ for (var i = 0; i < ops.length; i++) // Write DOM (maybe)
3082
+ endOperation_W2(ops[i]);
3083
+ for (var i = 0; i < ops.length; i++) // Read DOM
3084
+ endOperation_finish(ops[i]);
3085
+ }
3086
+
3087
+ function endOperation_R1(op) {
3088
+ var cm = op.cm, display = cm.display;
3089
+ maybeClipScrollbars(cm);
3090
+ if (op.updateMaxLine) findMaxLine(cm);
3091
+
3092
+ op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null ||
3093
+ op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom ||
3094
+ op.scrollToPos.to.line >= display.viewTo) ||
3095
+ display.maxLineChanged && cm.options.lineWrapping;
3096
+ op.update = op.mustUpdate &&
3097
+ new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
3098
+ }
3099
+
3100
+ function endOperation_W1(op) {
3101
+ op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
3102
+ }
3103
+
3104
+ function endOperation_R2(op) {
3105
+ var cm = op.cm, display = cm.display;
3106
+ if (op.updatedDisplay) updateHeightsInViewport(cm);
3107
+
3108
+ op.barMeasure = measureForScrollbars(cm);
3109
+
3110
+ // If the max line changed since it was last measured, measure it,
3111
+ // and ensure the document's width matches it.
3112
+ // updateDisplay_W2 will use these properties to do the actual resizing
3113
+ if (display.maxLineChanged && !cm.options.lineWrapping) {
3114
+ op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
3115
+ cm.display.sizerWidth = op.adjustWidthTo;
3116
+ op.barMeasure.scrollWidth =
3117
+ Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
3118
+ op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
3119
+ }
3120
+
3121
+ if (op.updatedDisplay || op.selectionChanged)
3122
+ op.preparedSelection = display.input.prepareSelection(op.focus);
3123
+ }
3124
+
3125
+ function endOperation_W2(op) {
3126
+ var cm = op.cm;
3127
+
3128
+ if (op.adjustWidthTo != null) {
3129
+ cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
3130
+ if (op.maxScrollLeft < cm.doc.scrollLeft)
3131
+ setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);
3132
+ cm.display.maxLineChanged = false;
3133
+ }
3134
+
3135
+ var takeFocus = op.focus && op.focus == activeElt() && (!document.hasFocus || document.hasFocus())
3136
+ if (op.preparedSelection)
3137
+ cm.display.input.showSelection(op.preparedSelection, takeFocus);
3138
+ if (op.updatedDisplay || op.startHeight != cm.doc.height)
3139
+ updateScrollbars(cm, op.barMeasure);
3140
+ if (op.updatedDisplay)
3141
+ setDocumentHeight(cm, op.barMeasure);
3142
+
3143
+ if (op.selectionChanged) restartBlink(cm);
3144
+
3145
+ if (cm.state.focused && op.updateInput)
3146
+ cm.display.input.reset(op.typing);
3147
+ if (takeFocus) ensureFocus(op.cm);
3148
+ }
3149
+
3150
+ function endOperation_finish(op) {
3151
+ var cm = op.cm, display = cm.display, doc = cm.doc;
3152
+
3153
+ if (op.updatedDisplay) postUpdateDisplay(cm, op.update);
3154
+
3155
+ // Abort mouse wheel delta measurement, when scrolling explicitly
3156
+ if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
3157
+ display.wheelStartX = display.wheelStartY = null;
3158
+
3159
+ // Propagate the scroll position to the actual DOM scroller
3160
+ if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) {
3161
+ doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop));
3162
+ display.scrollbars.setScrollTop(doc.scrollTop);
3163
+ display.scroller.scrollTop = doc.scrollTop;
3164
+ }
3165
+ if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) {
3166
+ doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - display.scroller.clientWidth, op.scrollLeft));
3167
+ display.scrollbars.setScrollLeft(doc.scrollLeft);
3168
+ display.scroller.scrollLeft = doc.scrollLeft;
3169
+ alignHorizontally(cm);
3170
+ }
3171
+ // If we need to scroll a specific position into view, do so.
3172
+ if (op.scrollToPos) {
3173
+ var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
3174
+ clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
3175
+ if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords);
3176
+ }
3177
+
3178
+ // Fire events for markers that are hidden/unidden by editing or
3179
+ // undoing
3180
+ var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers;
3181
+ if (hidden) for (var i = 0; i < hidden.length; ++i)
3182
+ if (!hidden[i].lines.length) signal(hidden[i], "hide");
3183
+ if (unhidden) for (var i = 0; i < unhidden.length; ++i)
3184
+ if (unhidden[i].lines.length) signal(unhidden[i], "unhide");
3185
+
3186
+ if (display.wrapper.offsetHeight)
3187
+ doc.scrollTop = cm.display.scroller.scrollTop;
3188
+
3189
+ // Fire change events, and delayed event handlers
3190
+ if (op.changeObjs)
3191
+ signal(cm, "changes", cm, op.changeObjs);
3192
+ if (op.update)
3193
+ op.update.finish();
3194
+ }
3195
+
3196
+ // Run the given function in an operation
3197
+ function runInOp(cm, f) {
3198
+ if (cm.curOp) return f();
3199
+ startOperation(cm);
3200
+ try { return f(); }
3201
+ finally { endOperation(cm); }
3202
+ }
3203
+ // Wraps a function in an operation. Returns the wrapped function.
3204
+ function operation(cm, f) {
3205
+ return function() {
3206
+ if (cm.curOp) return f.apply(cm, arguments);
3207
+ startOperation(cm);
3208
+ try { return f.apply(cm, arguments); }
3209
+ finally { endOperation(cm); }
3210
+ };
3211
+ }
3212
+ // Used to add methods to editor and doc instances, wrapping them in
3213
+ // operations.
3214
+ function methodOp(f) {
3215
+ return function() {
3216
+ if (this.curOp) return f.apply(this, arguments);
3217
+ startOperation(this);
3218
+ try { return f.apply(this, arguments); }
3219
+ finally { endOperation(this); }
3220
+ };
3221
+ }
3222
+ function docMethodOp(f) {
3223
+ return function() {
3224
+ var cm = this.cm;
3225
+ if (!cm || cm.curOp) return f.apply(this, arguments);
3226
+ startOperation(cm);
3227
+ try { return f.apply(this, arguments); }
3228
+ finally { endOperation(cm); }
3229
+ };
3230
+ }
3231
+
3232
+ // VIEW TRACKING
3233
+
3234
+ // These objects are used to represent the visible (currently drawn)
3235
+ // part of the document. A LineView may correspond to multiple
3236
+ // logical lines, if those are connected by collapsed ranges.
3237
+ function LineView(doc, line, lineN) {
3238
+ // The starting line
3239
+ this.line = line;
3240
+ // Continuing lines, if any
3241
+ this.rest = visualLineContinued(line);
3242
+ // Number of logical lines in this visual line
3243
+ this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1;
3244
+ this.node = this.text = null;
3245
+ this.hidden = lineIsHidden(doc, line);
3246
+ }
3247
+
3248
+ // Create a range of LineView objects for the given lines.
3249
+ function buildViewArray(cm, from, to) {
3250
+ var array = [], nextPos;
3251
+ for (var pos = from; pos < to; pos = nextPos) {
3252
+ var view = new LineView(cm.doc, getLine(cm.doc, pos), pos);
3253
+ nextPos = pos + view.size;
3254
+ array.push(view);
3255
+ }
3256
+ return array;
3257
+ }
3258
+
3259
+ // Updates the display.view data structure for a given change to the
3260
+ // document. From and to are in pre-change coordinates. Lendiff is
3261
+ // the amount of lines added or subtracted by the change. This is
3262
+ // used for changes that span multiple lines, or change the way
3263
+ // lines are divided into visual lines. regLineChange (below)
3264
+ // registers single-line changes.
3265
+ function regChange(cm, from, to, lendiff) {
3266
+ if (from == null) from = cm.doc.first;
3267
+ if (to == null) to = cm.doc.first + cm.doc.size;
3268
+ if (!lendiff) lendiff = 0;
3269
+
3270
+ var display = cm.display;
3271
+ if (lendiff && to < display.viewTo &&
3272
+ (display.updateLineNumbers == null || display.updateLineNumbers > from))
3273
+ display.updateLineNumbers = from;
3274
+
3275
+ cm.curOp.viewChanged = true;
3276
+
3277
+ if (from >= display.viewTo) { // Change after
3278
+ if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo)
3279
+ resetView(cm);
3280
+ } else if (to <= display.viewFrom) { // Change before
3281
+ if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) {
3282
+ resetView(cm);
3283
+ } else {
3284
+ display.viewFrom += lendiff;
3285
+ display.viewTo += lendiff;
3286
+ }
3287
+ } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap
3288
+ resetView(cm);
3289
+ } else if (from <= display.viewFrom) { // Top overlap
3290
+ var cut = viewCuttingPoint(cm, to, to + lendiff, 1);
3291
+ if (cut) {
3292
+ display.view = display.view.slice(cut.index);
3293
+ display.viewFrom = cut.lineN;
3294
+ display.viewTo += lendiff;
3295
+ } else {
3296
+ resetView(cm);
3297
+ }
3298
+ } else if (to >= display.viewTo) { // Bottom overlap
3299
+ var cut = viewCuttingPoint(cm, from, from, -1);
3300
+ if (cut) {
3301
+ display.view = display.view.slice(0, cut.index);
3302
+ display.viewTo = cut.lineN;
3303
+ } else {
3304
+ resetView(cm);
3305
+ }
3306
+ } else { // Gap in the middle
3307
+ var cutTop = viewCuttingPoint(cm, from, from, -1);
3308
+ var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1);
3309
+ if (cutTop && cutBot) {
3310
+ display.view = display.view.slice(0, cutTop.index)
3311
+ .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN))
3312
+ .concat(display.view.slice(cutBot.index));
3313
+ display.viewTo += lendiff;
3314
+ } else {
3315
+ resetView(cm);
3316
+ }
3317
+ }
3318
+
3319
+ var ext = display.externalMeasured;
3320
+ if (ext) {
3321
+ if (to < ext.lineN)
3322
+ ext.lineN += lendiff;
3323
+ else if (from < ext.lineN + ext.size)
3324
+ display.externalMeasured = null;
3325
+ }
3326
+ }
3327
+
3328
+ // Register a change to a single line. Type must be one of "text",
3329
+ // "gutter", "class", "widget"
3330
+ function regLineChange(cm, line, type) {
3331
+ cm.curOp.viewChanged = true;
3332
+ var display = cm.display, ext = cm.display.externalMeasured;
3333
+ if (ext && line >= ext.lineN && line < ext.lineN + ext.size)
3334
+ display.externalMeasured = null;
3335
+
3336
+ if (line < display.viewFrom || line >= display.viewTo) return;
3337
+ var lineView = display.view[findViewIndex(cm, line)];
3338
+ if (lineView.node == null) return;
3339
+ var arr = lineView.changes || (lineView.changes = []);
3340
+ if (indexOf(arr, type) == -1) arr.push(type);
3341
+ }
3342
+
3343
+ // Clear the view.
3344
+ function resetView(cm) {
3345
+ cm.display.viewFrom = cm.display.viewTo = cm.doc.first;
3346
+ cm.display.view = [];
3347
+ cm.display.viewOffset = 0;
3348
+ }
3349
+
3350
+ // Find the view element corresponding to a given line. Return null
3351
+ // when the line isn't visible.
3352
+ function findViewIndex(cm, n) {
3353
+ if (n >= cm.display.viewTo) return null;
3354
+ n -= cm.display.viewFrom;
3355
+ if (n < 0) return null;
3356
+ var view = cm.display.view;
3357
+ for (var i = 0; i < view.length; i++) {
3358
+ n -= view[i].size;
3359
+ if (n < 0) return i;
3360
+ }
3361
+ }
3362
+
3363
+ function viewCuttingPoint(cm, oldN, newN, dir) {
3364
+ var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
3365
+ if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
3366
+ return {index: index, lineN: newN};
3367
+ for (var i = 0, n = cm.display.viewFrom; i < index; i++)
3368
+ n += view[i].size;
3369
+ if (n != oldN) {
3370
+ if (dir > 0) {
3371
+ if (index == view.length - 1) return null;
3372
+ diff = (n + view[index].size) - oldN;
3373
+ index++;
3374
+ } else {
3375
+ diff = n - oldN;
3376
+ }
3377
+ oldN += diff; newN += diff;
3378
+ }
3379
+ while (visualLineNo(cm.doc, newN) != newN) {
3380
+ if (index == (dir < 0 ? 0 : view.length - 1)) return null;
3381
+ newN += dir * view[index - (dir < 0 ? 1 : 0)].size;
3382
+ index += dir;
3383
+ }
3384
+ return {index: index, lineN: newN};
3385
+ }
3386
+
3387
+ // Force the view to cover a given range, adding empty view element
3388
+ // or clipping off existing ones as needed.
3389
+ function adjustView(cm, from, to) {
3390
+ var display = cm.display, view = display.view;
3391
+ if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) {
3392
+ display.view = buildViewArray(cm, from, to);
3393
+ display.viewFrom = from;
3394
+ } else {
3395
+ if (display.viewFrom > from)
3396
+ display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);
3397
+ else if (display.viewFrom < from)
3398
+ display.view = display.view.slice(findViewIndex(cm, from));
3399
+ display.viewFrom = from;
3400
+ if (display.viewTo < to)
3401
+ display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));
3402
+ else if (display.viewTo > to)
3403
+ display.view = display.view.slice(0, findViewIndex(cm, to));
3404
+ }
3405
+ display.viewTo = to;
3406
+ }
3407
+
3408
+ // Count the number of lines in the view whose DOM representation is
3409
+ // out of date (or nonexistent).
3410
+ function countDirtyView(cm) {
3411
+ var view = cm.display.view, dirty = 0;
3412
+ for (var i = 0; i < view.length; i++) {
3413
+ var lineView = view[i];
3414
+ if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty;
3415
+ }
3416
+ return dirty;
3417
+ }
3418
+
3419
+ // EVENT HANDLERS
3420
+
3421
+ // Attach the necessary event handlers when initializing the editor
3422
+ function registerEventHandlers(cm) {
3423
+ var d = cm.display;
3424
+ on(d.scroller, "mousedown", operation(cm, onMouseDown));
3425
+ // Older IE's will not fire a second mousedown for a double click
3426
+ if (ie && ie_version < 11)
3427
+ on(d.scroller, "dblclick", operation(cm, function(e) {
3428
+ if (signalDOMEvent(cm, e)) return;
3429
+ var pos = posFromMouse(cm, e);
3430
+ if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return;
3431
+ e_preventDefault(e);
3432
+ var word = cm.findWordAt(pos);
3433
+ extendSelection(cm.doc, word.anchor, word.head);
3434
+ }));
3435
+ else
3436
+ on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); });
3437
+ // Some browsers fire contextmenu *after* opening the menu, at
3438
+ // which point we can't mess with it anymore. Context menu is
3439
+ // handled in onMouseDown for these browsers.
3440
+ if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);});
3441
+
3442
+ // Used to suppress mouse event handling when a touch happens
3443
+ var touchFinished, prevTouch = {end: 0};
3444
+ function finishTouch() {
3445
+ if (d.activeTouch) {
3446
+ touchFinished = setTimeout(function() {d.activeTouch = null;}, 1000);
3447
+ prevTouch = d.activeTouch;
3448
+ prevTouch.end = +new Date;
3449
+ }
3450
+ };
3451
+ function isMouseLikeTouchEvent(e) {
3452
+ if (e.touches.length != 1) return false;
3453
+ var touch = e.touches[0];
3454
+ return touch.radiusX <= 1 && touch.radiusY <= 1;
3455
+ }
3456
+ function farAway(touch, other) {
3457
+ if (other.left == null) return true;
3458
+ var dx = other.left - touch.left, dy = other.top - touch.top;
3459
+ return dx * dx + dy * dy > 20 * 20;
3460
+ }
3461
+ on(d.scroller, "touchstart", function(e) {
3462
+ if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e)) {
3463
+ clearTimeout(touchFinished);
3464
+ var now = +new Date;
3465
+ d.activeTouch = {start: now, moved: false,
3466
+ prev: now - prevTouch.end <= 300 ? prevTouch : null};
3467
+ if (e.touches.length == 1) {
3468
+ d.activeTouch.left = e.touches[0].pageX;
3469
+ d.activeTouch.top = e.touches[0].pageY;
3470
+ }
3471
+ }
3472
+ });
3473
+ on(d.scroller, "touchmove", function() {
3474
+ if (d.activeTouch) d.activeTouch.moved = true;
3475
+ });
3476
+ on(d.scroller, "touchend", function(e) {
3477
+ var touch = d.activeTouch;
3478
+ if (touch && !eventInWidget(d, e) && touch.left != null &&
3479
+ !touch.moved && new Date - touch.start < 300) {
3480
+ var pos = cm.coordsChar(d.activeTouch, "page"), range;
3481
+ if (!touch.prev || farAway(touch, touch.prev)) // Single tap
3482
+ range = new Range(pos, pos);
3483
+ else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
3484
+ range = cm.findWordAt(pos);
3485
+ else // Triple tap
3486
+ range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));
3487
+ cm.setSelection(range.anchor, range.head);
3488
+ cm.focus();
3489
+ e_preventDefault(e);
3490
+ }
3491
+ finishTouch();
3492
+ });
3493
+ on(d.scroller, "touchcancel", finishTouch);
3494
+
3495
+ // Sync scrolling between fake scrollbars and real scrollable
3496
+ // area, ensure viewport is updated when scrolling.
3497
+ on(d.scroller, "scroll", function() {
3498
+ if (d.scroller.clientHeight) {
3499
+ setScrollTop(cm, d.scroller.scrollTop);
3500
+ setScrollLeft(cm, d.scroller.scrollLeft, true);
3501
+ signal(cm, "scroll", cm);
3502
+ }
3503
+ });
3504
+
3505
+ // Listen to wheel events in order to try and update the viewport on time.
3506
+ on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);});
3507
+ on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);});
3508
+
3509
+ // Prevent wrapper from ever scrolling
3510
+ on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
3511
+
3512
+ d.dragFunctions = {
3513
+ enter: function(e) {if (!signalDOMEvent(cm, e)) e_stop(e);},
3514
+ over: function(e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
3515
+ start: function(e){onDragStart(cm, e);},
3516
+ drop: operation(cm, onDrop),
3517
+ leave: function(e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
3518
+ };
3519
+
3520
+ var inp = d.input.getField();
3521
+ on(inp, "keyup", function(e) { onKeyUp.call(cm, e); });
3522
+ on(inp, "keydown", operation(cm, onKeyDown));
3523
+ on(inp, "keypress", operation(cm, onKeyPress));
3524
+ on(inp, "focus", bind(onFocus, cm));
3525
+ on(inp, "blur", bind(onBlur, cm));
3526
+ }
3527
+
3528
+ function dragDropChanged(cm, value, old) {
3529
+ var wasOn = old && old != CodeMirror.Init;
3530
+ if (!value != !wasOn) {
3531
+ var funcs = cm.display.dragFunctions;
3532
+ var toggle = value ? on : off;
3533
+ toggle(cm.display.scroller, "dragstart", funcs.start);
3534
+ toggle(cm.display.scroller, "dragenter", funcs.enter);
3535
+ toggle(cm.display.scroller, "dragover", funcs.over);
3536
+ toggle(cm.display.scroller, "dragleave", funcs.leave);
3537
+ toggle(cm.display.scroller, "drop", funcs.drop);
3538
+ }
3539
+ }
3540
+
3541
+ // Called when the window resizes
3542
+ function onResize(cm) {
3543
+ var d = cm.display;
3544
+ if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth)
3545
+ return;
3546
+ // Might be a text scaling operation, clear size caches.
3547
+ d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
3548
+ d.scrollbarsClipped = false;
3549
+ cm.setSize();
3550
+ }
3551
+
3552
+ // MOUSE EVENTS
3553
+
3554
+ // Return true when the given mouse event happened in a widget
3555
+ function eventInWidget(display, e) {
3556
+ for (var n = e_target(e); n != display.wrapper; n = n.parentNode) {
3557
+ if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
3558
+ (n.parentNode == display.sizer && n != display.mover))
3559
+ return true;
3560
+ }
3561
+ }
3562
+
3563
+ // Given a mouse event, find the corresponding position. If liberal
3564
+ // is false, it checks whether a gutter or scrollbar was clicked,
3565
+ // and returns null if it was. forRect is used by rectangular
3566
+ // selections, and tries to estimate a character position even for
3567
+ // coordinates beyond the right of the text.
3568
+ function posFromMouse(cm, e, liberal, forRect) {
3569
+ var display = cm.display;
3570
+ if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null;
3571
+
3572
+ var x, y, space = display.lineSpace.getBoundingClientRect();
3573
+ // Fails unpredictably on IE[67] when mouse is dragged around quickly.
3574
+ try { x = e.clientX - space.left; y = e.clientY - space.top; }
3575
+ catch (e) { return null; }
3576
+ var coords = coordsChar(cm, x, y), line;
3577
+ if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) {
3578
+ var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length;
3579
+ coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
3580
+ }
3581
+ return coords;
3582
+ }
3583
+
3584
+ // A mouse down can be a single click, double click, triple click,
3585
+ // start of selection drag, start of text drag, new cursor
3586
+ // (ctrl-click), rectangle drag (alt-drag), or xwin
3587
+ // middle-click-paste. Or it might be a click on something we should
3588
+ // not interfere with, such as a scrollbar or widget.
3589
+ function onMouseDown(e) {
3590
+ var cm = this, display = cm.display;
3591
+ if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) return;
3592
+ display.shift = e.shiftKey;
3593
+
3594
+ if (eventInWidget(display, e)) {
3595
+ if (!webkit) {
3596
+ // Briefly turn off draggability, to allow widgets to do
3597
+ // normal dragging things.
3598
+ display.scroller.draggable = false;
3599
+ setTimeout(function(){display.scroller.draggable = true;}, 100);
3600
+ }
3601
+ return;
3602
+ }
3603
+ if (clickInGutter(cm, e)) return;
3604
+ var start = posFromMouse(cm, e);
3605
+ window.focus();
3606
+
3607
+ switch (e_button(e)) {
3608
+ case 1:
3609
+ // #3261: make sure, that we're not starting a second selection
3610
+ if (cm.state.selectingText)
3611
+ cm.state.selectingText(e);
3612
+ else if (start)
3613
+ leftButtonDown(cm, e, start);
3614
+ else if (e_target(e) == display.scroller)
3615
+ e_preventDefault(e);
3616
+ break;
3617
+ case 2:
3618
+ if (webkit) cm.state.lastMiddleDown = +new Date;
3619
+ if (start) extendSelection(cm.doc, start);
3620
+ setTimeout(function() {display.input.focus();}, 20);
3621
+ e_preventDefault(e);
3622
+ break;
3623
+ case 3:
3624
+ if (captureRightClick) onContextMenu(cm, e);
3625
+ else delayBlurEvent(cm);
3626
+ break;
3627
+ }
3628
+ }
3629
+
3630
+ var lastClick, lastDoubleClick;
3631
+ function leftButtonDown(cm, e, start) {
3632
+ if (ie) setTimeout(bind(ensureFocus, cm), 0);
3633
+ else cm.curOp.focus = activeElt();
3634
+
3635
+ var now = +new Date, type;
3636
+ if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
3637
+ type = "triple";
3638
+ } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) {
3639
+ type = "double";
3640
+ lastDoubleClick = {time: now, pos: start};
3641
+ } else {
3642
+ type = "single";
3643
+ lastClick = {time: now, pos: start};
3644
+ }
3645
+
3646
+ var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained;
3647
+ if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
3648
+ type == "single" && (contained = sel.contains(start)) > -1 &&
3649
+ (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) &&
3650
+ (cmp(contained.to(), start) > 0 || start.xRel < 0))
3651
+ leftButtonStartDrag(cm, e, start, modifier);
3652
+ else
3653
+ leftButtonSelect(cm, e, start, type, modifier);
3654
+ }
3655
+
3656
+ // Start a text drag. When it ends, see if any dragging actually
3657
+ // happen, and treat as a click if it didn't.
3658
+ function leftButtonStartDrag(cm, e, start, modifier) {
3659
+ var display = cm.display, startTime = +new Date;
3660
+ var dragEnd = operation(cm, function(e2) {
3661
+ if (webkit) display.scroller.draggable = false;
3662
+ cm.state.draggingText = false;
3663
+ off(document, "mouseup", dragEnd);
3664
+ off(display.scroller, "drop", dragEnd);
3665
+ if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
3666
+ e_preventDefault(e2);
3667
+ if (!modifier && +new Date - 200 < startTime)
3668
+ extendSelection(cm.doc, start);
3669
+ // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
3670
+ if (webkit || ie && ie_version == 9)
3671
+ setTimeout(function() {document.body.focus(); display.input.focus();}, 20);
3672
+ else
3673
+ display.input.focus();
3674
+ }
3675
+ });
3676
+ // Let the drag handler handle this.
3677
+ if (webkit) display.scroller.draggable = true;
3678
+ cm.state.draggingText = dragEnd;
3679
+ dragEnd.copy = mac ? e.altKey : e.ctrlKey
3680
+ // IE's approach to draggable
3681
+ if (display.scroller.dragDrop) display.scroller.dragDrop();
3682
+ on(document, "mouseup", dragEnd);
3683
+ on(display.scroller, "drop", dragEnd);
3684
+ }
3685
+
3686
+ // Normal selection, as opposed to text dragging.
3687
+ function leftButtonSelect(cm, e, start, type, addNew) {
3688
+ var display = cm.display, doc = cm.doc;
3689
+ e_preventDefault(e);
3690
+
3691
+ var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
3692
+ if (addNew && !e.shiftKey) {
3693
+ ourIndex = doc.sel.contains(start);
3694
+ if (ourIndex > -1)
3695
+ ourRange = ranges[ourIndex];
3696
+ else
3697
+ ourRange = new Range(start, start);
3698
+ } else {
3699
+ ourRange = doc.sel.primary();
3700
+ ourIndex = doc.sel.primIndex;
3701
+ }
3702
+
3703
+ if (chromeOS ? e.shiftKey && e.metaKey : e.altKey) {
3704
+ type = "rect";
3705
+ if (!addNew) ourRange = new Range(start, start);
3706
+ start = posFromMouse(cm, e, true, true);
3707
+ ourIndex = -1;
3708
+ } else if (type == "double") {
3709
+ var word = cm.findWordAt(start);
3710
+ if (cm.display.shift || doc.extend)
3711
+ ourRange = extendRange(doc, ourRange, word.anchor, word.head);
3712
+ else
3713
+ ourRange = word;
3714
+ } else if (type == "triple") {
3715
+ var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0)));
3716
+ if (cm.display.shift || doc.extend)
3717
+ ourRange = extendRange(doc, ourRange, line.anchor, line.head);
3718
+ else
3719
+ ourRange = line;
3720
+ } else {
3721
+ ourRange = extendRange(doc, ourRange, start);
3722
+ }
3723
+
3724
+ if (!addNew) {
3725
+ ourIndex = 0;
3726
+ setSelection(doc, new Selection([ourRange], 0), sel_mouse);
3727
+ startSel = doc.sel;
3728
+ } else if (ourIndex == -1) {
3729
+ ourIndex = ranges.length;
3730
+ setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
3731
+ {scroll: false, origin: "*mouse"});
3732
+ } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) {
3733
+ setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
3734
+ {scroll: false, origin: "*mouse"});
3735
+ startSel = doc.sel;
3736
+ } else {
3737
+ replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
3738
+ }
3739
+
3740
+ var lastPos = start;
3741
+ function extendTo(pos) {
3742
+ if (cmp(lastPos, pos) == 0) return;
3743
+ lastPos = pos;
3744
+
3745
+ if (type == "rect") {
3746
+ var ranges = [], tabSize = cm.options.tabSize;
3747
+ var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize);
3748
+ var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize);
3749
+ var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol);
3750
+ for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line));
3751
+ line <= end; line++) {
3752
+ var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize);
3753
+ if (left == right)
3754
+ ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));
3755
+ else if (text.length > leftPos)
3756
+ ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));
3757
+ }
3758
+ if (!ranges.length) ranges.push(new Range(start, start));
3759
+ setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
3760
+ {origin: "*mouse", scroll: false});
3761
+ cm.scrollIntoView(pos);
3762
+ } else {
3763
+ var oldRange = ourRange;
3764
+ var anchor = oldRange.anchor, head = pos;
3765
+ if (type != "single") {
3766
+ if (type == "double")
3767
+ var range = cm.findWordAt(pos);
3768
+ else
3769
+ var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));
3770
+ if (cmp(range.anchor, anchor) > 0) {
3771
+ head = range.head;
3772
+ anchor = minPos(oldRange.from(), range.anchor);
3773
+ } else {
3774
+ head = range.anchor;
3775
+ anchor = maxPos(oldRange.to(), range.head);
3776
+ }
3777
+ }
3778
+ var ranges = startSel.ranges.slice(0);
3779
+ ranges[ourIndex] = new Range(clipPos(doc, anchor), head);
3780
+ setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse);
3781
+ }
3782
+ }
3783
+
3784
+ var editorSize = display.wrapper.getBoundingClientRect();
3785
+ // Used to ensure timeout re-tries don't fire when another extend
3786
+ // happened in the meantime (clearTimeout isn't reliable -- at
3787
+ // least on Chrome, the timeouts still happen even when cleared,
3788
+ // if the clear happens after their scheduled firing time).
3789
+ var counter = 0;
3790
+
3791
+ function extend(e) {
3792
+ var curCount = ++counter;
3793
+ var cur = posFromMouse(cm, e, true, type == "rect");
3794
+ if (!cur) return;
3795
+ if (cmp(cur, lastPos) != 0) {
3796
+ cm.curOp.focus = activeElt();
3797
+ extendTo(cur);
3798
+ var visible = visibleLines(display, doc);
3799
+ if (cur.line >= visible.to || cur.line < visible.from)
3800
+ setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150);
3801
+ } else {
3802
+ var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0;
3803
+ if (outside) setTimeout(operation(cm, function() {
3804
+ if (counter != curCount) return;
3805
+ display.scroller.scrollTop += outside;
3806
+ extend(e);
3807
+ }), 50);
3808
+ }
3809
+ }
3810
+
3811
+ function done(e) {
3812
+ cm.state.selectingText = false;
3813
+ counter = Infinity;
3814
+ e_preventDefault(e);
3815
+ display.input.focus();
3816
+ off(document, "mousemove", move);
3817
+ off(document, "mouseup", up);
3818
+ doc.history.lastSelOrigin = null;
3819
+ }
3820
+
3821
+ var move = operation(cm, function(e) {
3822
+ if (!e_button(e)) done(e);
3823
+ else extend(e);
3824
+ });
3825
+ var up = operation(cm, done);
3826
+ cm.state.selectingText = up;
3827
+ on(document, "mousemove", move);
3828
+ on(document, "mouseup", up);
3829
+ }
3830
+
3831
+ // Determines whether an event happened in the gutter, and fires the
3832
+ // handlers for the corresponding event.
3833
+ function gutterEvent(cm, e, type, prevent) {
3834
+ try { var mX = e.clientX, mY = e.clientY; }
3835
+ catch(e) { return false; }
3836
+ if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false;
3837
+ if (prevent) e_preventDefault(e);
3838
+
3839
+ var display = cm.display;
3840
+ var lineBox = display.lineDiv.getBoundingClientRect();
3841
+
3842
+ if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e);
3843
+ mY -= lineBox.top - display.viewOffset;
3844
+
3845
+ for (var i = 0; i < cm.options.gutters.length; ++i) {
3846
+ var g = display.gutters.childNodes[i];
3847
+ if (g && g.getBoundingClientRect().right >= mX) {
3848
+ var line = lineAtHeight(cm.doc, mY);
3849
+ var gutter = cm.options.gutters[i];
3850
+ signal(cm, type, cm, line, gutter, e);
3851
+ return e_defaultPrevented(e);
3852
+ }
3853
+ }
3854
+ }
3855
+
3856
+ function clickInGutter(cm, e) {
3857
+ return gutterEvent(cm, e, "gutterClick", true);
3858
+ }
3859
+
3860
+ // Kludge to work around strange IE behavior where it'll sometimes
3861
+ // re-fire a series of drag-related events right after the drop (#1551)
3862
+ var lastDrop = 0;
3863
+
3864
+ function onDrop(e) {
3865
+ var cm = this;
3866
+ clearDragCursor(cm);
3867
+ if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
3868
+ return;
3869
+ e_preventDefault(e);
3870
+ if (ie) lastDrop = +new Date;
3871
+ var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
3872
+ if (!pos || cm.isReadOnly()) return;
3873
+ // Might be a file drop, in which case we simply extract the text
3874
+ // and insert it.
3875
+ if (files && files.length && window.FileReader && window.File) {
3876
+ var n = files.length, text = Array(n), read = 0;
3877
+ var loadFile = function(file, i) {
3878
+ if (cm.options.allowDropFileTypes &&
3879
+ indexOf(cm.options.allowDropFileTypes, file.type) == -1)
3880
+ return;
3881
+
3882
+ var reader = new FileReader;
3883
+ reader.onload = operation(cm, function() {
3884
+ var content = reader.result;
3885
+ if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) content = "";
3886
+ text[i] = content;
3887
+ if (++read == n) {
3888
+ pos = clipPos(cm.doc, pos);
3889
+ var change = {from: pos, to: pos,
3890
+ text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())),
3891
+ origin: "paste"};
3892
+ makeChange(cm.doc, change);
3893
+ setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change)));
3894
+ }
3895
+ });
3896
+ reader.readAsText(file);
3897
+ };
3898
+ for (var i = 0; i < n; ++i) loadFile(files[i], i);
3899
+ } else { // Normal drop
3900
+ // Don't do a replace if the drop happened inside of the selected text.
3901
+ if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) {
3902
+ cm.state.draggingText(e);
3903
+ // Ensure the editor is re-focused
3904
+ setTimeout(function() {cm.display.input.focus();}, 20);
3905
+ return;
3906
+ }
3907
+ try {
3908
+ var text = e.dataTransfer.getData("Text");
3909
+ if (text) {
3910
+ if (cm.state.draggingText && !cm.state.draggingText.copy)
3911
+ var selected = cm.listSelections();
3912
+ setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
3913
+ if (selected) for (var i = 0; i < selected.length; ++i)
3914
+ replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");
3915
+ cm.replaceSelection(text, "around", "paste");
3916
+ cm.display.input.focus();
3917
+ }
3918
+ }
3919
+ catch(e){}
3920
+ }
3921
+ }
3922
+
3923
+ function onDragStart(cm, e) {
3924
+ if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; }
3925
+ if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return;
3926
+
3927
+ e.dataTransfer.setData("Text", cm.getSelection());
3928
+ e.dataTransfer.effectAllowed = "copyMove"
3929
+
3930
+ // Use dummy image instead of default browsers image.
3931
+ // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there.
3932
+ if (e.dataTransfer.setDragImage && !safari) {
3933
+ var img = elt("img", null, null, "position: fixed; left: 0; top: 0;");
3934
+ img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
3935
+ if (presto) {
3936
+ img.width = img.height = 1;
3937
+ cm.display.wrapper.appendChild(img);
3938
+ // Force a relayout, or Opera won't use our image for some obscure reason
3939
+ img._top = img.offsetTop;
3940
+ }
3941
+ e.dataTransfer.setDragImage(img, 0, 0);
3942
+ if (presto) img.parentNode.removeChild(img);
3943
+ }
3944
+ }
3945
+
3946
+ function onDragOver(cm, e) {
3947
+ var pos = posFromMouse(cm, e);
3948
+ if (!pos) return;
3949
+ var frag = document.createDocumentFragment();
3950
+ drawSelectionCursor(cm, pos, frag);
3951
+ if (!cm.display.dragCursor) {
3952
+ cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
3953
+ cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
3954
+ }
3955
+ removeChildrenAndAdd(cm.display.dragCursor, frag);
3956
+ }
3957
+
3958
+ function clearDragCursor(cm) {
3959
+ if (cm.display.dragCursor) {
3960
+ cm.display.lineSpace.removeChild(cm.display.dragCursor);
3961
+ cm.display.dragCursor = null;
3962
+ }
3963
+ }
3964
+
3965
+ // SCROLL EVENTS
3966
+
3967
+ // Sync the scrollable area and scrollbars, ensure the viewport
3968
+ // covers the visible area.
3969
+ function setScrollTop(cm, val) {
3970
+ if (Math.abs(cm.doc.scrollTop - val) < 2) return;
3971
+ cm.doc.scrollTop = val;
3972
+ if (!gecko) updateDisplaySimple(cm, {top: val});
3973
+ if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val;
3974
+ cm.display.scrollbars.setScrollTop(val);
3975
+ if (gecko) updateDisplaySimple(cm);
3976
+ startWorker(cm, 100);
3977
+ }
3978
+ // Sync scroller and scrollbar, ensure the gutter elements are
3979
+ // aligned.
3980
+ function setScrollLeft(cm, val, isScroller) {
3981
+ if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return;
3982
+ val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth);
3983
+ cm.doc.scrollLeft = val;
3984
+ alignHorizontally(cm);
3985
+ if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val;
3986
+ cm.display.scrollbars.setScrollLeft(val);
3987
+ }
3988
+
3989
+ // Since the delta values reported on mouse wheel events are
3990
+ // unstandardized between browsers and even browser versions, and
3991
+ // generally horribly unpredictable, this code starts by measuring
3992
+ // the scroll effect that the first few mouse wheel events have,
3993
+ // and, from that, detects the way it can convert deltas to pixel
3994
+ // offsets afterwards.
3995
+ //
3996
+ // The reason we want to know the amount a wheel event will scroll
3997
+ // is that it gives us a chance to update the display before the
3998
+ // actual scrolling happens, reducing flickering.
3999
+
4000
+ var wheelSamples = 0, wheelPixelsPerUnit = null;
4001
+ // Fill in a browser-detected starting value on browsers where we
4002
+ // know one. These don't have to be accurate -- the result of them
4003
+ // being wrong would just be a slight flicker on the first wheel
4004
+ // scroll (if it is large enough).
4005
+ if (ie) wheelPixelsPerUnit = -.53;
4006
+ else if (gecko) wheelPixelsPerUnit = 15;
4007
+ else if (chrome) wheelPixelsPerUnit = -.7;
4008
+ else if (safari) wheelPixelsPerUnit = -1/3;
4009
+
4010
+ var wheelEventDelta = function(e) {
4011
+ var dx = e.wheelDeltaX, dy = e.wheelDeltaY;
4012
+ if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail;
4013
+ if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail;
4014
+ else if (dy == null) dy = e.wheelDelta;
4015
+ return {x: dx, y: dy};
4016
+ };
4017
+ CodeMirror.wheelEventPixels = function(e) {
4018
+ var delta = wheelEventDelta(e);
4019
+ delta.x *= wheelPixelsPerUnit;
4020
+ delta.y *= wheelPixelsPerUnit;
4021
+ return delta;
4022
+ };
4023
+
4024
+ function onScrollWheel(cm, e) {
4025
+ var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
4026
+
4027
+ var display = cm.display, scroll = display.scroller;
4028
+ // Quit if there's nothing to scroll here
4029
+ var canScrollX = scroll.scrollWidth > scroll.clientWidth;
4030
+ var canScrollY = scroll.scrollHeight > scroll.clientHeight;
4031
+ if (!(dx && canScrollX || dy && canScrollY)) return;
4032
+
4033
+ // Webkit browsers on OS X abort momentum scrolls when the target
4034
+ // of the scroll event is removed from the scrollable element.
4035
+ // This hack (see related code in patchDisplay) makes sure the
4036
+ // element is kept around.
4037
+ if (dy && mac && webkit) {
4038
+ outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) {
4039
+ for (var i = 0; i < view.length; i++) {
4040
+ if (view[i].node == cur) {
4041
+ cm.display.currentWheelTarget = cur;
4042
+ break outer;
4043
+ }
4044
+ }
4045
+ }
4046
+ }
4047
+
4048
+ // On some browsers, horizontal scrolling will cause redraws to
4049
+ // happen before the gutter has been realigned, causing it to
4050
+ // wriggle around in a most unseemly way. When we have an
4051
+ // estimated pixels/delta value, we just handle horizontal
4052
+ // scrolling entirely here. It'll be slightly off from native, but
4053
+ // better than glitching out.
4054
+ if (dx && !gecko && !presto && wheelPixelsPerUnit != null) {
4055
+ if (dy && canScrollY)
4056
+ setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));
4057
+ setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth)));
4058
+ // Only prevent default scrolling if vertical scrolling is
4059
+ // actually possible. Otherwise, it causes vertical scroll
4060
+ // jitter on OSX trackpads when deltaX is small and deltaY
4061
+ // is large (issue #3579)
4062
+ if (!dy || (dy && canScrollY))
4063
+ e_preventDefault(e);
4064
+ display.wheelStartX = null; // Abort measurement, if in progress
4065
+ return;
4066
+ }
4067
+
4068
+ // 'Project' the visible viewport to cover the area that is being
4069
+ // scrolled into view (if we know enough to estimate it).
4070
+ if (dy && wheelPixelsPerUnit != null) {
4071
+ var pixels = dy * wheelPixelsPerUnit;
4072
+ var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight;
4073
+ if (pixels < 0) top = Math.max(0, top + pixels - 50);
4074
+ else bot = Math.min(cm.doc.height, bot + pixels + 50);
4075
+ updateDisplaySimple(cm, {top: top, bottom: bot});
4076
+ }
4077
+
4078
+ if (wheelSamples < 20) {
4079
+ if (display.wheelStartX == null) {
4080
+ display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop;
4081
+ display.wheelDX = dx; display.wheelDY = dy;
4082
+ setTimeout(function() {
4083
+ if (display.wheelStartX == null) return;
4084
+ var movedX = scroll.scrollLeft - display.wheelStartX;
4085
+ var movedY = scroll.scrollTop - display.wheelStartY;
4086
+ var sample = (movedY && display.wheelDY && movedY / display.wheelDY) ||
4087
+ (movedX && display.wheelDX && movedX / display.wheelDX);
4088
+ display.wheelStartX = display.wheelStartY = null;
4089
+ if (!sample) return;
4090
+ wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1);
4091
+ ++wheelSamples;
4092
+ }, 200);
4093
+ } else {
4094
+ display.wheelDX += dx; display.wheelDY += dy;
4095
+ }
4096
+ }
4097
+ }
4098
+
4099
+ // KEY EVENTS
4100
+
4101
+ // Run a handler that was bound to a key.
4102
+ function doHandleBinding(cm, bound, dropShift) {
4103
+ if (typeof bound == "string") {
4104
+ bound = commands[bound];
4105
+ if (!bound) return false;
4106
+ }
4107
+ // Ensure previous input has been read, so that the handler sees a
4108
+ // consistent view of the document
4109
+ cm.display.input.ensurePolled();
4110
+ var prevShift = cm.display.shift, done = false;
4111
+ try {
4112
+ if (cm.isReadOnly()) cm.state.suppressEdits = true;
4113
+ if (dropShift) cm.display.shift = false;
4114
+ done = bound(cm) != Pass;
4115
+ } finally {
4116
+ cm.display.shift = prevShift;
4117
+ cm.state.suppressEdits = false;
4118
+ }
4119
+ return done;
4120
+ }
4121
+
4122
+ function lookupKeyForEditor(cm, name, handle) {
4123
+ for (var i = 0; i < cm.state.keyMaps.length; i++) {
4124
+ var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
4125
+ if (result) return result;
4126
+ }
4127
+ return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
4128
+ || lookupKey(name, cm.options.keyMap, handle, cm);
4129
+ }
4130
+
4131
+ var stopSeq = new Delayed;
4132
+ function dispatchKey(cm, name, e, handle) {
4133
+ var seq = cm.state.keySeq;
4134
+ if (seq) {
4135
+ if (isModifierKey(name)) return "handled";
4136
+ stopSeq.set(50, function() {
4137
+ if (cm.state.keySeq == seq) {
4138
+ cm.state.keySeq = null;
4139
+ cm.display.input.reset();
4140
+ }
4141
+ });
4142
+ name = seq + " " + name;
4143
+ }
4144
+ var result = lookupKeyForEditor(cm, name, handle);
4145
+
4146
+ if (result == "multi")
4147
+ cm.state.keySeq = name;
4148
+ if (result == "handled")
4149
+ signalLater(cm, "keyHandled", cm, name, e);
4150
+
4151
+ if (result == "handled" || result == "multi") {
4152
+ e_preventDefault(e);
4153
+ restartBlink(cm);
4154
+ }
4155
+
4156
+ if (seq && !result && /\'$/.test(name)) {
4157
+ e_preventDefault(e);
4158
+ return true;
4159
+ }
4160
+ return !!result;
4161
+ }
4162
+
4163
+ // Handle a key from the keydown event.
4164
+ function handleKeyBinding(cm, e) {
4165
+ var name = keyName(e, true);
4166
+ if (!name) return false;
4167
+
4168
+ if (e.shiftKey && !cm.state.keySeq) {
4169
+ // First try to resolve full name (including 'Shift-'). Failing
4170
+ // that, see if there is a cursor-motion command (starting with
4171
+ // 'go') bound to the keyname without 'Shift-'.
4172
+ return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);})
4173
+ || dispatchKey(cm, name, e, function(b) {
4174
+ if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
4175
+ return doHandleBinding(cm, b);
4176
+ });
4177
+ } else {
4178
+ return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); });
4179
+ }
4180
+ }
4181
+
4182
+ // Handle a key from the keypress event
4183
+ function handleCharBinding(cm, e, ch) {
4184
+ return dispatchKey(cm, "'" + ch + "'", e,
4185
+ function(b) { return doHandleBinding(cm, b, true); });
4186
+ }
4187
+
4188
+ var lastStoppedKey = null;
4189
+ function onKeyDown(e) {
4190
+ var cm = this;
4191
+ cm.curOp.focus = activeElt();
4192
+ if (signalDOMEvent(cm, e)) return;
4193
+ // IE does strange things with escape.
4194
+ if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false;
4195
+ var code = e.keyCode;
4196
+ cm.display.shift = code == 16 || e.shiftKey;
4197
+ var handled = handleKeyBinding(cm, e);
4198
+ if (presto) {
4199
+ lastStoppedKey = handled ? code : null;
4200
+ // Opera has no cut event... we try to at least catch the key combo
4201
+ if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey))
4202
+ cm.replaceSelection("", null, "cut");
4203
+ }
4204
+
4205
+ // Turn mouse into crosshair when Alt is held on Mac.
4206
+ if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
4207
+ showCrossHair(cm);
4208
+ }
4209
+
4210
+ function showCrossHair(cm) {
4211
+ var lineDiv = cm.display.lineDiv;
4212
+ addClass(lineDiv, "CodeMirror-crosshair");
4213
+
4214
+ function up(e) {
4215
+ if (e.keyCode == 18 || !e.altKey) {
4216
+ rmClass(lineDiv, "CodeMirror-crosshair");
4217
+ off(document, "keyup", up);
4218
+ off(document, "mouseover", up);
4219
+ }
4220
+ }
4221
+ on(document, "keyup", up);
4222
+ on(document, "mouseover", up);
4223
+ }
4224
+
4225
+ function onKeyUp(e) {
4226
+ if (e.keyCode == 16) this.doc.sel.shift = false;
4227
+ signalDOMEvent(this, e);
4228
+ }
4229
+
4230
+ function onKeyPress(e) {
4231
+ var cm = this;
4232
+ if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return;
4233
+ var keyCode = e.keyCode, charCode = e.charCode;
4234
+ if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;}
4235
+ if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return;
4236
+ var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
4237
+ if (handleCharBinding(cm, e, ch)) return;
4238
+ cm.display.input.onKeyPress(e);
4239
+ }
4240
+
4241
+ // FOCUS/BLUR EVENTS
4242
+
4243
+ function delayBlurEvent(cm) {
4244
+ cm.state.delayingBlurEvent = true;
4245
+ setTimeout(function() {
4246
+ if (cm.state.delayingBlurEvent) {
4247
+ cm.state.delayingBlurEvent = false;
4248
+ onBlur(cm);
4249
+ }
4250
+ }, 100);
4251
+ }
4252
+
4253
+ function onFocus(cm) {
4254
+ if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false;
4255
+
4256
+ if (cm.options.readOnly == "nocursor") return;
4257
+ if (!cm.state.focused) {
4258
+ signal(cm, "focus", cm);
4259
+ cm.state.focused = true;
4260
+ addClass(cm.display.wrapper, "CodeMirror-focused");
4261
+ // This test prevents this from firing when a context
4262
+ // menu is closed (since the input reset would kill the
4263
+ // select-all detection hack)
4264
+ if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
4265
+ cm.display.input.reset();
4266
+ if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730
4267
+ }
4268
+ cm.display.input.receivedFocus();
4269
+ }
4270
+ restartBlink(cm);
4271
+ }
4272
+ function onBlur(cm) {
4273
+ if (cm.state.delayingBlurEvent) return;
4274
+
4275
+ if (cm.state.focused) {
4276
+ signal(cm, "blur", cm);
4277
+ cm.state.focused = false;
4278
+ rmClass(cm.display.wrapper, "CodeMirror-focused");
4279
+ }
4280
+ clearInterval(cm.display.blinker);
4281
+ setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150);
4282
+ }
4283
+
4284
+ // CONTEXT MENU HANDLING
4285
+
4286
+ // To make the context menu work, we need to briefly unhide the
4287
+ // textarea (making it as unobtrusive as possible) to let the
4288
+ // right-click take effect on it.
4289
+ function onContextMenu(cm, e) {
4290
+ if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return;
4291
+ if (signalDOMEvent(cm, e, "contextmenu")) return;
4292
+ cm.display.input.onContextMenu(e);
4293
+ }
4294
+
4295
+ function contextMenuInGutter(cm, e) {
4296
+ if (!hasHandler(cm, "gutterContextMenu")) return false;
4297
+ return gutterEvent(cm, e, "gutterContextMenu", false);
4298
+ }
4299
+
4300
+ // UPDATING
4301
+
4302
+ // Compute the position of the end of a change (its 'to' property
4303
+ // refers to the pre-change end).
4304
+ var changeEnd = CodeMirror.changeEnd = function(change) {
4305
+ if (!change.text) return change.to;
4306
+ return Pos(change.from.line + change.text.length - 1,
4307
+ lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0));
4308
+ };
4309
+
4310
+ // Adjust a position to refer to the post-change position of the
4311
+ // same text, or the end of the change if the change covers it.
4312
+ function adjustForChange(pos, change) {
4313
+ if (cmp(pos, change.from) < 0) return pos;
4314
+ if (cmp(pos, change.to) <= 0) return changeEnd(change);
4315
+
4316
+ var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch;
4317
+ if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch;
4318
+ return Pos(line, ch);
4319
+ }
4320
+
4321
+ function computeSelAfterChange(doc, change) {
4322
+ var out = [];
4323
+ for (var i = 0; i < doc.sel.ranges.length; i++) {
4324
+ var range = doc.sel.ranges[i];
4325
+ out.push(new Range(adjustForChange(range.anchor, change),
4326
+ adjustForChange(range.head, change)));
4327
+ }
4328
+ return normalizeSelection(out, doc.sel.primIndex);
4329
+ }
4330
+
4331
+ function offsetPos(pos, old, nw) {
4332
+ if (pos.line == old.line)
4333
+ return Pos(nw.line, pos.ch - old.ch + nw.ch);
4334
+ else
4335
+ return Pos(nw.line + (pos.line - old.line), pos.ch);
4336
+ }
4337
+
4338
+ // Used by replaceSelections to allow moving the selection to the
4339
+ // start or around the replaced test. Hint may be "start" or "around".
4340
+ function computeReplacedSel(doc, changes, hint) {
4341
+ var out = [];
4342
+ var oldPrev = Pos(doc.first, 0), newPrev = oldPrev;
4343
+ for (var i = 0; i < changes.length; i++) {
4344
+ var change = changes[i];
4345
+ var from = offsetPos(change.from, oldPrev, newPrev);
4346
+ var to = offsetPos(changeEnd(change), oldPrev, newPrev);
4347
+ oldPrev = change.to;
4348
+ newPrev = to;
4349
+ if (hint == "around") {
4350
+ var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0;
4351
+ out[i] = new Range(inv ? to : from, inv ? from : to);
4352
+ } else {
4353
+ out[i] = new Range(from, from);
4354
+ }
4355
+ }
4356
+ return new Selection(out, doc.sel.primIndex);
4357
+ }
4358
+
4359
+ // Allow "beforeChange" event handlers to influence a change
4360
+ function filterChange(doc, change, update) {
4361
+ var obj = {
4362
+ canceled: false,
4363
+ from: change.from,
4364
+ to: change.to,
4365
+ text: change.text,
4366
+ origin: change.origin,
4367
+ cancel: function() { this.canceled = true; }
4368
+ };
4369
+ if (update) obj.update = function(from, to, text, origin) {
4370
+ if (from) this.from = clipPos(doc, from);
4371
+ if (to) this.to = clipPos(doc, to);
4372
+ if (text) this.text = text;
4373
+ if (origin !== undefined) this.origin = origin;
4374
+ };
4375
+ signal(doc, "beforeChange", doc, obj);
4376
+ if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj);
4377
+
4378
+ if (obj.canceled) return null;
4379
+ return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin};
4380
+ }
4381
+
4382
+ // Apply a change to a document, and add it to the document's
4383
+ // history, and propagating it to all linked documents.
4384
+ function makeChange(doc, change, ignoreReadOnly) {
4385
+ if (doc.cm) {
4386
+ if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly);
4387
+ if (doc.cm.state.suppressEdits) return;
4388
+ }
4389
+
4390
+ if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) {
4391
+ change = filterChange(doc, change, true);
4392
+ if (!change) return;
4393
+ }
4394
+
4395
+ // Possibly split or suppress the update based on the presence
4396
+ // of read-only spans in its range.
4397
+ var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to);
4398
+ if (split) {
4399
+ for (var i = split.length - 1; i >= 0; --i)
4400
+ makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});
4401
+ } else {
4402
+ makeChangeInner(doc, change);
4403
+ }
4404
+ }
4405
+
4406
+ function makeChangeInner(doc, change) {
4407
+ if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return;
4408
+ var selAfter = computeSelAfterChange(doc, change);
4409
+ addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN);
4410
+
4411
+ makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change));
4412
+ var rebased = [];
4413
+
4414
+ linkedDocs(doc, function(doc, sharedHist) {
4415
+ if (!sharedHist && indexOf(rebased, doc.history) == -1) {
4416
+ rebaseHist(doc.history, change);
4417
+ rebased.push(doc.history);
4418
+ }
4419
+ makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change));
4420
+ });
4421
+ }
4422
+
4423
+ // Revert a change stored in a document's history.
4424
+ function makeChangeFromHistory(doc, type, allowSelectionOnly) {
4425
+ if (doc.cm && doc.cm.state.suppressEdits && !allowSelectionOnly) return;
4426
+
4427
+ var hist = doc.history, event, selAfter = doc.sel;
4428
+ var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done;
4429
+
4430
+ // Verify that there is a useable event (so that ctrl-z won't
4431
+ // needlessly clear selection events)
4432
+ for (var i = 0; i < source.length; i++) {
4433
+ event = source[i];
4434
+ if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges)
4435
+ break;
4436
+ }
4437
+ if (i == source.length) return;
4438
+ hist.lastOrigin = hist.lastSelOrigin = null;
4439
+
4440
+ for (;;) {
4441
+ event = source.pop();
4442
+ if (event.ranges) {
4443
+ pushSelectionToHistory(event, dest);
4444
+ if (allowSelectionOnly && !event.equals(doc.sel)) {
4445
+ setSelection(doc, event, {clearRedo: false});
4446
+ return;
4447
+ }
4448
+ selAfter = event;
4449
+ }
4450
+ else break;
4451
+ }
4452
+
4453
+ // Build up a reverse change object to add to the opposite history
4454
+ // stack (redo when undoing, and vice versa).
4455
+ var antiChanges = [];
4456
+ pushSelectionToHistory(selAfter, dest);
4457
+ dest.push({changes: antiChanges, generation: hist.generation});
4458
+ hist.generation = event.generation || ++hist.maxGeneration;
4459
+
4460
+ var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange");
4461
+
4462
+ for (var i = event.changes.length - 1; i >= 0; --i) {
4463
+ var change = event.changes[i];
4464
+ change.origin = type;
4465
+ if (filter && !filterChange(doc, change, false)) {
4466
+ source.length = 0;
4467
+ return;
4468
+ }
4469
+
4470
+ antiChanges.push(historyChangeFromChange(doc, change));
4471
+
4472
+ var after = i ? computeSelAfterChange(doc, change) : lst(source);
4473
+ makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
4474
+ if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)});
4475
+ var rebased = [];
4476
+
4477
+ // Propagate to the linked documents
4478
+ linkedDocs(doc, function(doc, sharedHist) {
4479
+ if (!sharedHist && indexOf(rebased, doc.history) == -1) {
4480
+ rebaseHist(doc.history, change);
4481
+ rebased.push(doc.history);
4482
+ }
4483
+ makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change));
4484
+ });
4485
+ }
4486
+ }
4487
+
4488
+ // Sub-views need their line numbers shifted when text is added
4489
+ // above or below them in the parent document.
4490
+ function shiftDoc(doc, distance) {
4491
+ if (distance == 0) return;
4492
+ doc.first += distance;
4493
+ doc.sel = new Selection(map(doc.sel.ranges, function(range) {
4494
+ return new Range(Pos(range.anchor.line + distance, range.anchor.ch),
4495
+ Pos(range.head.line + distance, range.head.ch));
4496
+ }), doc.sel.primIndex);
4497
+ if (doc.cm) {
4498
+ regChange(doc.cm, doc.first, doc.first - distance, distance);
4499
+ for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
4500
+ regLineChange(doc.cm, l, "gutter");
4501
+ }
4502
+ }
4503
+
4504
+ // More lower-level change function, handling only a single document
4505
+ // (not linked ones).
4506
+ function makeChangeSingleDoc(doc, change, selAfter, spans) {
4507
+ if (doc.cm && !doc.cm.curOp)
4508
+ return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);
4509
+
4510
+ if (change.to.line < doc.first) {
4511
+ shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line));
4512
+ return;
4513
+ }
4514
+ if (change.from.line > doc.lastLine()) return;
4515
+
4516
+ // Clip the change to the size of this doc
4517
+ if (change.from.line < doc.first) {
4518
+ var shift = change.text.length - 1 - (doc.first - change.from.line);
4519
+ shiftDoc(doc, shift);
4520
+ change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch),
4521
+ text: [lst(change.text)], origin: change.origin};
4522
+ }
4523
+ var last = doc.lastLine();
4524
+ if (change.to.line > last) {
4525
+ change = {from: change.from, to: Pos(last, getLine(doc, last).text.length),
4526
+ text: [change.text[0]], origin: change.origin};
4527
+ }
4528
+
4529
+ change.removed = getBetween(doc, change.from, change.to);
4530
+
4531
+ if (!selAfter) selAfter = computeSelAfterChange(doc, change);
4532
+ if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans);
4533
+ else updateDoc(doc, change, spans);
4534
+ setSelectionNoUndo(doc, selAfter, sel_dontScroll);
4535
+ }
4536
+
4537
+ // Handle the interaction of a change to a document with the editor
4538
+ // that this document is part of.
4539
+ function makeChangeSingleDocInEditor(cm, change, spans) {
4540
+ var doc = cm.doc, display = cm.display, from = change.from, to = change.to;
4541
+
4542
+ var recomputeMaxLength = false, checkWidthStart = from.line;
4543
+ if (!cm.options.lineWrapping) {
4544
+ checkWidthStart = lineNo(visualLine(getLine(doc, from.line)));
4545
+ doc.iter(checkWidthStart, to.line + 1, function(line) {
4546
+ if (line == display.maxLine) {
4547
+ recomputeMaxLength = true;
4548
+ return true;
4549
+ }
4550
+ });
4551
+ }
4552
+
4553
+ if (doc.sel.contains(change.from, change.to) > -1)
4554
+ signalCursorActivity(cm);
4555
+
4556
+ updateDoc(doc, change, spans, estimateHeight(cm));
4557
+
4558
+ if (!cm.options.lineWrapping) {
4559
+ doc.iter(checkWidthStart, from.line + change.text.length, function(line) {
4560
+ var len = lineLength(line);
4561
+ if (len > display.maxLineLength) {
4562
+ display.maxLine = line;
4563
+ display.maxLineLength = len;
4564
+ display.maxLineChanged = true;
4565
+ recomputeMaxLength = false;
4566
+ }
4567
+ });
4568
+ if (recomputeMaxLength) cm.curOp.updateMaxLine = true;
4569
+ }
4570
+
4571
+ // Adjust frontier, schedule worker
4572
+ doc.frontier = Math.min(doc.frontier, from.line);
4573
+ startWorker(cm, 400);
4574
+
4575
+ var lendiff = change.text.length - (to.line - from.line) - 1;
4576
+ // Remember that these lines changed, for updating the display
4577
+ if (change.full)
4578
+ regChange(cm);
4579
+ else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change))
4580
+ regLineChange(cm, from.line, "text");
4581
+ else
4582
+ regChange(cm, from.line, to.line + 1, lendiff);
4583
+
4584
+ var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
4585
+ if (changeHandler || changesHandler) {
4586
+ var obj = {
4587
+ from: from, to: to,
4588
+ text: change.text,
4589
+ removed: change.removed,
4590
+ origin: change.origin
4591
+ };
4592
+ if (changeHandler) signalLater(cm, "change", cm, obj);
4593
+ if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj);
4594
+ }
4595
+ cm.display.selForContextMenu = null;
4596
+ }
4597
+
4598
+ function replaceRange(doc, code, from, to, origin) {
4599
+ if (!to) to = from;
4600
+ if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; }
4601
+ if (typeof code == "string") code = doc.splitLines(code);
4602
+ makeChange(doc, {from: from, to: to, text: code, origin: origin});
4603
+ }
4604
+
4605
+ // SCROLLING THINGS INTO VIEW
4606
+
4607
+ // If an editor sits on the top or bottom of the window, partially
4608
+ // scrolled out of view, this ensures that the cursor is visible.
4609
+ function maybeScrollWindow(cm, coords) {
4610
+ if (signalDOMEvent(cm, "scrollCursorIntoView")) return;
4611
+
4612
+ var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
4613
+ if (coords.top + box.top < 0) doScroll = true;
4614
+ else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false;
4615
+ if (doScroll != null && !phantom) {
4616
+ var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " +
4617
+ (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " +
4618
+ (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " +
4619
+ coords.left + "px; width: 2px;");
4620
+ cm.display.lineSpace.appendChild(scrollNode);
4621
+ scrollNode.scrollIntoView(doScroll);
4622
+ cm.display.lineSpace.removeChild(scrollNode);
4623
+ }
4624
+ }
4625
+
4626
+ // Scroll a given position into view (immediately), verifying that
4627
+ // it actually became visible (as line heights are accurately
4628
+ // measured, the position of something may 'drift' during drawing).
4629
+ function scrollPosIntoView(cm, pos, end, margin) {
4630
+ if (margin == null) margin = 0;
4631
+ for (var limit = 0; limit < 5; limit++) {
4632
+ var changed = false, coords = cursorCoords(cm, pos);
4633
+ var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
4634
+ var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left),
4635
+ Math.min(coords.top, endCoords.top) - margin,
4636
+ Math.max(coords.left, endCoords.left),
4637
+ Math.max(coords.bottom, endCoords.bottom) + margin);
4638
+ var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
4639
+ if (scrollPos.scrollTop != null) {
4640
+ setScrollTop(cm, scrollPos.scrollTop);
4641
+ if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true;
4642
+ }
4643
+ if (scrollPos.scrollLeft != null) {
4644
+ setScrollLeft(cm, scrollPos.scrollLeft);
4645
+ if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true;
4646
+ }
4647
+ if (!changed) break;
4648
+ }
4649
+ return coords;
4650
+ }
4651
+
4652
+ // Scroll a given set of coordinates into view (immediately).
4653
+ function scrollIntoView(cm, x1, y1, x2, y2) {
4654
+ var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2);
4655
+ if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop);
4656
+ if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft);
4657
+ }
4658
+
4659
+ // Calculate a new scroll position needed to scroll the given
4660
+ // rectangle into view. Returns an object with scrollTop and
4661
+ // scrollLeft properties. When these are undefined, the
4662
+ // vertical/horizontal position does not need to be adjusted.
4663
+ function calculateScrollPos(cm, x1, y1, x2, y2) {
4664
+ var display = cm.display, snapMargin = textHeight(cm.display);
4665
+ if (y1 < 0) y1 = 0;
4666
+ var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
4667
+ var screen = displayHeight(cm), result = {};
4668
+ if (y2 - y1 > screen) y2 = y1 + screen;
4669
+ var docBottom = cm.doc.height + paddingVert(display);
4670
+ var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin;
4671
+ if (y1 < screentop) {
4672
+ result.scrollTop = atTop ? 0 : y1;
4673
+ } else if (y2 > screentop + screen) {
4674
+ var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen);
4675
+ if (newTop != screentop) result.scrollTop = newTop;
4676
+ }
4677
+
4678
+ var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
4679
+ var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
4680
+ var tooWide = x2 - x1 > screenw;
4681
+ if (tooWide) x2 = x1 + screenw;
4682
+ if (x1 < 10)
4683
+ result.scrollLeft = 0;
4684
+ else if (x1 < screenleft)
4685
+ result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10));
4686
+ else if (x2 > screenw + screenleft - 3)
4687
+ result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw;
4688
+ return result;
4689
+ }
4690
+
4691
+ // Store a relative adjustment to the scroll position in the current
4692
+ // operation (to be applied when the operation finishes).
4693
+ function addToScrollPos(cm, left, top) {
4694
+ if (left != null || top != null) resolveScrollToPos(cm);
4695
+ if (left != null)
4696
+ cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;
4697
+ if (top != null)
4698
+ cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;
4699
+ }
4700
+
4701
+ // Make sure that at the end of the operation the current cursor is
4702
+ // shown.
4703
+ function ensureCursorVisible(cm) {
4704
+ resolveScrollToPos(cm);
4705
+ var cur = cm.getCursor(), from = cur, to = cur;
4706
+ if (!cm.options.lineWrapping) {
4707
+ from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur;
4708
+ to = Pos(cur.line, cur.ch + 1);
4709
+ }
4710
+ cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true};
4711
+ }
4712
+
4713
+ // When an operation has its scrollToPos property set, and another
4714
+ // scroll action is applied before the end of the operation, this
4715
+ // 'simulates' scrolling that position into view in a cheap way, so
4716
+ // that the effect of intermediate scroll commands is not ignored.
4717
+ function resolveScrollToPos(cm) {
4718
+ var range = cm.curOp.scrollToPos;
4719
+ if (range) {
4720
+ cm.curOp.scrollToPos = null;
4721
+ var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to);
4722
+ var sPos = calculateScrollPos(cm, Math.min(from.left, to.left),
4723
+ Math.min(from.top, to.top) - range.margin,
4724
+ Math.max(from.right, to.right),
4725
+ Math.max(from.bottom, to.bottom) + range.margin);
4726
+ cm.scrollTo(sPos.scrollLeft, sPos.scrollTop);
4727
+ }
4728
+ }
4729
+
4730
+ // API UTILITIES
4731
+
4732
+ // Indent the given line. The how parameter can be "smart",
4733
+ // "add"/null, "subtract", or "prev". When aggressive is false
4734
+ // (typically set to true for forced single-line indents), empty
4735
+ // lines are not indented, and places where the mode returns Pass
4736
+ // are left alone.
4737
+ function indentLine(cm, n, how, aggressive) {
4738
+ var doc = cm.doc, state;
4739
+ if (how == null) how = "add";
4740
+ if (how == "smart") {
4741
+ // Fall back to "prev" when the mode doesn't have an indentation
4742
+ // method.
4743
+ if (!doc.mode.indent) how = "prev";
4744
+ else state = getStateBefore(cm, n);
4745
+ }
4746
+
4747
+ var tabSize = cm.options.tabSize;
4748
+ var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize);
4749
+ if (line.stateAfter) line.stateAfter = null;
4750
+ var curSpaceString = line.text.match(/^\s*/)[0], indentation;
4751
+ if (!aggressive && !/\S/.test(line.text)) {
4752
+ indentation = 0;
4753
+ how = "not";
4754
+ } else if (how == "smart") {
4755
+ indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
4756
+ if (indentation == Pass || indentation > 150) {
4757
+ if (!aggressive) return;
4758
+ how = "prev";
4759
+ }
4760
+ }
4761
+ if (how == "prev") {
4762
+ if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize);
4763
+ else indentation = 0;
4764
+ } else if (how == "add") {
4765
+ indentation = curSpace + cm.options.indentUnit;
4766
+ } else if (how == "subtract") {
4767
+ indentation = curSpace - cm.options.indentUnit;
4768
+ } else if (typeof how == "number") {
4769
+ indentation = curSpace + how;
4770
+ }
4771
+ indentation = Math.max(0, indentation);
4772
+
4773
+ var indentString = "", pos = 0;
4774
+ if (cm.options.indentWithTabs)
4775
+ for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}
4776
+ if (pos < indentation) indentString += spaceStr(indentation - pos);
4777
+
4778
+ if (indentString != curSpaceString) {
4779
+ replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
4780
+ line.stateAfter = null;
4781
+ return true;
4782
+ } else {
4783
+ // Ensure that, if the cursor was in the whitespace at the start
4784
+ // of the line, it is moved to the end of that space.
4785
+ for (var i = 0; i < doc.sel.ranges.length; i++) {
4786
+ var range = doc.sel.ranges[i];
4787
+ if (range.head.line == n && range.head.ch < curSpaceString.length) {
4788
+ var pos = Pos(n, curSpaceString.length);
4789
+ replaceOneSelection(doc, i, new Range(pos, pos));
4790
+ break;
4791
+ }
4792
+ }
4793
+ }
4794
+ }
4795
+
4796
+ // Utility for applying a change to a line by handle or number,
4797
+ // returning the number and optionally registering the line as
4798
+ // changed.
4799
+ function changeLine(doc, handle, changeType, op) {
4800
+ var no = handle, line = handle;
4801
+ if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle));
4802
+ else no = lineNo(handle);
4803
+ if (no == null) return null;
4804
+ if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType);
4805
+ return line;
4806
+ }
4807
+
4808
+ // Helper for deleting text near the selection(s), used to implement
4809
+ // backspace, delete, and similar functionality.
4810
+ function deleteNearSelection(cm, compute) {
4811
+ var ranges = cm.doc.sel.ranges, kill = [];
4812
+ // Build up a set of ranges to kill first, merging overlapping
4813
+ // ranges.
4814
+ for (var i = 0; i < ranges.length; i++) {
4815
+ var toKill = compute(ranges[i]);
4816
+ while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) {
4817
+ var replaced = kill.pop();
4818
+ if (cmp(replaced.from, toKill.from) < 0) {
4819
+ toKill.from = replaced.from;
4820
+ break;
4821
+ }
4822
+ }
4823
+ kill.push(toKill);
4824
+ }
4825
+ // Next, remove those actual ranges.
4826
+ runInOp(cm, function() {
4827
+ for (var i = kill.length - 1; i >= 0; i--)
4828
+ replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");
4829
+ ensureCursorVisible(cm);
4830
+ });
4831
+ }
4832
+
4833
+ // Used for horizontal relative motion. Dir is -1 or 1 (left or
4834
+ // right), unit can be "char", "column" (like char, but doesn't
4835
+ // cross line boundaries), "word" (across next word), or "group" (to
4836
+ // the start of next group of word or non-word-non-whitespace
4837
+ // chars). The visually param controls whether, in right-to-left
4838
+ // text, direction 1 means to move towards the next index in the
4839
+ // string, or towards the character to the right of the current
4840
+ // position. The resulting position will have a hitSide=true
4841
+ // property if it reached the end of the document.
4842
+ function findPosH(doc, pos, dir, unit, visually) {
4843
+ var line = pos.line, ch = pos.ch, origDir = dir;
4844
+ var lineObj = getLine(doc, line);
4845
+ function findNextLine() {
4846
+ var l = line + dir;
4847
+ if (l < doc.first || l >= doc.first + doc.size) return false
4848
+ line = l;
4849
+ return lineObj = getLine(doc, l);
4850
+ }
4851
+ function moveOnce(boundToLine) {
4852
+ var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true);
4853
+ if (next == null) {
4854
+ if (!boundToLine && findNextLine()) {
4855
+ if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj);
4856
+ else ch = dir < 0 ? lineObj.text.length : 0;
4857
+ } else return false
4858
+ } else ch = next;
4859
+ return true;
4860
+ }
4861
+
4862
+ if (unit == "char") {
4863
+ moveOnce()
4864
+ } else if (unit == "column") {
4865
+ moveOnce(true)
4866
+ } else if (unit == "word" || unit == "group") {
4867
+ var sawType = null, group = unit == "group";
4868
+ var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
4869
+ for (var first = true;; first = false) {
4870
+ if (dir < 0 && !moveOnce(!first)) break;
4871
+ var cur = lineObj.text.charAt(ch) || "\n";
4872
+ var type = isWordChar(cur, helper) ? "w"
4873
+ : group && cur == "\n" ? "n"
4874
+ : !group || /\s/.test(cur) ? null
4875
+ : "p";
4876
+ if (group && !first && !type) type = "s";
4877
+ if (sawType && sawType != type) {
4878
+ if (dir < 0) {dir = 1; moveOnce();}
4879
+ break;
4880
+ }
4881
+
4882
+ if (type) sawType = type;
4883
+ if (dir > 0 && !moveOnce(!first)) break;
4884
+ }
4885
+ }
4886
+ var result = skipAtomic(doc, Pos(line, ch), pos, origDir, true);
4887
+ if (!cmp(pos, result)) result.hitSide = true;
4888
+ return result;
4889
+ }
4890
+
4891
+ // For relative vertical movement. Dir may be -1 or 1. Unit can be
4892
+ // "page" or "line". The resulting position will have a hitSide=true
4893
+ // property if it reached the end of the document.
4894
+ function findPosV(cm, pos, dir, unit) {
4895
+ var doc = cm.doc, x = pos.left, y;
4896
+ if (unit == "page") {
4897
+ var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight);
4898
+ y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display));
4899
+ } else if (unit == "line") {
4900
+ y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
4901
+ }
4902
+ for (;;) {
4903
+ var target = coordsChar(cm, x, y);
4904
+ if (!target.outside) break;
4905
+ if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; }
4906
+ y += dir * 5;
4907
+ }
4908
+ return target;
4909
+ }
4910
+
4911
+ // EDITOR METHODS
4912
+
4913
+ // The publicly visible API. Note that methodOp(f) means
4914
+ // 'wrap f in an operation, performed on its `this` parameter'.
4915
+
4916
+ // This is not the complete set of editor methods. Most of the
4917
+ // methods defined on the Doc type are also injected into
4918
+ // CodeMirror.prototype, for backwards compatibility and
4919
+ // convenience.
4920
+
4921
+ CodeMirror.prototype = {
4922
+ constructor: CodeMirror,
4923
+ focus: function(){window.focus(); this.display.input.focus();},
4924
+
4925
+ setOption: function(option, value) {
4926
+ var options = this.options, old = options[option];
4927
+ if (options[option] == value && option != "mode") return;
4928
+ options[option] = value;
4929
+ if (optionHandlers.hasOwnProperty(option))
4930
+ operation(this, optionHandlers[option])(this, value, old);
4931
+ },
4932
+
4933
+ getOption: function(option) {return this.options[option];},
4934
+ getDoc: function() {return this.doc;},
4935
+
4936
+ addKeyMap: function(map, bottom) {
4937
+ this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
4938
+ },
4939
+ removeKeyMap: function(map) {
4940
+ var maps = this.state.keyMaps;
4941
+ for (var i = 0; i < maps.length; ++i)
4942
+ if (maps[i] == map || maps[i].name == map) {
4943
+ maps.splice(i, 1);
4944
+ return true;
4945
+ }
4946
+ },
4947
+
4948
+ addOverlay: methodOp(function(spec, options) {
4949
+ var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec);
4950
+ if (mode.startState) throw new Error("Overlays may not be stateful.");
4951
+ this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque});
4952
+ this.state.modeGen++;
4953
+ regChange(this);
4954
+ }),
4955
+ removeOverlay: methodOp(function(spec) {
4956
+ var overlays = this.state.overlays;
4957
+ for (var i = 0; i < overlays.length; ++i) {
4958
+ var cur = overlays[i].modeSpec;
4959
+ if (cur == spec || typeof spec == "string" && cur.name == spec) {
4960
+ overlays.splice(i, 1);
4961
+ this.state.modeGen++;
4962
+ regChange(this);
4963
+ return;
4964
+ }
4965
+ }
4966
+ }),
4967
+
4968
+ indentLine: methodOp(function(n, dir, aggressive) {
4969
+ if (typeof dir != "string" && typeof dir != "number") {
4970
+ if (dir == null) dir = this.options.smartIndent ? "smart" : "prev";
4971
+ else dir = dir ? "add" : "subtract";
4972
+ }
4973
+ if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive);
4974
+ }),
4975
+ indentSelection: methodOp(function(how) {
4976
+ var ranges = this.doc.sel.ranges, end = -1;
4977
+ for (var i = 0; i < ranges.length; i++) {
4978
+ var range = ranges[i];
4979
+ if (!range.empty()) {
4980
+ var from = range.from(), to = range.to();
4981
+ var start = Math.max(end, from.line);
4982
+ end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
4983
+ for (var j = start; j < end; ++j)
4984
+ indentLine(this, j, how);
4985
+ var newRanges = this.doc.sel.ranges;
4986
+ if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
4987
+ replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);
4988
+ } else if (range.head.line > end) {
4989
+ indentLine(this, range.head.line, how, true);
4990
+ end = range.head.line;
4991
+ if (i == this.doc.sel.primIndex) ensureCursorVisible(this);
4992
+ }
4993
+ }
4994
+ }),
4995
+
4996
+ // Fetch the parser token for a given character. Useful for hacks
4997
+ // that want to inspect the mode state (say, for completion).
4998
+ getTokenAt: function(pos, precise) {
4999
+ return takeToken(this, pos, precise);
5000
+ },
5001
+
5002
+ getLineTokens: function(line, precise) {
5003
+ return takeToken(this, Pos(line), precise, true);
5004
+ },
5005
+
5006
+ getTokenTypeAt: function(pos) {
5007
+ pos = clipPos(this.doc, pos);
5008
+ var styles = getLineStyles(this, getLine(this.doc, pos.line));
5009
+ var before = 0, after = (styles.length - 1) / 2, ch = pos.ch;
5010
+ var type;
5011
+ if (ch == 0) type = styles[2];
5012
+ else for (;;) {
5013
+ var mid = (before + after) >> 1;
5014
+ if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid;
5015
+ else if (styles[mid * 2 + 1] < ch) before = mid + 1;
5016
+ else { type = styles[mid * 2 + 2]; break; }
5017
+ }
5018
+ var cut = type ? type.indexOf("cm-overlay ") : -1;
5019
+ return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1);
5020
+ },
5021
+
5022
+ getModeAt: function(pos) {
5023
+ var mode = this.doc.mode;
5024
+ if (!mode.innerMode) return mode;
5025
+ return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode;
5026
+ },
5027
+
5028
+ getHelper: function(pos, type) {
5029
+ return this.getHelpers(pos, type)[0];
5030
+ },
5031
+
5032
+ getHelpers: function(pos, type) {
5033
+ var found = [];
5034
+ if (!helpers.hasOwnProperty(type)) return found;
5035
+ var help = helpers[type], mode = this.getModeAt(pos);
5036
+ if (typeof mode[type] == "string") {
5037
+ if (help[mode[type]]) found.push(help[mode[type]]);
5038
+ } else if (mode[type]) {
5039
+ for (var i = 0; i < mode[type].length; i++) {
5040
+ var val = help[mode[type][i]];
5041
+ if (val) found.push(val);
5042
+ }
5043
+ } else if (mode.helperType && help[mode.helperType]) {
5044
+ found.push(help[mode.helperType]);
5045
+ } else if (help[mode.name]) {
5046
+ found.push(help[mode.name]);
5047
+ }
5048
+ for (var i = 0; i < help._global.length; i++) {
5049
+ var cur = help._global[i];
5050
+ if (cur.pred(mode, this) && indexOf(found, cur.val) == -1)
5051
+ found.push(cur.val);
5052
+ }
5053
+ return found;
5054
+ },
5055
+
5056
+ getStateAfter: function(line, precise) {
5057
+ var doc = this.doc;
5058
+ line = clipLine(doc, line == null ? doc.first + doc.size - 1: line);
5059
+ return getStateBefore(this, line + 1, precise);
5060
+ },
5061
+
5062
+ cursorCoords: function(start, mode) {
5063
+ var pos, range = this.doc.sel.primary();
5064
+ if (start == null) pos = range.head;
5065
+ else if (typeof start == "object") pos = clipPos(this.doc, start);
5066
+ else pos = start ? range.from() : range.to();
5067
+ return cursorCoords(this, pos, mode || "page");
5068
+ },
5069
+
5070
+ charCoords: function(pos, mode) {
5071
+ return charCoords(this, clipPos(this.doc, pos), mode || "page");
5072
+ },
5073
+
5074
+ coordsChar: function(coords, mode) {
5075
+ coords = fromCoordSystem(this, coords, mode || "page");
5076
+ return coordsChar(this, coords.left, coords.top);
5077
+ },
5078
+
5079
+ lineAtHeight: function(height, mode) {
5080
+ height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top;
5081
+ return lineAtHeight(this.doc, height + this.display.viewOffset);
5082
+ },
5083
+ heightAtLine: function(line, mode) {
5084
+ var end = false, lineObj;
5085
+ if (typeof line == "number") {
5086
+ var last = this.doc.first + this.doc.size - 1;
5087
+ if (line < this.doc.first) line = this.doc.first;
5088
+ else if (line > last) { line = last; end = true; }
5089
+ lineObj = getLine(this.doc, line);
5090
+ } else {
5091
+ lineObj = line;
5092
+ }
5093
+ return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top +
5094
+ (end ? this.doc.height - heightAtLine(lineObj) : 0);
5095
+ },
5096
+
5097
+ defaultTextHeight: function() { return textHeight(this.display); },
5098
+ defaultCharWidth: function() { return charWidth(this.display); },
5099
+
5100
+ setGutterMarker: methodOp(function(line, gutterID, value) {
5101
+ return changeLine(this.doc, line, "gutter", function(line) {
5102
+ var markers = line.gutterMarkers || (line.gutterMarkers = {});
5103
+ markers[gutterID] = value;
5104
+ if (!value && isEmpty(markers)) line.gutterMarkers = null;
5105
+ return true;
5106
+ });
5107
+ }),
5108
+
5109
+ clearGutter: methodOp(function(gutterID) {
5110
+ var cm = this, doc = cm.doc, i = doc.first;
5111
+ doc.iter(function(line) {
5112
+ if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
5113
+ line.gutterMarkers[gutterID] = null;
5114
+ regLineChange(cm, i, "gutter");
5115
+ if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null;
5116
+ }
5117
+ ++i;
5118
+ });
5119
+ }),
5120
+
5121
+ lineInfo: function(line) {
5122
+ if (typeof line == "number") {
5123
+ if (!isLine(this.doc, line)) return null;
5124
+ var n = line;
5125
+ line = getLine(this.doc, line);
5126
+ if (!line) return null;
5127
+ } else {
5128
+ var n = lineNo(line);
5129
+ if (n == null) return null;
5130
+ }
5131
+ return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers,
5132
+ textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass,
5133
+ widgets: line.widgets};
5134
+ },
5135
+
5136
+ getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};},
5137
+
5138
+ addWidget: function(pos, node, scroll, vert, horiz) {
5139
+ var display = this.display;
5140
+ pos = cursorCoords(this, clipPos(this.doc, pos));
5141
+ var top = pos.bottom, left = pos.left;
5142
+ node.style.position = "absolute";
5143
+ node.setAttribute("cm-ignore-events", "true");
5144
+ this.display.input.setUneditable(node);
5145
+ display.sizer.appendChild(node);
5146
+ if (vert == "over") {
5147
+ top = pos.top;
5148
+ } else if (vert == "above" || vert == "near") {
5149
+ var vspace = Math.max(display.wrapper.clientHeight, this.doc.height),
5150
+ hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth);
5151
+ // Default to positioning above (if specified and possible); otherwise default to positioning below
5152
+ if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight)
5153
+ top = pos.top - node.offsetHeight;
5154
+ else if (pos.bottom + node.offsetHeight <= vspace)
5155
+ top = pos.bottom;
5156
+ if (left + node.offsetWidth > hspace)
5157
+ left = hspace - node.offsetWidth;
5158
+ }
5159
+ node.style.top = top + "px";
5160
+ node.style.left = node.style.right = "";
5161
+ if (horiz == "right") {
5162
+ left = display.sizer.clientWidth - node.offsetWidth;
5163
+ node.style.right = "0px";
5164
+ } else {
5165
+ if (horiz == "left") left = 0;
5166
+ else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2;
5167
+ node.style.left = left + "px";
5168
+ }
5169
+ if (scroll)
5170
+ scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);
5171
+ },
5172
+
5173
+ triggerOnKeyDown: methodOp(onKeyDown),
5174
+ triggerOnKeyPress: methodOp(onKeyPress),
5175
+ triggerOnKeyUp: onKeyUp,
5176
+
5177
+ execCommand: function(cmd) {
5178
+ if (commands.hasOwnProperty(cmd))
5179
+ return commands[cmd].call(null, this);
5180
+ },
5181
+
5182
+ triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
5183
+
5184
+ findPosH: function(from, amount, unit, visually) {
5185
+ var dir = 1;
5186
+ if (amount < 0) { dir = -1; amount = -amount; }
5187
+ for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
5188
+ cur = findPosH(this.doc, cur, dir, unit, visually);
5189
+ if (cur.hitSide) break;
5190
+ }
5191
+ return cur;
5192
+ },
5193
+
5194
+ moveH: methodOp(function(dir, unit) {
5195
+ var cm = this;
5196
+ cm.extendSelectionsBy(function(range) {
5197
+ if (cm.display.shift || cm.doc.extend || range.empty())
5198
+ return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);
5199
+ else
5200
+ return dir < 0 ? range.from() : range.to();
5201
+ }, sel_move);
5202
+ }),
5203
+
5204
+ deleteH: methodOp(function(dir, unit) {
5205
+ var sel = this.doc.sel, doc = this.doc;
5206
+ if (sel.somethingSelected())
5207
+ doc.replaceSelection("", null, "+delete");
5208
+ else
5209
+ deleteNearSelection(this, function(range) {
5210
+ var other = findPosH(doc, range.head, dir, unit, false);
5211
+ return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other};
5212
+ });
5213
+ }),
5214
+
5215
+ findPosV: function(from, amount, unit, goalColumn) {
5216
+ var dir = 1, x = goalColumn;
5217
+ if (amount < 0) { dir = -1; amount = -amount; }
5218
+ for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) {
5219
+ var coords = cursorCoords(this, cur, "div");
5220
+ if (x == null) x = coords.left;
5221
+ else coords.left = x;
5222
+ cur = findPosV(this, coords, dir, unit);
5223
+ if (cur.hitSide) break;
5224
+ }
5225
+ return cur;
5226
+ },
5227
+
5228
+ moveV: methodOp(function(dir, unit) {
5229
+ var cm = this, doc = this.doc, goals = [];
5230
+ var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected();
5231
+ doc.extendSelectionsBy(function(range) {
5232
+ if (collapse)
5233
+ return dir < 0 ? range.from() : range.to();
5234
+ var headPos = cursorCoords(cm, range.head, "div");
5235
+ if (range.goalColumn != null) headPos.left = range.goalColumn;
5236
+ goals.push(headPos.left);
5237
+ var pos = findPosV(cm, headPos, dir, unit);
5238
+ if (unit == "page" && range == doc.sel.primary())
5239
+ addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);
5240
+ return pos;
5241
+ }, sel_move);
5242
+ if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++)
5243
+ doc.sel.ranges[i].goalColumn = goals[i];
5244
+ }),
5245
+
5246
+ // Find the word at the given position (as returned by coordsChar).
5247
+ findWordAt: function(pos) {
5248
+ var doc = this.doc, line = getLine(doc, pos.line).text;
5249
+ var start = pos.ch, end = pos.ch;
5250
+ if (line) {
5251
+ var helper = this.getHelper(pos, "wordChars");
5252
+ if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end;
5253
+ var startChar = line.charAt(start);
5254
+ var check = isWordChar(startChar, helper)
5255
+ ? function(ch) { return isWordChar(ch, helper); }
5256
+ : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);}
5257
+ : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);};
5258
+ while (start > 0 && check(line.charAt(start - 1))) --start;
5259
+ while (end < line.length && check(line.charAt(end))) ++end;
5260
+ }
5261
+ return new Range(Pos(pos.line, start), Pos(pos.line, end));
5262
+ },
5263
+
5264
+ toggleOverwrite: function(value) {
5265
+ if (value != null && value == this.state.overwrite) return;
5266
+ if (this.state.overwrite = !this.state.overwrite)
5267
+ addClass(this.display.cursorDiv, "CodeMirror-overwrite");
5268
+ else
5269
+ rmClass(this.display.cursorDiv, "CodeMirror-overwrite");
5270
+
5271
+ signal(this, "overwriteToggle", this, this.state.overwrite);
5272
+ },
5273
+ hasFocus: function() { return this.display.input.getField() == activeElt(); },
5274
+ isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit); },
5275
+
5276
+ scrollTo: methodOp(function(x, y) {
5277
+ if (x != null || y != null) resolveScrollToPos(this);
5278
+ if (x != null) this.curOp.scrollLeft = x;
5279
+ if (y != null) this.curOp.scrollTop = y;
5280
+ }),
5281
+ getScrollInfo: function() {
5282
+ var scroller = this.display.scroller;
5283
+ return {left: scroller.scrollLeft, top: scroller.scrollTop,
5284
+ height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
5285
+ width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
5286
+ clientHeight: displayHeight(this), clientWidth: displayWidth(this)};
5287
+ },
5288
+
5289
+ scrollIntoView: methodOp(function(range, margin) {
5290
+ if (range == null) {
5291
+ range = {from: this.doc.sel.primary().head, to: null};
5292
+ if (margin == null) margin = this.options.cursorScrollMargin;
5293
+ } else if (typeof range == "number") {
5294
+ range = {from: Pos(range, 0), to: null};
5295
+ } else if (range.from == null) {
5296
+ range = {from: range, to: null};
5297
+ }
5298
+ if (!range.to) range.to = range.from;
5299
+ range.margin = margin || 0;
5300
+
5301
+ if (range.from.line != null) {
5302
+ resolveScrollToPos(this);
5303
+ this.curOp.scrollToPos = range;
5304
+ } else {
5305
+ var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left),
5306
+ Math.min(range.from.top, range.to.top) - range.margin,
5307
+ Math.max(range.from.right, range.to.right),
5308
+ Math.max(range.from.bottom, range.to.bottom) + range.margin);
5309
+ this.scrollTo(sPos.scrollLeft, sPos.scrollTop);
5310
+ }
5311
+ }),
5312
+
5313
+ setSize: methodOp(function(width, height) {
5314
+ var cm = this;
5315
+ function interpret(val) {
5316
+ return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val;
5317
+ }
5318
+ if (width != null) cm.display.wrapper.style.width = interpret(width);
5319
+ if (height != null) cm.display.wrapper.style.height = interpret(height);
5320
+ if (cm.options.lineWrapping) clearLineMeasurementCache(this);
5321
+ var lineNo = cm.display.viewFrom;
5322
+ cm.doc.iter(lineNo, cm.display.viewTo, function(line) {
5323
+ if (line.widgets) for (var i = 0; i < line.widgets.length; i++)
5324
+ if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; }
5325
+ ++lineNo;
5326
+ });
5327
+ cm.curOp.forceUpdate = true;
5328
+ signal(cm, "refresh", this);
5329
+ }),
5330
+
5331
+ operation: function(f){return runInOp(this, f);},
5332
+
5333
+ refresh: methodOp(function() {
5334
+ var oldHeight = this.display.cachedTextHeight;
5335
+ regChange(this);
5336
+ this.curOp.forceUpdate = true;
5337
+ clearCaches(this);
5338
+ this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop);
5339
+ updateGutterSpace(this);
5340
+ if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5)
5341
+ estimateLineHeights(this);
5342
+ signal(this, "refresh", this);
5343
+ }),
5344
+
5345
+ swapDoc: methodOp(function(doc) {
5346
+ var old = this.doc;
5347
+ old.cm = null;
5348
+ attachDoc(this, doc);
5349
+ clearCaches(this);
5350
+ this.display.input.reset();
5351
+ this.scrollTo(doc.scrollLeft, doc.scrollTop);
5352
+ this.curOp.forceScroll = true;
5353
+ signalLater(this, "swapDoc", this, old);
5354
+ return old;
5355
+ }),
5356
+
5357
+ getInputField: function(){return this.display.input.getField();},
5358
+ getWrapperElement: function(){return this.display.wrapper;},
5359
+ getScrollerElement: function(){return this.display.scroller;},
5360
+ getGutterElement: function(){return this.display.gutters;}
5361
+ };
5362
+ eventMixin(CodeMirror);
5363
+
5364
+ // OPTION DEFAULTS
5365
+
5366
+ // The default configuration options.
5367
+ var defaults = CodeMirror.defaults = {};
5368
+ // Functions to run when options are changed.
5369
+ var optionHandlers = CodeMirror.optionHandlers = {};
5370
+
5371
+ function option(name, deflt, handle, notOnInit) {
5372
+ CodeMirror.defaults[name] = deflt;
5373
+ if (handle) optionHandlers[name] =
5374
+ notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle;
5375
+ }
5376
+
5377
+ // Passed to option handlers when there is no old value.
5378
+ var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}};
5379
+
5380
+ // These two are, on init, called from the constructor because they
5381
+ // have to be initialized before the editor can start at all.
5382
+ option("value", "", function(cm, val) {
5383
+ cm.setValue(val);
5384
+ }, true);
5385
+ option("mode", null, function(cm, val) {
5386
+ cm.doc.modeOption = val;
5387
+ loadMode(cm);
5388
+ }, true);
5389
+
5390
+ option("indentUnit", 2, loadMode, true);
5391
+ option("indentWithTabs", false);
5392
+ option("smartIndent", true);
5393
+ option("tabSize", 4, function(cm) {
5394
+ resetModeState(cm);
5395
+ clearCaches(cm);
5396
+ regChange(cm);
5397
+ }, true);
5398
+ option("lineSeparator", null, function(cm, val) {
5399
+ cm.doc.lineSep = val;
5400
+ if (!val) return;
5401
+ var newBreaks = [], lineNo = cm.doc.first;
5402
+ cm.doc.iter(function(line) {
5403
+ for (var pos = 0;;) {
5404
+ var found = line.text.indexOf(val, pos);
5405
+ if (found == -1) break;
5406
+ pos = found + val.length;
5407
+ newBreaks.push(Pos(lineNo, found));
5408
+ }
5409
+ lineNo++;
5410
+ });
5411
+ for (var i = newBreaks.length - 1; i >= 0; i--)
5412
+ replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length))
5413
+ });
5414
+ option("specialChars", /[\u0000-\u001f\u007f\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) {
5415
+ cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
5416
+ if (old != CodeMirror.Init) cm.refresh();
5417
+ });
5418
+ option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
5419
+ option("electricChars", true);
5420
+ option("inputStyle", mobile ? "contenteditable" : "textarea", function() {
5421
+ throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME
5422
+ }, true);
5423
+ option("rtlMoveVisually", !windows);
5424
+ option("wholeLineUpdateBefore", true);
5425
+
5426
+ option("theme", "default", function(cm) {
5427
+ themeChanged(cm);
5428
+ guttersChanged(cm);
5429
+ }, true);
5430
+ option("keyMap", "default", function(cm, val, old) {
5431
+ var next = getKeyMap(val);
5432
+ var prev = old != CodeMirror.Init && getKeyMap(old);
5433
+ if (prev && prev.detach) prev.detach(cm, next);
5434
+ if (next.attach) next.attach(cm, prev || null);
5435
+ });
5436
+ option("extraKeys", null);
5437
+
5438
+ option("lineWrapping", false, wrappingChanged, true);
5439
+ option("gutters", [], function(cm) {
5440
+ setGuttersForLineNumbers(cm.options);
5441
+ guttersChanged(cm);
5442
+ }, true);
5443
+ option("fixedGutter", true, function(cm, val) {
5444
+ cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0";
5445
+ cm.refresh();
5446
+ }, true);
5447
+ option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true);
5448
+ option("scrollbarStyle", "native", function(cm) {
5449
+ initScrollbars(cm);
5450
+ updateScrollbars(cm);
5451
+ cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
5452
+ cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
5453
+ }, true);
5454
+ option("lineNumbers", false, function(cm) {
5455
+ setGuttersForLineNumbers(cm.options);
5456
+ guttersChanged(cm);
5457
+ }, true);
5458
+ option("firstLineNumber", 1, guttersChanged, true);
5459
+ option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true);
5460
+ option("showCursorWhenSelecting", false, updateSelection, true);
5461
+
5462
+ option("resetSelectionOnContextMenu", true);
5463
+ option("lineWiseCopyCut", true);
5464
+
5465
+ option("readOnly", false, function(cm, val) {
5466
+ if (val == "nocursor") {
5467
+ onBlur(cm);
5468
+ cm.display.input.blur();
5469
+ cm.display.disabled = true;
5470
+ } else {
5471
+ cm.display.disabled = false;
5472
+ }
5473
+ cm.display.input.readOnlyChanged(val)
5474
+ });
5475
+ option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true);
5476
+ option("dragDrop", true, dragDropChanged);
5477
+ option("allowDropFileTypes", null);
5478
+
5479
+ option("cursorBlinkRate", 530);
5480
+ option("cursorScrollMargin", 0);
5481
+ option("cursorHeight", 1, updateSelection, true);
5482
+ option("singleCursorHeightPerLine", true, updateSelection, true);
5483
+ option("workTime", 100);
5484
+ option("workDelay", 100);
5485
+ option("flattenSpans", true, resetModeState, true);
5486
+ option("addModeClass", false, resetModeState, true);
5487
+ option("pollInterval", 100);
5488
+ option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;});
5489
+ option("historyEventDelay", 1250);
5490
+ option("viewportMargin", 10, function(cm){cm.refresh();}, true);
5491
+ option("maxHighlightLength", 10000, resetModeState, true);
5492
+ option("moveInputWithCursor", true, function(cm, val) {
5493
+ if (!val) cm.display.input.resetPosition();
5494
+ });
5495
+
5496
+ option("tabindex", null, function(cm, val) {
5497
+ cm.display.input.getField().tabIndex = val || "";
5498
+ });
5499
+ option("autofocus", null);
5500
+
5501
+ // MODE DEFINITION AND QUERYING
5502
+
5503
+ // Known modes, by name and by MIME
5504
+ var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {};
5505
+
5506
+ // Extra arguments are stored as the mode's dependencies, which is
5507
+ // used by (legacy) mechanisms like loadmode.js to automatically
5508
+ // load a mode. (Preferred mechanism is the require/define calls.)
5509
+ CodeMirror.defineMode = function(name, mode) {
5510
+ if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name;
5511
+ if (arguments.length > 2)
5512
+ mode.dependencies = Array.prototype.slice.call(arguments, 2);
5513
+ modes[name] = mode;
5514
+ };
5515
+
5516
+ CodeMirror.defineMIME = function(mime, spec) {
5517
+ mimeModes[mime] = spec;
5518
+ };
5519
+
5520
+ // Given a MIME type, a {name, ...options} config object, or a name
5521
+ // string, return a mode config object.
5522
+ CodeMirror.resolveMode = function(spec) {
5523
+ if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) {
5524
+ spec = mimeModes[spec];
5525
+ } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) {
5526
+ var found = mimeModes[spec.name];
5527
+ if (typeof found == "string") found = {name: found};
5528
+ spec = createObj(found, spec);
5529
+ spec.name = found.name;
5530
+ } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) {
5531
+ return CodeMirror.resolveMode("application/xml");
5532
+ }
5533
+ if (typeof spec == "string") return {name: spec};
5534
+ else return spec || {name: "null"};
5535
+ };
5536
+
5537
+ // Given a mode spec (anything that resolveMode accepts), find and
5538
+ // initialize an actual mode object.
5539
+ CodeMirror.getMode = function(options, spec) {
5540
+ var spec = CodeMirror.resolveMode(spec);
5541
+ var mfactory = modes[spec.name];
5542
+ if (!mfactory) return CodeMirror.getMode(options, "text/plain");
5543
+ var modeObj = mfactory(options, spec);
5544
+ if (modeExtensions.hasOwnProperty(spec.name)) {
5545
+ var exts = modeExtensions[spec.name];
5546
+ for (var prop in exts) {
5547
+ if (!exts.hasOwnProperty(prop)) continue;
5548
+ if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop];
5549
+ modeObj[prop] = exts[prop];
5550
+ }
5551
+ }
5552
+ modeObj.name = spec.name;
5553
+ if (spec.helperType) modeObj.helperType = spec.helperType;
5554
+ if (spec.modeProps) for (var prop in spec.modeProps)
5555
+ modeObj[prop] = spec.modeProps[prop];
5556
+
5557
+ return modeObj;
5558
+ };
5559
+
5560
+ // Minimal default mode.
5561
+ CodeMirror.defineMode("null", function() {
5562
+ return {token: function(stream) {stream.skipToEnd();}};
5563
+ });
5564
+ CodeMirror.defineMIME("text/plain", "null");
5565
+
5566
+ // This can be used to attach properties to mode objects from
5567
+ // outside the actual mode definition.
5568
+ var modeExtensions = CodeMirror.modeExtensions = {};
5569
+ CodeMirror.extendMode = function(mode, properties) {
5570
+ var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
5571
+ copyObj(properties, exts);
5572
+ };
5573
+
5574
+ // EXTENSIONS
5575
+
5576
+ CodeMirror.defineExtension = function(name, func) {
5577
+ CodeMirror.prototype[name] = func;
5578
+ };
5579
+ CodeMirror.defineDocExtension = function(name, func) {
5580
+ Doc.prototype[name] = func;
5581
+ };
5582
+ CodeMirror.defineOption = option;
5583
+
5584
+ var initHooks = [];
5585
+ CodeMirror.defineInitHook = function(f) {initHooks.push(f);};
5586
+
5587
+ var helpers = CodeMirror.helpers = {};
5588
+ CodeMirror.registerHelper = function(type, name, value) {
5589
+ if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []};
5590
+ helpers[type][name] = value;
5591
+ };
5592
+ CodeMirror.registerGlobalHelper = function(type, name, predicate, value) {
5593
+ CodeMirror.registerHelper(type, name, value);
5594
+ helpers[type]._global.push({pred: predicate, val: value});
5595
+ };
5596
+
5597
+ // MODE STATE HANDLING
5598
+
5599
+ // Utility functions for working with state. Exported because nested
5600
+ // modes need to do this for their inner modes.
5601
+
5602
+ var copyState = CodeMirror.copyState = function(mode, state) {
5603
+ if (state === true) return state;
5604
+ if (mode.copyState) return mode.copyState(state);
5605
+ var nstate = {};
5606
+ for (var n in state) {
5607
+ var val = state[n];
5608
+ if (val instanceof Array) val = val.concat([]);
5609
+ nstate[n] = val;
5610
+ }
5611
+ return nstate;
5612
+ };
5613
+
5614
+ var startState = CodeMirror.startState = function(mode, a1, a2) {
5615
+ return mode.startState ? mode.startState(a1, a2) : true;
5616
+ };
5617
+
5618
+ // Given a mode and a state (for that mode), find the inner mode and
5619
+ // state at the position that the state refers to.
5620
+ CodeMirror.innerMode = function(mode, state) {
5621
+ while (mode.innerMode) {
5622
+ var info = mode.innerMode(state);
5623
+ if (!info || info.mode == mode) break;
5624
+ state = info.state;
5625
+ mode = info.mode;
5626
+ }
5627
+ return info || {mode: mode, state: state};
5628
+ };
5629
+
5630
+ // STANDARD COMMANDS
5631
+
5632
+ // Commands are parameter-less actions that can be performed on an
5633
+ // editor, mostly used for keybindings.
5634
+ var commands = CodeMirror.commands = {
5635
+ selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);},
5636
+ singleSelection: function(cm) {
5637
+ cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll);
5638
+ },
5639
+ killLine: function(cm) {
5640
+ deleteNearSelection(cm, function(range) {
5641
+ if (range.empty()) {
5642
+ var len = getLine(cm.doc, range.head.line).text.length;
5643
+ if (range.head.ch == len && range.head.line < cm.lastLine())
5644
+ return {from: range.head, to: Pos(range.head.line + 1, 0)};
5645
+ else
5646
+ return {from: range.head, to: Pos(range.head.line, len)};
5647
+ } else {
5648
+ return {from: range.from(), to: range.to()};
5649
+ }
5650
+ });
5651
+ },
5652
+ deleteLine: function(cm) {
5653
+ deleteNearSelection(cm, function(range) {
5654
+ return {from: Pos(range.from().line, 0),
5655
+ to: clipPos(cm.doc, Pos(range.to().line + 1, 0))};
5656
+ });
5657
+ },
5658
+ delLineLeft: function(cm) {
5659
+ deleteNearSelection(cm, function(range) {
5660
+ return {from: Pos(range.from().line, 0), to: range.from()};
5661
+ });
5662
+ },
5663
+ delWrappedLineLeft: function(cm) {
5664
+ deleteNearSelection(cm, function(range) {
5665
+ var top = cm.charCoords(range.head, "div").top + 5;
5666
+ var leftPos = cm.coordsChar({left: 0, top: top}, "div");
5667
+ return {from: leftPos, to: range.from()};
5668
+ });
5669
+ },
5670
+ delWrappedLineRight: function(cm) {
5671
+ deleteNearSelection(cm, function(range) {
5672
+ var top = cm.charCoords(range.head, "div").top + 5;
5673
+ var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
5674
+ return {from: range.from(), to: rightPos };
5675
+ });
5676
+ },
5677
+ undo: function(cm) {cm.undo();},
5678
+ redo: function(cm) {cm.redo();},
5679
+ undoSelection: function(cm) {cm.undoSelection();},
5680
+ redoSelection: function(cm) {cm.redoSelection();},
5681
+ goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));},
5682
+ goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));},
5683
+ goLineStart: function(cm) {
5684
+ cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); },
5685
+ {origin: "+move", bias: 1});
5686
+ },
5687
+ goLineStartSmart: function(cm) {
5688
+ cm.extendSelectionsBy(function(range) {
5689
+ return lineStartSmart(cm, range.head);
5690
+ }, {origin: "+move", bias: 1});
5691
+ },
5692
+ goLineEnd: function(cm) {
5693
+ cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); },
5694
+ {origin: "+move", bias: -1});
5695
+ },
5696
+ goLineRight: function(cm) {
5697
+ cm.extendSelectionsBy(function(range) {
5698
+ var top = cm.charCoords(range.head, "div").top + 5;
5699
+ return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
5700
+ }, sel_move);
5701
+ },
5702
+ goLineLeft: function(cm) {
5703
+ cm.extendSelectionsBy(function(range) {
5704
+ var top = cm.charCoords(range.head, "div").top + 5;
5705
+ return cm.coordsChar({left: 0, top: top}, "div");
5706
+ }, sel_move);
5707
+ },
5708
+ goLineLeftSmart: function(cm) {
5709
+ cm.extendSelectionsBy(function(range) {
5710
+ var top = cm.charCoords(range.head, "div").top + 5;
5711
+ var pos = cm.coordsChar({left: 0, top: top}, "div");
5712
+ if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head);
5713
+ return pos;
5714
+ }, sel_move);
5715
+ },
5716
+ goLineUp: function(cm) {cm.moveV(-1, "line");},
5717
+ goLineDown: function(cm) {cm.moveV(1, "line");},
5718
+ goPageUp: function(cm) {cm.moveV(-1, "page");},
5719
+ goPageDown: function(cm) {cm.moveV(1, "page");},
5720
+ goCharLeft: function(cm) {cm.moveH(-1, "char");},
5721
+ goCharRight: function(cm) {cm.moveH(1, "char");},
5722
+ goColumnLeft: function(cm) {cm.moveH(-1, "column");},
5723
+ goColumnRight: function(cm) {cm.moveH(1, "column");},
5724
+ goWordLeft: function(cm) {cm.moveH(-1, "word");},
5725
+ goGroupRight: function(cm) {cm.moveH(1, "group");},
5726
+ goGroupLeft: function(cm) {cm.moveH(-1, "group");},
5727
+ goWordRight: function(cm) {cm.moveH(1, "word");},
5728
+ delCharBefore: function(cm) {cm.deleteH(-1, "char");},
5729
+ delCharAfter: function(cm) {cm.deleteH(1, "char");},
5730
+ delWordBefore: function(cm) {cm.deleteH(-1, "word");},
5731
+ delWordAfter: function(cm) {cm.deleteH(1, "word");},
5732
+ delGroupBefore: function(cm) {cm.deleteH(-1, "group");},
5733
+ delGroupAfter: function(cm) {cm.deleteH(1, "group");},
5734
+ indentAuto: function(cm) {cm.indentSelection("smart");},
5735
+ indentMore: function(cm) {cm.indentSelection("add");},
5736
+ indentLess: function(cm) {cm.indentSelection("subtract");},
5737
+ insertTab: function(cm) {cm.replaceSelection("\t");},
5738
+ insertSoftTab: function(cm) {
5739
+ var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
5740
+ for (var i = 0; i < ranges.length; i++) {
5741
+ var pos = ranges[i].from();
5742
+ var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
5743
+ spaces.push(spaceStr(tabSize - col % tabSize));
5744
+ }
5745
+ cm.replaceSelections(spaces);
5746
+ },
5747
+ defaultTab: function(cm) {
5748
+ if (cm.somethingSelected()) cm.indentSelection("add");
5749
+ else cm.execCommand("insertTab");
5750
+ },
5751
+ transposeChars: function(cm) {
5752
+ runInOp(cm, function() {
5753
+ var ranges = cm.listSelections(), newSel = [];
5754
+ for (var i = 0; i < ranges.length; i++) {
5755
+ var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
5756
+ if (line) {
5757
+ if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1);
5758
+ if (cur.ch > 0) {
5759
+ cur = new Pos(cur.line, cur.ch + 1);
5760
+ cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
5761
+ Pos(cur.line, cur.ch - 2), cur, "+transpose");
5762
+ } else if (cur.line > cm.doc.first) {
5763
+ var prev = getLine(cm.doc, cur.line - 1).text;
5764
+ if (prev)
5765
+ cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
5766
+ prev.charAt(prev.length - 1),
5767
+ Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose");
5768
+ }
5769
+ }
5770
+ newSel.push(new Range(cur, cur));
5771
+ }
5772
+ cm.setSelections(newSel);
5773
+ });
5774
+ },
5775
+ newlineAndIndent: function(cm) {
5776
+ runInOp(cm, function() {
5777
+ var len = cm.listSelections().length;
5778
+ for (var i = 0; i < len; i++) {
5779
+ var range = cm.listSelections()[i];
5780
+ cm.replaceRange(cm.doc.lineSeparator(), range.anchor, range.head, "+input");
5781
+ cm.indentLine(range.from().line + 1, null, true);
5782
+ }
5783
+ ensureCursorVisible(cm);
5784
+ });
5785
+ },
5786
+ openLine: function(cm) {cm.replaceSelection("\n", "start")},
5787
+ toggleOverwrite: function(cm) {cm.toggleOverwrite();}
5788
+ };
5789
+
5790
+
5791
+ // STANDARD KEYMAPS
5792
+
5793
+ var keyMap = CodeMirror.keyMap = {};
5794
+
5795
+ keyMap.basic = {
5796
+ "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown",
5797
+ "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown",
5798
+ "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore",
5799
+ "Tab": "defaultTab", "Shift-Tab": "indentAuto",
5800
+ "Enter": "newlineAndIndent", "Insert": "toggleOverwrite",
5801
+ "Esc": "singleSelection"
5802
+ };
5803
+ // Note that the save and find-related commands aren't defined by
5804
+ // default. User code or addons can define them. Unknown commands
5805
+ // are simply ignored.
5806
+ keyMap.pcDefault = {
5807
+ "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo",
5808
+ "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
5809
+ "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd",
5810
+ "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find",
5811
+ "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll",
5812
+ "Ctrl-[": "indentLess", "Ctrl-]": "indentMore",
5813
+ "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection",
5814
+ fallthrough: "basic"
5815
+ };
5816
+ // Very basic readline/emacs-style bindings, which are standard on Mac.
5817
+ keyMap.emacsy = {
5818
+ "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown",
5819
+ "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
5820
+ "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore",
5821
+ "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars",
5822
+ "Ctrl-O": "openLine"
5823
+ };
5824
+ keyMap.macDefault = {
5825
+ "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
5826
+ "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
5827
+ "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore",
5828
+ "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find",
5829
+ "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll",
5830
+ "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
5831
+ "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
5832
+ fallthrough: ["basic", "emacsy"]
5833
+ };
5834
+ keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
5835
+
5836
+ // KEYMAP DISPATCH
5837
+
5838
+ function normalizeKeyName(name) {
5839
+ var parts = name.split(/-(?!$)/), name = parts[parts.length - 1];
5840
+ var alt, ctrl, shift, cmd;
5841
+ for (var i = 0; i < parts.length - 1; i++) {
5842
+ var mod = parts[i];
5843
+ if (/^(cmd|meta|m)$/i.test(mod)) cmd = true;
5844
+ else if (/^a(lt)?$/i.test(mod)) alt = true;
5845
+ else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true;
5846
+ else if (/^s(hift)$/i.test(mod)) shift = true;
5847
+ else throw new Error("Unrecognized modifier name: " + mod);
5848
+ }
5849
+ if (alt) name = "Alt-" + name;
5850
+ if (ctrl) name = "Ctrl-" + name;
5851
+ if (cmd) name = "Cmd-" + name;
5852
+ if (shift) name = "Shift-" + name;
5853
+ return name;
5854
+ }
5855
+
5856
+ // This is a kludge to keep keymaps mostly working as raw objects
5857
+ // (backwards compatibility) while at the same time support features
5858
+ // like normalization and multi-stroke key bindings. It compiles a
5859
+ // new normalized keymap, and then updates the old object to reflect
5860
+ // this.
5861
+ CodeMirror.normalizeKeyMap = function(keymap) {
5862
+ var copy = {};
5863
+ for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) {
5864
+ var value = keymap[keyname];
5865
+ if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue;
5866
+ if (value == "...") { delete keymap[keyname]; continue; }
5867
+
5868
+ var keys = map(keyname.split(" "), normalizeKeyName);
5869
+ for (var i = 0; i < keys.length; i++) {
5870
+ var val, name;
5871
+ if (i == keys.length - 1) {
5872
+ name = keys.join(" ");
5873
+ val = value;
5874
+ } else {
5875
+ name = keys.slice(0, i + 1).join(" ");
5876
+ val = "...";
5877
+ }
5878
+ var prev = copy[name];
5879
+ if (!prev) copy[name] = val;
5880
+ else if (prev != val) throw new Error("Inconsistent bindings for " + name);
5881
+ }
5882
+ delete keymap[keyname];
5883
+ }
5884
+ for (var prop in copy) keymap[prop] = copy[prop];
5885
+ return keymap;
5886
+ };
5887
+
5888
+ var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) {
5889
+ map = getKeyMap(map);
5890
+ var found = map.call ? map.call(key, context) : map[key];
5891
+ if (found === false) return "nothing";
5892
+ if (found === "...") return "multi";
5893
+ if (found != null && handle(found)) return "handled";
5894
+
5895
+ if (map.fallthrough) {
5896
+ if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
5897
+ return lookupKey(key, map.fallthrough, handle, context);
5898
+ for (var i = 0; i < map.fallthrough.length; i++) {
5899
+ var result = lookupKey(key, map.fallthrough[i], handle, context);
5900
+ if (result) return result;
5901
+ }
5902
+ }
5903
+ };
5904
+
5905
+ // Modifier key presses don't count as 'real' key presses for the
5906
+ // purpose of keymap fallthrough.
5907
+ var isModifierKey = CodeMirror.isModifierKey = function(value) {
5908
+ var name = typeof value == "string" ? value : keyNames[value.keyCode];
5909
+ return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod";
5910
+ };
5911
+
5912
+ // Look up the name of a key as indicated by an event object.
5913
+ var keyName = CodeMirror.keyName = function(event, noShift) {
5914
+ if (presto && event.keyCode == 34 && event["char"]) return false;
5915
+ var base = keyNames[event.keyCode], name = base;
5916
+ if (name == null || event.altGraphKey) return false;
5917
+ if (event.altKey && base != "Alt") name = "Alt-" + name;
5918
+ if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name;
5919
+ if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name;
5920
+ if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name;
5921
+ return name;
5922
+ };
5923
+
5924
+ function getKeyMap(val) {
5925
+ return typeof val == "string" ? keyMap[val] : val;
5926
+ }
5927
+
5928
+ // FROMTEXTAREA
5929
+
5930
+ CodeMirror.fromTextArea = function(textarea, options) {
5931
+ options = options ? copyObj(options) : {};
5932
+ options.value = textarea.value;
5933
+ if (!options.tabindex && textarea.tabIndex)
5934
+ options.tabindex = textarea.tabIndex;
5935
+ if (!options.placeholder && textarea.placeholder)
5936
+ options.placeholder = textarea.placeholder;
5937
+ // Set autofocus to true if this textarea is focused, or if it has
5938
+ // autofocus and no other element is focused.
5939
+ if (options.autofocus == null) {
5940
+ var hasFocus = activeElt();
5941
+ options.autofocus = hasFocus == textarea ||
5942
+ textarea.getAttribute("autofocus") != null && hasFocus == document.body;
5943
+ }
5944
+
5945
+ function save() {textarea.value = cm.getValue();}
5946
+ if (textarea.form) {
5947
+ on(textarea.form, "submit", save);
5948
+ // Deplorable hack to make the submit method do the right thing.
5949
+ if (!options.leaveSubmitMethodAlone) {
5950
+ var form = textarea.form, realSubmit = form.submit;
5951
+ try {
5952
+ var wrappedSubmit = form.submit = function() {
5953
+ save();
5954
+ form.submit = realSubmit;
5955
+ form.submit();
5956
+ form.submit = wrappedSubmit;
5957
+ };
5958
+ } catch(e) {}
5959
+ }
5960
+ }
5961
+
5962
+ options.finishInit = function(cm) {
5963
+ cm.save = save;
5964
+ cm.getTextArea = function() { return textarea; };
5965
+ cm.toTextArea = function() {
5966
+ cm.toTextArea = isNaN; // Prevent this from being ran twice
5967
+ save();
5968
+ textarea.parentNode.removeChild(cm.getWrapperElement());
5969
+ textarea.style.display = "";
5970
+ if (textarea.form) {
5971
+ off(textarea.form, "submit", save);
5972
+ if (typeof textarea.form.submit == "function")
5973
+ textarea.form.submit = realSubmit;
5974
+ }
5975
+ };
5976
+ };
5977
+
5978
+ textarea.style.display = "none";
5979
+ var cm = CodeMirror(function(node) {
5980
+ textarea.parentNode.insertBefore(node, textarea.nextSibling);
5981
+ }, options);
5982
+ return cm;
5983
+ };
5984
+
5985
+ // STRING STREAM
5986
+
5987
+ // Fed to the mode parsers, provides helper functions to make
5988
+ // parsers more succinct.
5989
+
5990
+ var StringStream = CodeMirror.StringStream = function(string, tabSize) {
5991
+ this.pos = this.start = 0;
5992
+ this.string = string;
5993
+ this.tabSize = tabSize || 8;
5994
+ this.lastColumnPos = this.lastColumnValue = 0;
5995
+ this.lineStart = 0;
5996
+ };
5997
+
5998
+ StringStream.prototype = {
5999
+ eol: function() {return this.pos >= this.string.length;},
6000
+ sol: function() {return this.pos == this.lineStart;},
6001
+ peek: function() {return this.string.charAt(this.pos) || undefined;},
6002
+ next: function() {
6003
+ if (this.pos < this.string.length)
6004
+ return this.string.charAt(this.pos++);
6005
+ },
6006
+ eat: function(match) {
6007
+ var ch = this.string.charAt(this.pos);
6008
+ if (typeof match == "string") var ok = ch == match;
6009
+ else var ok = ch && (match.test ? match.test(ch) : match(ch));
6010
+ if (ok) {++this.pos; return ch;}
6011
+ },
6012
+ eatWhile: function(match) {
6013
+ var start = this.pos;
6014
+ while (this.eat(match)){}
6015
+ return this.pos > start;
6016
+ },
6017
+ eatSpace: function() {
6018
+ var start = this.pos;
6019
+ while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos;
6020
+ return this.pos > start;
6021
+ },
6022
+ skipToEnd: function() {this.pos = this.string.length;},
6023
+ skipTo: function(ch) {
6024
+ var found = this.string.indexOf(ch, this.pos);
6025
+ if (found > -1) {this.pos = found; return true;}
6026
+ },
6027
+ backUp: function(n) {this.pos -= n;},
6028
+ column: function() {
6029
+ if (this.lastColumnPos < this.start) {
6030
+ this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue);
6031
+ this.lastColumnPos = this.start;
6032
+ }
6033
+ return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
6034
+ },
6035
+ indentation: function() {
6036
+ return countColumn(this.string, null, this.tabSize) -
6037
+ (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0);
6038
+ },
6039
+ match: function(pattern, consume, caseInsensitive) {
6040
+ if (typeof pattern == "string") {
6041
+ var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;};
6042
+ var substr = this.string.substr(this.pos, pattern.length);
6043
+ if (cased(substr) == cased(pattern)) {
6044
+ if (consume !== false) this.pos += pattern.length;
6045
+ return true;
6046
+ }
6047
+ } else {
6048
+ var match = this.string.slice(this.pos).match(pattern);
6049
+ if (match && match.index > 0) return null;
6050
+ if (match && consume !== false) this.pos += match[0].length;
6051
+ return match;
6052
+ }
6053
+ },
6054
+ current: function(){return this.string.slice(this.start, this.pos);},
6055
+ hideFirstChars: function(n, inner) {
6056
+ this.lineStart += n;
6057
+ try { return inner(); }
6058
+ finally { this.lineStart -= n; }
6059
+ }
6060
+ };
6061
+
6062
+ // TEXTMARKERS
6063
+
6064
+ // Created with markText and setBookmark methods. A TextMarker is a
6065
+ // handle that can be used to clear or find a marked position in the
6066
+ // document. Line objects hold arrays (markedSpans) containing
6067
+ // {from, to, marker} object pointing to such marker objects, and
6068
+ // indicating that such a marker is present on that line. Multiple
6069
+ // lines may point to the same marker when it spans across lines.
6070
+ // The spans will have null for their from/to properties when the
6071
+ // marker continues beyond the start/end of the line. Markers have
6072
+ // links back to the lines they currently touch.
6073
+
6074
+ var nextMarkerId = 0;
6075
+
6076
+ var TextMarker = CodeMirror.TextMarker = function(doc, type) {
6077
+ this.lines = [];
6078
+ this.type = type;
6079
+ this.doc = doc;
6080
+ this.id = ++nextMarkerId;
6081
+ };
6082
+ eventMixin(TextMarker);
6083
+
6084
+ // Clear the marker.
6085
+ TextMarker.prototype.clear = function() {
6086
+ if (this.explicitlyCleared) return;
6087
+ var cm = this.doc.cm, withOp = cm && !cm.curOp;
6088
+ if (withOp) startOperation(cm);
6089
+ if (hasHandler(this, "clear")) {
6090
+ var found = this.find();
6091
+ if (found) signalLater(this, "clear", found.from, found.to);
6092
+ }
6093
+ var min = null, max = null;
6094
+ for (var i = 0; i < this.lines.length; ++i) {
6095
+ var line = this.lines[i];
6096
+ var span = getMarkedSpanFor(line.markedSpans, this);
6097
+ if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text");
6098
+ else if (cm) {
6099
+ if (span.to != null) max = lineNo(line);
6100
+ if (span.from != null) min = lineNo(line);
6101
+ }
6102
+ line.markedSpans = removeMarkedSpan(line.markedSpans, span);
6103
+ if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm)
6104
+ updateLineHeight(line, textHeight(cm.display));
6105
+ }
6106
+ if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) {
6107
+ var visual = visualLine(this.lines[i]), len = lineLength(visual);
6108
+ if (len > cm.display.maxLineLength) {
6109
+ cm.display.maxLine = visual;
6110
+ cm.display.maxLineLength = len;
6111
+ cm.display.maxLineChanged = true;
6112
+ }
6113
+ }
6114
+
6115
+ if (min != null && cm && this.collapsed) regChange(cm, min, max + 1);
6116
+ this.lines.length = 0;
6117
+ this.explicitlyCleared = true;
6118
+ if (this.atomic && this.doc.cantEdit) {
6119
+ this.doc.cantEdit = false;
6120
+ if (cm) reCheckSelection(cm.doc);
6121
+ }
6122
+ if (cm) signalLater(cm, "markerCleared", cm, this);
6123
+ if (withOp) endOperation(cm);
6124
+ if (this.parent) this.parent.clear();
6125
+ };
6126
+
6127
+ // Find the position of the marker in the document. Returns a {from,
6128
+ // to} object by default. Side can be passed to get a specific side
6129
+ // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the
6130
+ // Pos objects returned contain a line object, rather than a line
6131
+ // number (used to prevent looking up the same line twice).
6132
+ TextMarker.prototype.find = function(side, lineObj) {
6133
+ if (side == null && this.type == "bookmark") side = 1;
6134
+ var from, to;
6135
+ for (var i = 0; i < this.lines.length; ++i) {
6136
+ var line = this.lines[i];
6137
+ var span = getMarkedSpanFor(line.markedSpans, this);
6138
+ if (span.from != null) {
6139
+ from = Pos(lineObj ? line : lineNo(line), span.from);
6140
+ if (side == -1) return from;
6141
+ }
6142
+ if (span.to != null) {
6143
+ to = Pos(lineObj ? line : lineNo(line), span.to);
6144
+ if (side == 1) return to;
6145
+ }
6146
+ }
6147
+ return from && {from: from, to: to};
6148
+ };
6149
+
6150
+ // Signals that the marker's widget changed, and surrounding layout
6151
+ // should be recomputed.
6152
+ TextMarker.prototype.changed = function() {
6153
+ var pos = this.find(-1, true), widget = this, cm = this.doc.cm;
6154
+ if (!pos || !cm) return;
6155
+ runInOp(cm, function() {
6156
+ var line = pos.line, lineN = lineNo(pos.line);
6157
+ var view = findViewForLine(cm, lineN);
6158
+ if (view) {
6159
+ clearLineMeasurementCacheFor(view);
6160
+ cm.curOp.selectionChanged = cm.curOp.forceUpdate = true;
6161
+ }
6162
+ cm.curOp.updateMaxLine = true;
6163
+ if (!lineIsHidden(widget.doc, line) && widget.height != null) {
6164
+ var oldHeight = widget.height;
6165
+ widget.height = null;
6166
+ var dHeight = widgetHeight(widget) - oldHeight;
6167
+ if (dHeight)
6168
+ updateLineHeight(line, line.height + dHeight);
6169
+ }
6170
+ });
6171
+ };
6172
+
6173
+ TextMarker.prototype.attachLine = function(line) {
6174
+ if (!this.lines.length && this.doc.cm) {
6175
+ var op = this.doc.cm.curOp;
6176
+ if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1)
6177
+ (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);
6178
+ }
6179
+ this.lines.push(line);
6180
+ };
6181
+ TextMarker.prototype.detachLine = function(line) {
6182
+ this.lines.splice(indexOf(this.lines, line), 1);
6183
+ if (!this.lines.length && this.doc.cm) {
6184
+ var op = this.doc.cm.curOp;
6185
+ (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this);
6186
+ }
6187
+ };
6188
+
6189
+ // Collapsed markers have unique ids, in order to be able to order
6190
+ // them, which is needed for uniquely determining an outer marker
6191
+ // when they overlap (they may nest, but not partially overlap).
6192
+ var nextMarkerId = 0;
6193
+
6194
+ // Create a marker, wire it up to the right lines, and
6195
+ function markText(doc, from, to, options, type) {
6196
+ // Shared markers (across linked documents) are handled separately
6197
+ // (markTextShared will call out to this again, once per
6198
+ // document).
6199
+ if (options && options.shared) return markTextShared(doc, from, to, options, type);
6200
+ // Ensure we are in an operation.
6201
+ if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type);
6202
+
6203
+ var marker = new TextMarker(doc, type), diff = cmp(from, to);
6204
+ if (options) copyObj(options, marker, false);
6205
+ // Don't connect empty markers unless clearWhenEmpty is false
6206
+ if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false)
6207
+ return marker;
6208
+ if (marker.replacedWith) {
6209
+ // Showing up as a widget implies collapsed (widget replaces text)
6210
+ marker.collapsed = true;
6211
+ marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget");
6212
+ if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true");
6213
+ if (options.insertLeft) marker.widgetNode.insertLeft = true;
6214
+ }
6215
+ if (marker.collapsed) {
6216
+ if (conflictingCollapsedRange(doc, from.line, from, to, marker) ||
6217
+ from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker))
6218
+ throw new Error("Inserting collapsed marker partially overlapping an existing one");
6219
+ sawCollapsedSpans = true;
6220
+ }
6221
+
6222
+ if (marker.addToHistory)
6223
+ addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);
6224
+
6225
+ var curLine = from.line, cm = doc.cm, updateMaxLine;
6226
+ doc.iter(curLine, to.line + 1, function(line) {
6227
+ if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine)
6228
+ updateMaxLine = true;
6229
+ if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0);
6230
+ addMarkedSpan(line, new MarkedSpan(marker,
6231
+ curLine == from.line ? from.ch : null,
6232
+ curLine == to.line ? to.ch : null));
6233
+ ++curLine;
6234
+ });
6235
+ // lineIsHidden depends on the presence of the spans, so needs a second pass
6236
+ if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) {
6237
+ if (lineIsHidden(doc, line)) updateLineHeight(line, 0);
6238
+ });
6239
+
6240
+ if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); });
6241
+
6242
+ if (marker.readOnly) {
6243
+ sawReadOnlySpans = true;
6244
+ if (doc.history.done.length || doc.history.undone.length)
6245
+ doc.clearHistory();
6246
+ }
6247
+ if (marker.collapsed) {
6248
+ marker.id = ++nextMarkerId;
6249
+ marker.atomic = true;
6250
+ }
6251
+ if (cm) {
6252
+ // Sync editor state
6253
+ if (updateMaxLine) cm.curOp.updateMaxLine = true;
6254
+ if (marker.collapsed)
6255
+ regChange(cm, from.line, to.line + 1);
6256
+ else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css)
6257
+ for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");
6258
+ if (marker.atomic) reCheckSelection(cm.doc);
6259
+ signalLater(cm, "markerAdded", cm, marker);
6260
+ }
6261
+ return marker;
6262
+ }
6263
+
6264
+ // SHARED TEXTMARKERS
6265
+
6266
+ // A shared marker spans multiple linked documents. It is
6267
+ // implemented as a meta-marker-object controlling multiple normal
6268
+ // markers.
6269
+ var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) {
6270
+ this.markers = markers;
6271
+ this.primary = primary;
6272
+ for (var i = 0; i < markers.length; ++i)
6273
+ markers[i].parent = this;
6274
+ };
6275
+ eventMixin(SharedTextMarker);
6276
+
6277
+ SharedTextMarker.prototype.clear = function() {
6278
+ if (this.explicitlyCleared) return;
6279
+ this.explicitlyCleared = true;
6280
+ for (var i = 0; i < this.markers.length; ++i)
6281
+ this.markers[i].clear();
6282
+ signalLater(this, "clear");
6283
+ };
6284
+ SharedTextMarker.prototype.find = function(side, lineObj) {
6285
+ return this.primary.find(side, lineObj);
6286
+ };
6287
+
6288
+ function markTextShared(doc, from, to, options, type) {
6289
+ options = copyObj(options);
6290
+ options.shared = false;
6291
+ var markers = [markText(doc, from, to, options, type)], primary = markers[0];
6292
+ var widget = options.widgetNode;
6293
+ linkedDocs(doc, function(doc) {
6294
+ if (widget) options.widgetNode = widget.cloneNode(true);
6295
+ markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type));
6296
+ for (var i = 0; i < doc.linked.length; ++i)
6297
+ if (doc.linked[i].isParent) return;
6298
+ primary = lst(markers);
6299
+ });
6300
+ return new SharedTextMarker(markers, primary);
6301
+ }
6302
+
6303
+ function findSharedMarkers(doc) {
6304
+ return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())),
6305
+ function(m) { return m.parent; });
6306
+ }
6307
+
6308
+ function copySharedMarkers(doc, markers) {
6309
+ for (var i = 0; i < markers.length; i++) {
6310
+ var marker = markers[i], pos = marker.find();
6311
+ var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
6312
+ if (cmp(mFrom, mTo)) {
6313
+ var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
6314
+ marker.markers.push(subMark);
6315
+ subMark.parent = marker;
6316
+ }
6317
+ }
6318
+ }
6319
+
6320
+ function detachSharedMarkers(markers) {
6321
+ for (var i = 0; i < markers.length; i++) {
6322
+ var marker = markers[i], linked = [marker.primary.doc];;
6323
+ linkedDocs(marker.primary.doc, function(d) { linked.push(d); });
6324
+ for (var j = 0; j < marker.markers.length; j++) {
6325
+ var subMarker = marker.markers[j];
6326
+ if (indexOf(linked, subMarker.doc) == -1) {
6327
+ subMarker.parent = null;
6328
+ marker.markers.splice(j--, 1);
6329
+ }
6330
+ }
6331
+ }
6332
+ }
6333
+
6334
+ // TEXTMARKER SPANS
6335
+
6336
+ function MarkedSpan(marker, from, to) {
6337
+ this.marker = marker;
6338
+ this.from = from; this.to = to;
6339
+ }
6340
+
6341
+ // Search an array of spans for a span matching the given marker.
6342
+ function getMarkedSpanFor(spans, marker) {
6343
+ if (spans) for (var i = 0; i < spans.length; ++i) {
6344
+ var span = spans[i];
6345
+ if (span.marker == marker) return span;
6346
+ }
6347
+ }
6348
+ // Remove a span from an array, returning undefined if no spans are
6349
+ // left (we don't store arrays for lines without spans).
6350
+ function removeMarkedSpan(spans, span) {
6351
+ for (var r, i = 0; i < spans.length; ++i)
6352
+ if (spans[i] != span) (r || (r = [])).push(spans[i]);
6353
+ return r;
6354
+ }
6355
+ // Add a span to a line.
6356
+ function addMarkedSpan(line, span) {
6357
+ line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span];
6358
+ span.marker.attachLine(line);
6359
+ }
6360
+
6361
+ // Used for the algorithm that adjusts markers for a change in the
6362
+ // document. These functions cut an array of spans at a given
6363
+ // character position, returning an array of remaining chunks (or
6364
+ // undefined if nothing remains).
6365
+ function markedSpansBefore(old, startCh, isInsert) {
6366
+ if (old) for (var i = 0, nw; i < old.length; ++i) {
6367
+ var span = old[i], marker = span.marker;
6368
+ var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh);
6369
+ if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) {
6370
+ var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh);
6371
+ (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to));
6372
+ }
6373
+ }
6374
+ return nw;
6375
+ }
6376
+ function markedSpansAfter(old, endCh, isInsert) {
6377
+ if (old) for (var i = 0, nw; i < old.length; ++i) {
6378
+ var span = old[i], marker = span.marker;
6379
+ var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh);
6380
+ if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) {
6381
+ var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh);
6382
+ (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh,
6383
+ span.to == null ? null : span.to - endCh));
6384
+ }
6385
+ }
6386
+ return nw;
6387
+ }
6388
+
6389
+ // Given a change object, compute the new set of marker spans that
6390
+ // cover the line in which the change took place. Removes spans
6391
+ // entirely within the change, reconnects spans belonging to the
6392
+ // same marker that appear on both sides of the change, and cuts off
6393
+ // spans partially within the change. Returns an array of span
6394
+ // arrays with one element for each line in (after) the change.
6395
+ function stretchSpansOverChange(doc, change) {
6396
+ if (change.full) return null;
6397
+ var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans;
6398
+ var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans;
6399
+ if (!oldFirst && !oldLast) return null;
6400
+
6401
+ var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0;
6402
+ // Get the spans that 'stick out' on both sides
6403
+ var first = markedSpansBefore(oldFirst, startCh, isInsert);
6404
+ var last = markedSpansAfter(oldLast, endCh, isInsert);
6405
+
6406
+ // Next, merge those two ends
6407
+ var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0);
6408
+ if (first) {
6409
+ // Fix up .to properties of first
6410
+ for (var i = 0; i < first.length; ++i) {
6411
+ var span = first[i];
6412
+ if (span.to == null) {
6413
+ var found = getMarkedSpanFor(last, span.marker);
6414
+ if (!found) span.to = startCh;
6415
+ else if (sameLine) span.to = found.to == null ? null : found.to + offset;
6416
+ }
6417
+ }
6418
+ }
6419
+ if (last) {
6420
+ // Fix up .from in last (or move them into first in case of sameLine)
6421
+ for (var i = 0; i < last.length; ++i) {
6422
+ var span = last[i];
6423
+ if (span.to != null) span.to += offset;
6424
+ if (span.from == null) {
6425
+ var found = getMarkedSpanFor(first, span.marker);
6426
+ if (!found) {
6427
+ span.from = offset;
6428
+ if (sameLine) (first || (first = [])).push(span);
6429
+ }
6430
+ } else {
6431
+ span.from += offset;
6432
+ if (sameLine) (first || (first = [])).push(span);
6433
+ }
6434
+ }
6435
+ }
6436
+ // Make sure we didn't create any zero-length spans
6437
+ if (first) first = clearEmptySpans(first);
6438
+ if (last && last != first) last = clearEmptySpans(last);
6439
+
6440
+ var newMarkers = [first];
6441
+ if (!sameLine) {
6442
+ // Fill gap with whole-line-spans
6443
+ var gap = change.text.length - 2, gapMarkers;
6444
+ if (gap > 0 && first)
6445
+ for (var i = 0; i < first.length; ++i)
6446
+ if (first[i].to == null)
6447
+ (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));
6448
+ for (var i = 0; i < gap; ++i)
6449
+ newMarkers.push(gapMarkers);
6450
+ newMarkers.push(last);
6451
+ }
6452
+ return newMarkers;
6453
+ }
6454
+
6455
+ // Remove spans that are empty and don't have a clearWhenEmpty
6456
+ // option of false.
6457
+ function clearEmptySpans(spans) {
6458
+ for (var i = 0; i < spans.length; ++i) {
6459
+ var span = spans[i];
6460
+ if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false)
6461
+ spans.splice(i--, 1);
6462
+ }
6463
+ if (!spans.length) return null;
6464
+ return spans;
6465
+ }
6466
+
6467
+ // Used for un/re-doing changes from the history. Combines the
6468
+ // result of computing the existing spans with the set of spans that
6469
+ // existed in the history (so that deleting around a span and then
6470
+ // undoing brings back the span).
6471
+ function mergeOldSpans(doc, change) {
6472
+ var old = getOldSpans(doc, change);
6473
+ var stretched = stretchSpansOverChange(doc, change);
6474
+ if (!old) return stretched;
6475
+ if (!stretched) return old;
6476
+
6477
+ for (var i = 0; i < old.length; ++i) {
6478
+ var oldCur = old[i], stretchCur = stretched[i];
6479
+ if (oldCur && stretchCur) {
6480
+ spans: for (var j = 0; j < stretchCur.length; ++j) {
6481
+ var span = stretchCur[j];
6482
+ for (var k = 0; k < oldCur.length; ++k)
6483
+ if (oldCur[k].marker == span.marker) continue spans;
6484
+ oldCur.push(span);
6485
+ }
6486
+ } else if (stretchCur) {
6487
+ old[i] = stretchCur;
6488
+ }
6489
+ }
6490
+ return old;
6491
+ }
6492
+
6493
+ // Used to 'clip' out readOnly ranges when making a change.
6494
+ function removeReadOnlyRanges(doc, from, to) {
6495
+ var markers = null;
6496
+ doc.iter(from.line, to.line + 1, function(line) {
6497
+ if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) {
6498
+ var mark = line.markedSpans[i].marker;
6499
+ if (mark.readOnly && (!markers || indexOf(markers, mark) == -1))
6500
+ (markers || (markers = [])).push(mark);
6501
+ }
6502
+ });
6503
+ if (!markers) return null;
6504
+ var parts = [{from: from, to: to}];
6505
+ for (var i = 0; i < markers.length; ++i) {
6506
+ var mk = markers[i], m = mk.find(0);
6507
+ for (var j = 0; j < parts.length; ++j) {
6508
+ var p = parts[j];
6509
+ if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue;
6510
+ var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to);
6511
+ if (dfrom < 0 || !mk.inclusiveLeft && !dfrom)
6512
+ newParts.push({from: p.from, to: m.from});
6513
+ if (dto > 0 || !mk.inclusiveRight && !dto)
6514
+ newParts.push({from: m.to, to: p.to});
6515
+ parts.splice.apply(parts, newParts);
6516
+ j += newParts.length - 1;
6517
+ }
6518
+ }
6519
+ return parts;
6520
+ }
6521
+
6522
+ // Connect or disconnect spans from a line.
6523
+ function detachMarkedSpans(line) {
6524
+ var spans = line.markedSpans;
6525
+ if (!spans) return;
6526
+ for (var i = 0; i < spans.length; ++i)
6527
+ spans[i].marker.detachLine(line);
6528
+ line.markedSpans = null;
6529
+ }
6530
+ function attachMarkedSpans(line, spans) {
6531
+ if (!spans) return;
6532
+ for (var i = 0; i < spans.length; ++i)
6533
+ spans[i].marker.attachLine(line);
6534
+ line.markedSpans = spans;
6535
+ }
6536
+
6537
+ // Helpers used when computing which overlapping collapsed span
6538
+ // counts as the larger one.
6539
+ function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; }
6540
+ function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; }
6541
+
6542
+ // Returns a number indicating which of two overlapping collapsed
6543
+ // spans is larger (and thus includes the other). Falls back to
6544
+ // comparing ids when the spans cover exactly the same range.
6545
+ function compareCollapsedMarkers(a, b) {
6546
+ var lenDiff = a.lines.length - b.lines.length;
6547
+ if (lenDiff != 0) return lenDiff;
6548
+ var aPos = a.find(), bPos = b.find();
6549
+ var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b);
6550
+ if (fromCmp) return -fromCmp;
6551
+ var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b);
6552
+ if (toCmp) return toCmp;
6553
+ return b.id - a.id;
6554
+ }
6555
+
6556
+ // Find out whether a line ends or starts in a collapsed span. If
6557
+ // so, return the marker for that span.
6558
+ function collapsedSpanAtSide(line, start) {
6559
+ var sps = sawCollapsedSpans && line.markedSpans, found;
6560
+ if (sps) for (var sp, i = 0; i < sps.length; ++i) {
6561
+ sp = sps[i];
6562
+ if (sp.marker.collapsed && (start ? sp.from : sp.to) == null &&
6563
+ (!found || compareCollapsedMarkers(found, sp.marker) < 0))
6564
+ found = sp.marker;
6565
+ }
6566
+ return found;
6567
+ }
6568
+ function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); }
6569
+ function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); }
6570
+
6571
+ // Test whether there exists a collapsed span that partially
6572
+ // overlaps (covers the start or end, but not both) of a new span.
6573
+ // Such overlap is not allowed.
6574
+ function conflictingCollapsedRange(doc, lineNo, from, to, marker) {
6575
+ var line = getLine(doc, lineNo);
6576
+ var sps = sawCollapsedSpans && line.markedSpans;
6577
+ if (sps) for (var i = 0; i < sps.length; ++i) {
6578
+ var sp = sps[i];
6579
+ if (!sp.marker.collapsed) continue;
6580
+ var found = sp.marker.find(0);
6581
+ var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker);
6582
+ var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker);
6583
+ if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue;
6584
+ if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
6585
+ fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0))
6586
+ return true;
6587
+ }
6588
+ }
6589
+
6590
+ // A visual line is a line as drawn on the screen. Folding, for
6591
+ // example, can cause multiple logical lines to appear on the same
6592
+ // visual line. This finds the start of the visual line that the
6593
+ // given line is part of (usually that is the line itself).
6594
+ function visualLine(line) {
6595
+ var merged;
6596
+ while (merged = collapsedSpanAtStart(line))
6597
+ line = merged.find(-1, true).line;
6598
+ return line;
6599
+ }
6600
+
6601
+ // Returns an array of logical lines that continue the visual line
6602
+ // started by the argument, or undefined if there are no such lines.
6603
+ function visualLineContinued(line) {
6604
+ var merged, lines;
6605
+ while (merged = collapsedSpanAtEnd(line)) {
6606
+ line = merged.find(1, true).line;
6607
+ (lines || (lines = [])).push(line);
6608
+ }
6609
+ return lines;
6610
+ }
6611
+
6612
+ // Get the line number of the start of the visual line that the
6613
+ // given line number is part of.
6614
+ function visualLineNo(doc, lineN) {
6615
+ var line = getLine(doc, lineN), vis = visualLine(line);
6616
+ if (line == vis) return lineN;
6617
+ return lineNo(vis);
6618
+ }
6619
+ // Get the line number of the start of the next visual line after
6620
+ // the given line.
6621
+ function visualLineEndNo(doc, lineN) {
6622
+ if (lineN > doc.lastLine()) return lineN;
6623
+ var line = getLine(doc, lineN), merged;
6624
+ if (!lineIsHidden(doc, line)) return lineN;
6625
+ while (merged = collapsedSpanAtEnd(line))
6626
+ line = merged.find(1, true).line;
6627
+ return lineNo(line) + 1;
6628
+ }
6629
+
6630
+ // Compute whether a line is hidden. Lines count as hidden when they
6631
+ // are part of a visual line that starts with another line, or when
6632
+ // they are entirely covered by collapsed, non-widget span.
6633
+ function lineIsHidden(doc, line) {
6634
+ var sps = sawCollapsedSpans && line.markedSpans;
6635
+ if (sps) for (var sp, i = 0; i < sps.length; ++i) {
6636
+ sp = sps[i];
6637
+ if (!sp.marker.collapsed) continue;
6638
+ if (sp.from == null) return true;
6639
+ if (sp.marker.widgetNode) continue;
6640
+ if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp))
6641
+ return true;
6642
+ }
6643
+ }
6644
+ function lineIsHiddenInner(doc, line, span) {
6645
+ if (span.to == null) {
6646
+ var end = span.marker.find(1, true);
6647
+ return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker));
6648
+ }
6649
+ if (span.marker.inclusiveRight && span.to == line.text.length)
6650
+ return true;
6651
+ for (var sp, i = 0; i < line.markedSpans.length; ++i) {
6652
+ sp = line.markedSpans[i];
6653
+ if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to &&
6654
+ (sp.to == null || sp.to != span.from) &&
6655
+ (sp.marker.inclusiveLeft || span.marker.inclusiveRight) &&
6656
+ lineIsHiddenInner(doc, line, sp)) return true;
6657
+ }
6658
+ }
6659
+
6660
+ // LINE WIDGETS
6661
+
6662
+ // Line widgets are block elements displayed above or below a line.
6663
+
6664
+ var LineWidget = CodeMirror.LineWidget = function(doc, node, options) {
6665
+ if (options) for (var opt in options) if (options.hasOwnProperty(opt))
6666
+ this[opt] = options[opt];
6667
+ this.doc = doc;
6668
+ this.node = node;
6669
+ };
6670
+ eventMixin(LineWidget);
6671
+
6672
+ function adjustScrollWhenAboveVisible(cm, line, diff) {
6673
+ if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
6674
+ addToScrollPos(cm, null, diff);
6675
+ }
6676
+
6677
+ LineWidget.prototype.clear = function() {
6678
+ var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
6679
+ if (no == null || !ws) return;
6680
+ for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
6681
+ if (!ws.length) line.widgets = null;
6682
+ var height = widgetHeight(this);
6683
+ updateLineHeight(line, Math.max(0, line.height - height));
6684
+ if (cm) runInOp(cm, function() {
6685
+ adjustScrollWhenAboveVisible(cm, line, -height);
6686
+ regLineChange(cm, no, "widget");
6687
+ });
6688
+ };
6689
+ LineWidget.prototype.changed = function() {
6690
+ var oldH = this.height, cm = this.doc.cm, line = this.line;
6691
+ this.height = null;
6692
+ var diff = widgetHeight(this) - oldH;
6693
+ if (!diff) return;
6694
+ updateLineHeight(line, line.height + diff);
6695
+ if (cm) runInOp(cm, function() {
6696
+ cm.curOp.forceUpdate = true;
6697
+ adjustScrollWhenAboveVisible(cm, line, diff);
6698
+ });
6699
+ };
6700
+
6701
+ function widgetHeight(widget) {
6702
+ if (widget.height != null) return widget.height;
6703
+ var cm = widget.doc.cm;
6704
+ if (!cm) return 0;
6705
+ if (!contains(document.body, widget.node)) {
6706
+ var parentStyle = "position: relative;";
6707
+ if (widget.coverGutter)
6708
+ parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;";
6709
+ if (widget.noHScroll)
6710
+ parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;";
6711
+ removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
6712
+ }
6713
+ return widget.height = widget.node.parentNode.offsetHeight;
6714
+ }
6715
+
6716
+ function addLineWidget(doc, handle, node, options) {
6717
+ var widget = new LineWidget(doc, node, options);
6718
+ var cm = doc.cm;
6719
+ if (cm && widget.noHScroll) cm.display.alignWidgets = true;
6720
+ changeLine(doc, handle, "widget", function(line) {
6721
+ var widgets = line.widgets || (line.widgets = []);
6722
+ if (widget.insertAt == null) widgets.push(widget);
6723
+ else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
6724
+ widget.line = line;
6725
+ if (cm && !lineIsHidden(doc, line)) {
6726
+ var aboveVisible = heightAtLine(line) < doc.scrollTop;
6727
+ updateLineHeight(line, line.height + widgetHeight(widget));
6728
+ if (aboveVisible) addToScrollPos(cm, null, widget.height);
6729
+ cm.curOp.forceUpdate = true;
6730
+ }
6731
+ return true;
6732
+ });
6733
+ return widget;
6734
+ }
6735
+
6736
+ // LINE DATA STRUCTURE
6737
+
6738
+ // Line objects. These hold state related to a line, including
6739
+ // highlighting info (the styles array).
6740
+ var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) {
6741
+ this.text = text;
6742
+ attachMarkedSpans(this, markedSpans);
6743
+ this.height = estimateHeight ? estimateHeight(this) : 1;
6744
+ };
6745
+ eventMixin(Line);
6746
+ Line.prototype.lineNo = function() { return lineNo(this); };
6747
+
6748
+ // Change the content (text, markers) of a line. Automatically
6749
+ // invalidates cached information and tries to re-estimate the
6750
+ // line's height.
6751
+ function updateLine(line, text, markedSpans, estimateHeight) {
6752
+ line.text = text;
6753
+ if (line.stateAfter) line.stateAfter = null;
6754
+ if (line.styles) line.styles = null;
6755
+ if (line.order != null) line.order = null;
6756
+ detachMarkedSpans(line);
6757
+ attachMarkedSpans(line, markedSpans);
6758
+ var estHeight = estimateHeight ? estimateHeight(line) : 1;
6759
+ if (estHeight != line.height) updateLineHeight(line, estHeight);
6760
+ }
6761
+
6762
+ // Detach a line from the document tree and its markers.
6763
+ function cleanUpLine(line) {
6764
+ line.parent = null;
6765
+ detachMarkedSpans(line);
6766
+ }
6767
+
6768
+ function extractLineClasses(type, output) {
6769
+ if (type) for (;;) {
6770
+ var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
6771
+ if (!lineClass) break;
6772
+ type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
6773
+ var prop = lineClass[1] ? "bgClass" : "textClass";
6774
+ if (output[prop] == null)
6775
+ output[prop] = lineClass[2];
6776
+ else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop]))
6777
+ output[prop] += " " + lineClass[2];
6778
+ }
6779
+ return type;
6780
+ }
6781
+
6782
+ function callBlankLine(mode, state) {
6783
+ if (mode.blankLine) return mode.blankLine(state);
6784
+ if (!mode.innerMode) return;
6785
+ var inner = CodeMirror.innerMode(mode, state);
6786
+ if (inner.mode.blankLine) return inner.mode.blankLine(inner.state);
6787
+ }
6788
+
6789
+ function readToken(mode, stream, state, inner) {
6790
+ for (var i = 0; i < 10; i++) {
6791
+ if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode;
6792
+ var style = mode.token(stream, state);
6793
+ if (stream.pos > stream.start) return style;
6794
+ }
6795
+ throw new Error("Mode " + mode.name + " failed to advance stream.");
6796
+ }
6797
+
6798
+ // Utility for getTokenAt and getLineTokens
6799
+ function takeToken(cm, pos, precise, asArray) {
6800
+ function getObj(copy) {
6801
+ return {start: stream.start, end: stream.pos,
6802
+ string: stream.current(),
6803
+ type: style || null,
6804
+ state: copy ? copyState(doc.mode, state) : state};
6805
+ }
6806
+
6807
+ var doc = cm.doc, mode = doc.mode, style;
6808
+ pos = clipPos(doc, pos);
6809
+ var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise);
6810
+ var stream = new StringStream(line.text, cm.options.tabSize), tokens;
6811
+ if (asArray) tokens = [];
6812
+ while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
6813
+ stream.start = stream.pos;
6814
+ style = readToken(mode, stream, state);
6815
+ if (asArray) tokens.push(getObj(true));
6816
+ }
6817
+ return asArray ? tokens : getObj();
6818
+ }
6819
+
6820
+ // Run the given mode's parser over a line, calling f for each token.
6821
+ function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) {
6822
+ var flattenSpans = mode.flattenSpans;
6823
+ if (flattenSpans == null) flattenSpans = cm.options.flattenSpans;
6824
+ var curStart = 0, curStyle = null;
6825
+ var stream = new StringStream(text, cm.options.tabSize), style;
6826
+ var inner = cm.options.addModeClass && [null];
6827
+ if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses);
6828
+ while (!stream.eol()) {
6829
+ if (stream.pos > cm.options.maxHighlightLength) {
6830
+ flattenSpans = false;
6831
+ if (forceToEnd) processLine(cm, text, state, stream.pos);
6832
+ stream.pos = text.length;
6833
+ style = null;
6834
+ } else {
6835
+ style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses);
6836
+ }
6837
+ if (inner) {
6838
+ var mName = inner[0].name;
6839
+ if (mName) style = "m-" + (style ? mName + " " + style : mName);
6840
+ }
6841
+ if (!flattenSpans || curStyle != style) {
6842
+ while (curStart < stream.start) {
6843
+ curStart = Math.min(stream.start, curStart + 50000);
6844
+ f(curStart, curStyle);
6845
+ }
6846
+ curStyle = style;
6847
+ }
6848
+ stream.start = stream.pos;
6849
+ }
6850
+ while (curStart < stream.pos) {
6851
+ // Webkit seems to refuse to render text nodes longer than 57444 characters
6852
+ var pos = Math.min(stream.pos, curStart + 50000);
6853
+ f(pos, curStyle);
6854
+ curStart = pos;
6855
+ }
6856
+ }
6857
+
6858
+ // Compute a style array (an array starting with a mode generation
6859
+ // -- for invalidation -- followed by pairs of end positions and
6860
+ // style strings), which is used to highlight the tokens on the
6861
+ // line.
6862
+ function highlightLine(cm, line, state, forceToEnd) {
6863
+ // A styles array always starts with a number identifying the
6864
+ // mode/overlays that it is based on (for easy invalidation).
6865
+ var st = [cm.state.modeGen], lineClasses = {};
6866
+ // Compute the base array of styles
6867
+ runMode(cm, line.text, cm.doc.mode, state, function(end, style) {
6868
+ st.push(end, style);
6869
+ }, lineClasses, forceToEnd);
6870
+
6871
+ // Run overlays, adjust style array.
6872
+ for (var o = 0; o < cm.state.overlays.length; ++o) {
6873
+ var overlay = cm.state.overlays[o], i = 1, at = 0;
6874
+ runMode(cm, line.text, overlay.mode, true, function(end, style) {
6875
+ var start = i;
6876
+ // Ensure there's a token end at the current position, and that i points at it
6877
+ while (at < end) {
6878
+ var i_end = st[i];
6879
+ if (i_end > end)
6880
+ st.splice(i, 1, end, st[i+1], i_end);
6881
+ i += 2;
6882
+ at = Math.min(end, i_end);
6883
+ }
6884
+ if (!style) return;
6885
+ if (overlay.opaque) {
6886
+ st.splice(start, i - start, end, "cm-overlay " + style);
6887
+ i = start + 2;
6888
+ } else {
6889
+ for (; start < i; start += 2) {
6890
+ var cur = st[start+1];
6891
+ st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style;
6892
+ }
6893
+ }
6894
+ }, lineClasses);
6895
+ }
6896
+
6897
+ return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null};
6898
+ }
6899
+
6900
+ function getLineStyles(cm, line, updateFrontier) {
6901
+ if (!line.styles || line.styles[0] != cm.state.modeGen) {
6902
+ var state = getStateBefore(cm, lineNo(line));
6903
+ var result = highlightLine(cm, line, line.text.length > cm.options.maxHighlightLength ? copyState(cm.doc.mode, state) : state);
6904
+ line.stateAfter = state;
6905
+ line.styles = result.styles;
6906
+ if (result.classes) line.styleClasses = result.classes;
6907
+ else if (line.styleClasses) line.styleClasses = null;
6908
+ if (updateFrontier === cm.doc.frontier) cm.doc.frontier++;
6909
+ }
6910
+ return line.styles;
6911
+ }
6912
+
6913
+ // Lightweight form of highlight -- proceed over this line and
6914
+ // update state, but don't save a style array. Used for lines that
6915
+ // aren't currently visible.
6916
+ function processLine(cm, text, state, startAt) {
6917
+ var mode = cm.doc.mode;
6918
+ var stream = new StringStream(text, cm.options.tabSize);
6919
+ stream.start = stream.pos = startAt || 0;
6920
+ if (text == "") callBlankLine(mode, state);
6921
+ while (!stream.eol()) {
6922
+ readToken(mode, stream, state);
6923
+ stream.start = stream.pos;
6924
+ }
6925
+ }
6926
+
6927
+ // Convert a style as returned by a mode (either null, or a string
6928
+ // containing one or more styles) to a CSS style. This is cached,
6929
+ // and also looks for line-wide styles.
6930
+ var styleToClassCache = {}, styleToClassCacheWithMode = {};
6931
+ function interpretTokenStyle(style, options) {
6932
+ if (!style || /^\s*$/.test(style)) return null;
6933
+ var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache;
6934
+ return cache[style] ||
6935
+ (cache[style] = style.replace(/\S+/g, "cm-$&"));
6936
+ }
6937
+
6938
+ // Render the DOM representation of the text of a line. Also builds
6939
+ // up a 'line map', which points at the DOM nodes that represent
6940
+ // specific stretches of text, and is used by the measuring code.
6941
+ // The returned object contains the DOM node, this map, and
6942
+ // information about line-wide styles that were set by the mode.
6943
+ function buildLineContent(cm, lineView) {
6944
+ // The padding-right forces the element to have a 'border', which
6945
+ // is needed on Webkit to be able to get line-level bounding
6946
+ // rectangles for it (in measureChar).
6947
+ var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
6948
+ var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content,
6949
+ col: 0, pos: 0, cm: cm,
6950
+ trailingSpace: false,
6951
+ splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")};
6952
+ lineView.measure = {};
6953
+
6954
+ // Iterate over the logical lines that make up this visual line.
6955
+ for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) {
6956
+ var line = i ? lineView.rest[i - 1] : lineView.line, order;
6957
+ builder.pos = 0;
6958
+ builder.addToken = buildToken;
6959
+ // Optionally wire in some hacks into the token-rendering
6960
+ // algorithm, to deal with browser quirks.
6961
+ if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
6962
+ builder.addToken = buildTokenBadBidi(builder.addToken, order);
6963
+ builder.map = [];
6964
+ var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
6965
+ insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
6966
+ if (line.styleClasses) {
6967
+ if (line.styleClasses.bgClass)
6968
+ builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");
6969
+ if (line.styleClasses.textClass)
6970
+ builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");
6971
+ }
6972
+
6973
+ // Ensure at least a single node is present, for measuring.
6974
+ if (builder.map.length == 0)
6975
+ builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));
6976
+
6977
+ // Store the map and a cache object for the current logical line
6978
+ if (i == 0) {
6979
+ lineView.measure.map = builder.map;
6980
+ lineView.measure.cache = {};
6981
+ } else {
6982
+ (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map);
6983
+ (lineView.measure.caches || (lineView.measure.caches = [])).push({});
6984
+ }
6985
+ }
6986
+
6987
+ // See issue #2901
6988
+ if (webkit) {
6989
+ var last = builder.content.lastChild
6990
+ if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
6991
+ builder.content.className = "cm-tab-wrap-hack";
6992
+ }
6993
+
6994
+ signal(cm, "renderLine", cm, lineView.line, builder.pre);
6995
+ if (builder.pre.className)
6996
+ builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");
6997
+
6998
+ return builder;
6999
+ }
7000
+
7001
+ function defaultSpecialCharPlaceholder(ch) {
7002
+ var token = elt("span", "\u2022", "cm-invalidchar");
7003
+ token.title = "\\u" + ch.charCodeAt(0).toString(16);
7004
+ token.setAttribute("aria-label", token.title);
7005
+ return token;
7006
+ }
7007
+
7008
+ // Build up the DOM representation for a single token, and add it to
7009
+ // the line map. Takes care to render special characters separately.
7010
+ function buildToken(builder, text, style, startStyle, endStyle, title, css) {
7011
+ if (!text) return;
7012
+ var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text
7013
+ var special = builder.cm.state.specialChars, mustWrap = false;
7014
+ if (!special.test(text)) {
7015
+ builder.col += text.length;
7016
+ var content = document.createTextNode(displayText);
7017
+ builder.map.push(builder.pos, builder.pos + text.length, content);
7018
+ if (ie && ie_version < 9) mustWrap = true;
7019
+ builder.pos += text.length;
7020
+ } else {
7021
+ var content = document.createDocumentFragment(), pos = 0;
7022
+ while (true) {
7023
+ special.lastIndex = pos;
7024
+ var m = special.exec(text);
7025
+ var skipped = m ? m.index - pos : text.length - pos;
7026
+ if (skipped) {
7027
+ var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
7028
+ if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
7029
+ else content.appendChild(txt);
7030
+ builder.map.push(builder.pos, builder.pos + skipped, txt);
7031
+ builder.col += skipped;
7032
+ builder.pos += skipped;
7033
+ }
7034
+ if (!m) break;
7035
+ pos += skipped + 1;
7036
+ if (m[0] == "\t") {
7037
+ var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
7038
+ var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
7039
+ txt.setAttribute("role", "presentation");
7040
+ txt.setAttribute("cm-text", "\t");
7041
+ builder.col += tabWidth;
7042
+ } else if (m[0] == "\r" || m[0] == "\n") {
7043
+ var txt = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
7044
+ txt.setAttribute("cm-text", m[0]);
7045
+ builder.col += 1;
7046
+ } else {
7047
+ var txt = builder.cm.options.specialCharPlaceholder(m[0]);
7048
+ txt.setAttribute("cm-text", m[0]);
7049
+ if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
7050
+ else content.appendChild(txt);
7051
+ builder.col += 1;
7052
+ }
7053
+ builder.map.push(builder.pos, builder.pos + 1, txt);
7054
+ builder.pos++;
7055
+ }
7056
+ }
7057
+ builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32
7058
+ if (style || startStyle || endStyle || mustWrap || css) {
7059
+ var fullStyle = style || "";
7060
+ if (startStyle) fullStyle += startStyle;
7061
+ if (endStyle) fullStyle += endStyle;
7062
+ var token = elt("span", [content], fullStyle, css);
7063
+ if (title) token.title = title;
7064
+ return builder.content.appendChild(token);
7065
+ }
7066
+ builder.content.appendChild(content);
7067
+ }
7068
+
7069
+ function splitSpaces(text, trailingBefore) {
7070
+ if (text.length > 1 && !/ /.test(text)) return text
7071
+ var spaceBefore = trailingBefore, result = ""
7072
+ for (var i = 0; i < text.length; i++) {
7073
+ var ch = text.charAt(i)
7074
+ if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
7075
+ ch = "\u00a0"
7076
+ result += ch
7077
+ spaceBefore = ch == " "
7078
+ }
7079
+ return result
7080
+ }
7081
+
7082
+ // Work around nonsense dimensions being reported for stretches of
7083
+ // right-to-left text.
7084
+ function buildTokenBadBidi(inner, order) {
7085
+ return function(builder, text, style, startStyle, endStyle, title, css) {
7086
+ style = style ? style + " cm-force-border" : "cm-force-border";
7087
+ var start = builder.pos, end = start + text.length;
7088
+ for (;;) {
7089
+ // Find the part that overlaps with the start of this text
7090
+ for (var i = 0; i < order.length; i++) {
7091
+ var part = order[i];
7092
+ if (part.to > start && part.from <= start) break;
7093
+ }
7094
+ if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css);
7095
+ inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
7096
+ startStyle = null;
7097
+ text = text.slice(part.to - start);
7098
+ start = part.to;
7099
+ }
7100
+ };
7101
+ }
7102
+
7103
+ function buildCollapsedSpan(builder, size, marker, ignoreWidget) {
7104
+ var widget = !ignoreWidget && marker.widgetNode;
7105
+ if (widget) builder.map.push(builder.pos, builder.pos + size, widget);
7106
+ if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
7107
+ if (!widget)
7108
+ widget = builder.content.appendChild(document.createElement("span"));
7109
+ widget.setAttribute("cm-marker", marker.id);
7110
+ }
7111
+ if (widget) {
7112
+ builder.cm.display.input.setUneditable(widget);
7113
+ builder.content.appendChild(widget);
7114
+ }
7115
+ builder.pos += size;
7116
+ builder.trailingSpace = false
7117
+ }
7118
+
7119
+ // Outputs a number of spans to make up a line, taking highlighting
7120
+ // and marked text into account.
7121
+ function insertLineContent(line, builder, styles) {
7122
+ var spans = line.markedSpans, allText = line.text, at = 0;
7123
+ if (!spans) {
7124
+ for (var i = 1; i < styles.length; i+=2)
7125
+ builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options));
7126
+ return;
7127
+ }
7128
+
7129
+ var len = allText.length, pos = 0, i = 1, text = "", style, css;
7130
+ var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed;
7131
+ for (;;) {
7132
+ if (nextChange == pos) { // Update current marker set
7133
+ spanStyle = spanEndStyle = spanStartStyle = title = css = "";
7134
+ collapsed = null; nextChange = Infinity;
7135
+ var foundBookmarks = [], endStyles
7136
+ for (var j = 0; j < spans.length; ++j) {
7137
+ var sp = spans[j], m = sp.marker;
7138
+ if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
7139
+ foundBookmarks.push(m);
7140
+ } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
7141
+ if (sp.to != null && sp.to != pos && nextChange > sp.to) {
7142
+ nextChange = sp.to;
7143
+ spanEndStyle = "";
7144
+ }
7145
+ if (m.className) spanStyle += " " + m.className;
7146
+ if (m.css) css = (css ? css + ";" : "") + m.css;
7147
+ if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
7148
+ if (m.endStyle && sp.to == nextChange) (endStyles || (endStyles = [])).push(m.endStyle, sp.to)
7149
+ if (m.title && !title) title = m.title;
7150
+ if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
7151
+ collapsed = sp;
7152
+ } else if (sp.from > pos && nextChange > sp.from) {
7153
+ nextChange = sp.from;
7154
+ }
7155
+ }
7156
+ if (endStyles) for (var j = 0; j < endStyles.length; j += 2)
7157
+ if (endStyles[j + 1] == nextChange) spanEndStyle += " " + endStyles[j]
7158
+
7159
+ if (!collapsed || collapsed.from == pos) for (var j = 0; j < foundBookmarks.length; ++j)
7160
+ buildCollapsedSpan(builder, 0, foundBookmarks[j]);
7161
+ if (collapsed && (collapsed.from || 0) == pos) {
7162
+ buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
7163
+ collapsed.marker, collapsed.from == null);
7164
+ if (collapsed.to == null) return;
7165
+ if (collapsed.to == pos) collapsed = false;
7166
+ }
7167
+ }
7168
+ if (pos >= len) break;
7169
+
7170
+ var upto = Math.min(len, nextChange);
7171
+ while (true) {
7172
+ if (text) {
7173
+ var end = pos + text.length;
7174
+ if (!collapsed) {
7175
+ var tokenText = end > upto ? text.slice(0, upto - pos) : text;
7176
+ builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle,
7177
+ spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css);
7178
+ }
7179
+ if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;}
7180
+ pos = end;
7181
+ spanStartStyle = "";
7182
+ }
7183
+ text = allText.slice(at, at = styles[i++]);
7184
+ style = interpretTokenStyle(styles[i++], builder.cm.options);
7185
+ }
7186
+ }
7187
+ }
7188
+
7189
+ // DOCUMENT DATA STRUCTURE
7190
+
7191
+ // By default, updates that start and end at the beginning of a line
7192
+ // are treated specially, in order to make the association of line
7193
+ // widgets and marker elements with the text behave more intuitive.
7194
+ function isWholeLineUpdate(doc, change) {
7195
+ return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" &&
7196
+ (!doc.cm || doc.cm.options.wholeLineUpdateBefore);
7197
+ }
7198
+
7199
+ // Perform a change on the document data structure.
7200
+ function updateDoc(doc, change, markedSpans, estimateHeight) {
7201
+ function spansFor(n) {return markedSpans ? markedSpans[n] : null;}
7202
+ function update(line, text, spans) {
7203
+ updateLine(line, text, spans, estimateHeight);
7204
+ signalLater(line, "change", line, change);
7205
+ }
7206
+ function linesFor(start, end) {
7207
+ for (var i = start, result = []; i < end; ++i)
7208
+ result.push(new Line(text[i], spansFor(i), estimateHeight));
7209
+ return result;
7210
+ }
7211
+
7212
+ var from = change.from, to = change.to, text = change.text;
7213
+ var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line);
7214
+ var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line;
7215
+
7216
+ // Adjust the line structure
7217
+ if (change.full) {
7218
+ doc.insert(0, linesFor(0, text.length));
7219
+ doc.remove(text.length, doc.size - text.length);
7220
+ } else if (isWholeLineUpdate(doc, change)) {
7221
+ // This is a whole-line replace. Treated specially to make
7222
+ // sure line objects move the way they are supposed to.
7223
+ var added = linesFor(0, text.length - 1);
7224
+ update(lastLine, lastLine.text, lastSpans);
7225
+ if (nlines) doc.remove(from.line, nlines);
7226
+ if (added.length) doc.insert(from.line, added);
7227
+ } else if (firstLine == lastLine) {
7228
+ if (text.length == 1) {
7229
+ update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans);
7230
+ } else {
7231
+ var added = linesFor(1, text.length - 1);
7232
+ added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight));
7233
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
7234
+ doc.insert(from.line + 1, added);
7235
+ }
7236
+ } else if (text.length == 1) {
7237
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0));
7238
+ doc.remove(from.line + 1, nlines);
7239
+ } else {
7240
+ update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0));
7241
+ update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans);
7242
+ var added = linesFor(1, text.length - 1);
7243
+ if (nlines > 1) doc.remove(from.line + 1, nlines - 1);
7244
+ doc.insert(from.line + 1, added);
7245
+ }
7246
+
7247
+ signalLater(doc, "change", doc, change);
7248
+ }
7249
+
7250
+ // The document is represented as a BTree consisting of leaves, with
7251
+ // chunk of lines in them, and branches, with up to ten leaves or
7252
+ // other branch nodes below them. The top node is always a branch
7253
+ // node, and is the document object itself (meaning it has
7254
+ // additional methods and properties).
7255
+ //
7256
+ // All nodes have parent links. The tree is used both to go from
7257
+ // line numbers to line objects, and to go from objects to numbers.
7258
+ // It also indexes by height, and is used to convert between height
7259
+ // and line object, and to find the total height of the document.
7260
+ //
7261
+ // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html
7262
+
7263
+ function LeafChunk(lines) {
7264
+ this.lines = lines;
7265
+ this.parent = null;
7266
+ for (var i = 0, height = 0; i < lines.length; ++i) {
7267
+ lines[i].parent = this;
7268
+ height += lines[i].height;
7269
+ }
7270
+ this.height = height;
7271
+ }
7272
+
7273
+ LeafChunk.prototype = {
7274
+ chunkSize: function() { return this.lines.length; },
7275
+ // Remove the n lines at offset 'at'.
7276
+ removeInner: function(at, n) {
7277
+ for (var i = at, e = at + n; i < e; ++i) {
7278
+ var line = this.lines[i];
7279
+ this.height -= line.height;
7280
+ cleanUpLine(line);
7281
+ signalLater(line, "delete");
7282
+ }
7283
+ this.lines.splice(at, n);
7284
+ },
7285
+ // Helper used to collapse a small branch into a single leaf.
7286
+ collapse: function(lines) {
7287
+ lines.push.apply(lines, this.lines);
7288
+ },
7289
+ // Insert the given array of lines at offset 'at', count them as
7290
+ // having the given height.
7291
+ insertInner: function(at, lines, height) {
7292
+ this.height += height;
7293
+ this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at));
7294
+ for (var i = 0; i < lines.length; ++i) lines[i].parent = this;
7295
+ },
7296
+ // Used to iterate over a part of the tree.
7297
+ iterN: function(at, n, op) {
7298
+ for (var e = at + n; at < e; ++at)
7299
+ if (op(this.lines[at])) return true;
7300
+ }
7301
+ };
7302
+
7303
+ function BranchChunk(children) {
7304
+ this.children = children;
7305
+ var size = 0, height = 0;
7306
+ for (var i = 0; i < children.length; ++i) {
7307
+ var ch = children[i];
7308
+ size += ch.chunkSize(); height += ch.height;
7309
+ ch.parent = this;
7310
+ }
7311
+ this.size = size;
7312
+ this.height = height;
7313
+ this.parent = null;
7314
+ }
7315
+
7316
+ BranchChunk.prototype = {
7317
+ chunkSize: function() { return this.size; },
7318
+ removeInner: function(at, n) {
7319
+ this.size -= n;
7320
+ for (var i = 0; i < this.children.length; ++i) {
7321
+ var child = this.children[i], sz = child.chunkSize();
7322
+ if (at < sz) {
7323
+ var rm = Math.min(n, sz - at), oldHeight = child.height;
7324
+ child.removeInner(at, rm);
7325
+ this.height -= oldHeight - child.height;
7326
+ if (sz == rm) { this.children.splice(i--, 1); child.parent = null; }
7327
+ if ((n -= rm) == 0) break;
7328
+ at = 0;
7329
+ } else at -= sz;
7330
+ }
7331
+ // If the result is smaller than 25 lines, ensure that it is a
7332
+ // single leaf node.
7333
+ if (this.size - n < 25 &&
7334
+ (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) {
7335
+ var lines = [];
7336
+ this.collapse(lines);
7337
+ this.children = [new LeafChunk(lines)];
7338
+ this.children[0].parent = this;
7339
+ }
7340
+ },
7341
+ collapse: function(lines) {
7342
+ for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines);
7343
+ },
7344
+ insertInner: function(at, lines, height) {
7345
+ this.size += lines.length;
7346
+ this.height += height;
7347
+ for (var i = 0; i < this.children.length; ++i) {
7348
+ var child = this.children[i], sz = child.chunkSize();
7349
+ if (at <= sz) {
7350
+ child.insertInner(at, lines, height);
7351
+ if (child.lines && child.lines.length > 50) {
7352
+ // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
7353
+ // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
7354
+ var remaining = child.lines.length % 25 + 25
7355
+ for (var pos = remaining; pos < child.lines.length;) {
7356
+ var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
7357
+ child.height -= leaf.height;
7358
+ this.children.splice(++i, 0, leaf);
7359
+ leaf.parent = this;
7360
+ }
7361
+ child.lines = child.lines.slice(0, remaining);
7362
+ this.maybeSpill();
7363
+ }
7364
+ break;
7365
+ }
7366
+ at -= sz;
7367
+ }
7368
+ },
7369
+ // When a node has grown, check whether it should be split.
7370
+ maybeSpill: function() {
7371
+ if (this.children.length <= 10) return;
7372
+ var me = this;
7373
+ do {
7374
+ var spilled = me.children.splice(me.children.length - 5, 5);
7375
+ var sibling = new BranchChunk(spilled);
7376
+ if (!me.parent) { // Become the parent node
7377
+ var copy = new BranchChunk(me.children);
7378
+ copy.parent = me;
7379
+ me.children = [copy, sibling];
7380
+ me = copy;
7381
+ } else {
7382
+ me.size -= sibling.size;
7383
+ me.height -= sibling.height;
7384
+ var myIndex = indexOf(me.parent.children, me);
7385
+ me.parent.children.splice(myIndex + 1, 0, sibling);
7386
+ }
7387
+ sibling.parent = me.parent;
7388
+ } while (me.children.length > 10);
7389
+ me.parent.maybeSpill();
7390
+ },
7391
+ iterN: function(at, n, op) {
7392
+ for (var i = 0; i < this.children.length; ++i) {
7393
+ var child = this.children[i], sz = child.chunkSize();
7394
+ if (at < sz) {
7395
+ var used = Math.min(n, sz - at);
7396
+ if (child.iterN(at, used, op)) return true;
7397
+ if ((n -= used) == 0) break;
7398
+ at = 0;
7399
+ } else at -= sz;
7400
+ }
7401
+ }
7402
+ };
7403
+
7404
+ var nextDocId = 0;
7405
+ var Doc = CodeMirror.Doc = function(text, mode, firstLine, lineSep) {
7406
+ if (!(this instanceof Doc)) return new Doc(text, mode, firstLine, lineSep);
7407
+ if (firstLine == null) firstLine = 0;
7408
+
7409
+ BranchChunk.call(this, [new LeafChunk([new Line("", null)])]);
7410
+ this.first = firstLine;
7411
+ this.scrollTop = this.scrollLeft = 0;
7412
+ this.cantEdit = false;
7413
+ this.cleanGeneration = 1;
7414
+ this.frontier = firstLine;
7415
+ var start = Pos(firstLine, 0);
7416
+ this.sel = simpleSelection(start);
7417
+ this.history = new History(null);
7418
+ this.id = ++nextDocId;
7419
+ this.modeOption = mode;
7420
+ this.lineSep = lineSep;
7421
+ this.extend = false;
7422
+
7423
+ if (typeof text == "string") text = this.splitLines(text);
7424
+ updateDoc(this, {from: start, to: start, text: text});
7425
+ setSelection(this, simpleSelection(start), sel_dontScroll);
7426
+ };
7427
+
7428
+ Doc.prototype = createObj(BranchChunk.prototype, {
7429
+ constructor: Doc,
7430
+ // Iterate over the document. Supports two forms -- with only one
7431
+ // argument, it calls that for each line in the document. With
7432
+ // three, it iterates over the range given by the first two (with
7433
+ // the second being non-inclusive).
7434
+ iter: function(from, to, op) {
7435
+ if (op) this.iterN(from - this.first, to - from, op);
7436
+ else this.iterN(this.first, this.first + this.size, from);
7437
+ },
7438
+
7439
+ // Non-public interface for adding and removing lines.
7440
+ insert: function(at, lines) {
7441
+ var height = 0;
7442
+ for (var i = 0; i < lines.length; ++i) height += lines[i].height;
7443
+ this.insertInner(at - this.first, lines, height);
7444
+ },
7445
+ remove: function(at, n) { this.removeInner(at - this.first, n); },
7446
+
7447
+ // From here, the methods are part of the public interface. Most
7448
+ // are also available from CodeMirror (editor) instances.
7449
+
7450
+ getValue: function(lineSep) {
7451
+ var lines = getLines(this, this.first, this.first + this.size);
7452
+ if (lineSep === false) return lines;
7453
+ return lines.join(lineSep || this.lineSeparator());
7454
+ },
7455
+ setValue: docMethodOp(function(code) {
7456
+ var top = Pos(this.first, 0), last = this.first + this.size - 1;
7457
+ makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length),
7458
+ text: this.splitLines(code), origin: "setValue", full: true}, true);
7459
+ setSelection(this, simpleSelection(top));
7460
+ }),
7461
+ replaceRange: function(code, from, to, origin) {
7462
+ from = clipPos(this, from);
7463
+ to = to ? clipPos(this, to) : from;
7464
+ replaceRange(this, code, from, to, origin);
7465
+ },
7466
+ getRange: function(from, to, lineSep) {
7467
+ var lines = getBetween(this, clipPos(this, from), clipPos(this, to));
7468
+ if (lineSep === false) return lines;
7469
+ return lines.join(lineSep || this.lineSeparator());
7470
+ },
7471
+
7472
+ getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;},
7473
+
7474
+ getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);},
7475
+ getLineNumber: function(line) {return lineNo(line);},
7476
+
7477
+ getLineHandleVisualStart: function(line) {
7478
+ if (typeof line == "number") line = getLine(this, line);
7479
+ return visualLine(line);
7480
+ },
7481
+
7482
+ lineCount: function() {return this.size;},
7483
+ firstLine: function() {return this.first;},
7484
+ lastLine: function() {return this.first + this.size - 1;},
7485
+
7486
+ clipPos: function(pos) {return clipPos(this, pos);},
7487
+
7488
+ getCursor: function(start) {
7489
+ var range = this.sel.primary(), pos;
7490
+ if (start == null || start == "head") pos = range.head;
7491
+ else if (start == "anchor") pos = range.anchor;
7492
+ else if (start == "end" || start == "to" || start === false) pos = range.to();
7493
+ else pos = range.from();
7494
+ return pos;
7495
+ },
7496
+ listSelections: function() { return this.sel.ranges; },
7497
+ somethingSelected: function() {return this.sel.somethingSelected();},
7498
+
7499
+ setCursor: docMethodOp(function(line, ch, options) {
7500
+ setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options);
7501
+ }),
7502
+ setSelection: docMethodOp(function(anchor, head, options) {
7503
+ setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options);
7504
+ }),
7505
+ extendSelection: docMethodOp(function(head, other, options) {
7506
+ extendSelection(this, clipPos(this, head), other && clipPos(this, other), options);
7507
+ }),
7508
+ extendSelections: docMethodOp(function(heads, options) {
7509
+ extendSelections(this, clipPosArray(this, heads), options);
7510
+ }),
7511
+ extendSelectionsBy: docMethodOp(function(f, options) {
7512
+ var heads = map(this.sel.ranges, f);
7513
+ extendSelections(this, clipPosArray(this, heads), options);
7514
+ }),
7515
+ setSelections: docMethodOp(function(ranges, primary, options) {
7516
+ if (!ranges.length) return;
7517
+ for (var i = 0, out = []; i < ranges.length; i++)
7518
+ out[i] = new Range(clipPos(this, ranges[i].anchor),
7519
+ clipPos(this, ranges[i].head));
7520
+ if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex);
7521
+ setSelection(this, normalizeSelection(out, primary), options);
7522
+ }),
7523
+ addSelection: docMethodOp(function(anchor, head, options) {
7524
+ var ranges = this.sel.ranges.slice(0);
7525
+ ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor)));
7526
+ setSelection(this, normalizeSelection(ranges, ranges.length - 1), options);
7527
+ }),
7528
+
7529
+ getSelection: function(lineSep) {
7530
+ var ranges = this.sel.ranges, lines;
7531
+ for (var i = 0; i < ranges.length; i++) {
7532
+ var sel = getBetween(this, ranges[i].from(), ranges[i].to());
7533
+ lines = lines ? lines.concat(sel) : sel;
7534
+ }
7535
+ if (lineSep === false) return lines;
7536
+ else return lines.join(lineSep || this.lineSeparator());
7537
+ },
7538
+ getSelections: function(lineSep) {
7539
+ var parts = [], ranges = this.sel.ranges;
7540
+ for (var i = 0; i < ranges.length; i++) {
7541
+ var sel = getBetween(this, ranges[i].from(), ranges[i].to());
7542
+ if (lineSep !== false) sel = sel.join(lineSep || this.lineSeparator());
7543
+ parts[i] = sel;
7544
+ }
7545
+ return parts;
7546
+ },
7547
+ replaceSelection: function(code, collapse, origin) {
7548
+ var dup = [];
7549
+ for (var i = 0; i < this.sel.ranges.length; i++)
7550
+ dup[i] = code;
7551
+ this.replaceSelections(dup, collapse, origin || "+input");
7552
+ },
7553
+ replaceSelections: docMethodOp(function(code, collapse, origin) {
7554
+ var changes = [], sel = this.sel;
7555
+ for (var i = 0; i < sel.ranges.length; i++) {
7556
+ var range = sel.ranges[i];
7557
+ changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin};
7558
+ }
7559
+ var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
7560
+ for (var i = changes.length - 1; i >= 0; i--)
7561
+ makeChange(this, changes[i]);
7562
+ if (newSel) setSelectionReplaceHistory(this, newSel);
7563
+ else if (this.cm) ensureCursorVisible(this.cm);
7564
+ }),
7565
+ undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}),
7566
+ redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}),
7567
+ undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}),
7568
+ redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}),
7569
+
7570
+ setExtending: function(val) {this.extend = val;},
7571
+ getExtending: function() {return this.extend;},
7572
+
7573
+ historySize: function() {
7574
+ var hist = this.history, done = 0, undone = 0;
7575
+ for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done;
7576
+ for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone;
7577
+ return {undo: done, redo: undone};
7578
+ },
7579
+ clearHistory: function() {this.history = new History(this.history.maxGeneration);},
7580
+
7581
+ markClean: function() {
7582
+ this.cleanGeneration = this.changeGeneration(true);
7583
+ },
7584
+ changeGeneration: function(forceSplit) {
7585
+ if (forceSplit)
7586
+ this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;
7587
+ return this.history.generation;
7588
+ },
7589
+ isClean: function (gen) {
7590
+ return this.history.generation == (gen || this.cleanGeneration);
7591
+ },
7592
+
7593
+ getHistory: function() {
7594
+ return {done: copyHistoryArray(this.history.done),
7595
+ undone: copyHistoryArray(this.history.undone)};
7596
+ },
7597
+ setHistory: function(histData) {
7598
+ var hist = this.history = new History(this.history.maxGeneration);
7599
+ hist.done = copyHistoryArray(histData.done.slice(0), null, true);
7600
+ hist.undone = copyHistoryArray(histData.undone.slice(0), null, true);
7601
+ },
7602
+
7603
+ addLineClass: docMethodOp(function(handle, where, cls) {
7604
+ return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
7605
+ var prop = where == "text" ? "textClass"
7606
+ : where == "background" ? "bgClass"
7607
+ : where == "gutter" ? "gutterClass" : "wrapClass";
7608
+ if (!line[prop]) line[prop] = cls;
7609
+ else if (classTest(cls).test(line[prop])) return false;
7610
+ else line[prop] += " " + cls;
7611
+ return true;
7612
+ });
7613
+ }),
7614
+ removeLineClass: docMethodOp(function(handle, where, cls) {
7615
+ return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) {
7616
+ var prop = where == "text" ? "textClass"
7617
+ : where == "background" ? "bgClass"
7618
+ : where == "gutter" ? "gutterClass" : "wrapClass";
7619
+ var cur = line[prop];
7620
+ if (!cur) return false;
7621
+ else if (cls == null) line[prop] = null;
7622
+ else {
7623
+ var found = cur.match(classTest(cls));
7624
+ if (!found) return false;
7625
+ var end = found.index + found[0].length;
7626
+ line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null;
7627
+ }
7628
+ return true;
7629
+ });
7630
+ }),
7631
+
7632
+ addLineWidget: docMethodOp(function(handle, node, options) {
7633
+ return addLineWidget(this, handle, node, options);
7634
+ }),
7635
+ removeLineWidget: function(widget) { widget.clear(); },
7636
+
7637
+ markText: function(from, to, options) {
7638
+ return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range");
7639
+ },
7640
+ setBookmark: function(pos, options) {
7641
+ var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
7642
+ insertLeft: options && options.insertLeft,
7643
+ clearWhenEmpty: false, shared: options && options.shared,
7644
+ handleMouseEvents: options && options.handleMouseEvents};
7645
+ pos = clipPos(this, pos);
7646
+ return markText(this, pos, pos, realOpts, "bookmark");
7647
+ },
7648
+ findMarksAt: function(pos) {
7649
+ pos = clipPos(this, pos);
7650
+ var markers = [], spans = getLine(this, pos.line).markedSpans;
7651
+ if (spans) for (var i = 0; i < spans.length; ++i) {
7652
+ var span = spans[i];
7653
+ if ((span.from == null || span.from <= pos.ch) &&
7654
+ (span.to == null || span.to >= pos.ch))
7655
+ markers.push(span.marker.parent || span.marker);
7656
+ }
7657
+ return markers;
7658
+ },
7659
+ findMarks: function(from, to, filter) {
7660
+ from = clipPos(this, from); to = clipPos(this, to);
7661
+ var found = [], lineNo = from.line;
7662
+ this.iter(from.line, to.line + 1, function(line) {
7663
+ var spans = line.markedSpans;
7664
+ if (spans) for (var i = 0; i < spans.length; i++) {
7665
+ var span = spans[i];
7666
+ if (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
7667
+ span.from == null && lineNo != from.line ||
7668
+ span.from != null && lineNo == to.line && span.from >= to.ch) &&
7669
+ (!filter || filter(span.marker)))
7670
+ found.push(span.marker.parent || span.marker);
7671
+ }
7672
+ ++lineNo;
7673
+ });
7674
+ return found;
7675
+ },
7676
+ getAllMarks: function() {
7677
+ var markers = [];
7678
+ this.iter(function(line) {
7679
+ var sps = line.markedSpans;
7680
+ if (sps) for (var i = 0; i < sps.length; ++i)
7681
+ if (sps[i].from != null) markers.push(sps[i].marker);
7682
+ });
7683
+ return markers;
7684
+ },
7685
+
7686
+ posFromIndex: function(off) {
7687
+ var ch, lineNo = this.first, sepSize = this.lineSeparator().length;
7688
+ this.iter(function(line) {
7689
+ var sz = line.text.length + sepSize;
7690
+ if (sz > off) { ch = off; return true; }
7691
+ off -= sz;
7692
+ ++lineNo;
7693
+ });
7694
+ return clipPos(this, Pos(lineNo, ch));
7695
+ },
7696
+ indexFromPos: function (coords) {
7697
+ coords = clipPos(this, coords);
7698
+ var index = coords.ch;
7699
+ if (coords.line < this.first || coords.ch < 0) return 0;
7700
+ var sepSize = this.lineSeparator().length;
7701
+ this.iter(this.first, coords.line, function (line) {
7702
+ index += line.text.length + sepSize;
7703
+ });
7704
+ return index;
7705
+ },
7706
+
7707
+ copy: function(copyHistory) {
7708
+ var doc = new Doc(getLines(this, this.first, this.first + this.size),
7709
+ this.modeOption, this.first, this.lineSep);
7710
+ doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft;
7711
+ doc.sel = this.sel;
7712
+ doc.extend = false;
7713
+ if (copyHistory) {
7714
+ doc.history.undoDepth = this.history.undoDepth;
7715
+ doc.setHistory(this.getHistory());
7716
+ }
7717
+ return doc;
7718
+ },
7719
+
7720
+ linkedDoc: function(options) {
7721
+ if (!options) options = {};
7722
+ var from = this.first, to = this.first + this.size;
7723
+ if (options.from != null && options.from > from) from = options.from;
7724
+ if (options.to != null && options.to < to) to = options.to;
7725
+ var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep);
7726
+ if (options.sharedHist) copy.history = this.history;
7727
+ (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist});
7728
+ copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}];
7729
+ copySharedMarkers(copy, findSharedMarkers(this));
7730
+ return copy;
7731
+ },
7732
+ unlinkDoc: function(other) {
7733
+ if (other instanceof CodeMirror) other = other.doc;
7734
+ if (this.linked) for (var i = 0; i < this.linked.length; ++i) {
7735
+ var link = this.linked[i];
7736
+ if (link.doc != other) continue;
7737
+ this.linked.splice(i, 1);
7738
+ other.unlinkDoc(this);
7739
+ detachSharedMarkers(findSharedMarkers(this));
7740
+ break;
7741
+ }
7742
+ // If the histories were shared, split them again
7743
+ if (other.history == this.history) {
7744
+ var splitIds = [other.id];
7745
+ linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true);
7746
+ other.history = new History(null);
7747
+ other.history.done = copyHistoryArray(this.history.done, splitIds);
7748
+ other.history.undone = copyHistoryArray(this.history.undone, splitIds);
7749
+ }
7750
+ },
7751
+ iterLinkedDocs: function(f) {linkedDocs(this, f);},
7752
+
7753
+ getMode: function() {return this.mode;},
7754
+ getEditor: function() {return this.cm;},
7755
+
7756
+ splitLines: function(str) {
7757
+ if (this.lineSep) return str.split(this.lineSep);
7758
+ return splitLinesAuto(str);
7759
+ },
7760
+ lineSeparator: function() { return this.lineSep || "\n"; }
7761
+ });
7762
+
7763
+ // Public alias.
7764
+ Doc.prototype.eachLine = Doc.prototype.iter;
7765
+
7766
+ // Set up methods on CodeMirror's prototype to redirect to the editor's document.
7767
+ var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
7768
+ for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
7769
+ CodeMirror.prototype[prop] = (function(method) {
7770
+ return function() {return method.apply(this.doc, arguments);};
7771
+ })(Doc.prototype[prop]);
7772
+
7773
+ eventMixin(Doc);
7774
+
7775
+ // Call f for all linked documents.
7776
+ function linkedDocs(doc, f, sharedHistOnly) {
7777
+ function propagate(doc, skip, sharedHist) {
7778
+ if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) {
7779
+ var rel = doc.linked[i];
7780
+ if (rel.doc == skip) continue;
7781
+ var shared = sharedHist && rel.sharedHist;
7782
+ if (sharedHistOnly && !shared) continue;
7783
+ f(rel.doc, shared);
7784
+ propagate(rel.doc, doc, shared);
7785
+ }
7786
+ }
7787
+ propagate(doc, null, true);
7788
+ }
7789
+
7790
+ // Attach a document to an editor.
7791
+ function attachDoc(cm, doc) {
7792
+ if (doc.cm) throw new Error("This document is already in use.");
7793
+ cm.doc = doc;
7794
+ doc.cm = cm;
7795
+ estimateLineHeights(cm);
7796
+ loadMode(cm);
7797
+ if (!cm.options.lineWrapping) findMaxLine(cm);
7798
+ cm.options.mode = doc.modeOption;
7799
+ regChange(cm);
7800
+ }
7801
+
7802
+ // LINE UTILITIES
7803
+
7804
+ // Find the line object corresponding to the given line number.
7805
+ function getLine(doc, n) {
7806
+ n -= doc.first;
7807
+ if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.");
7808
+ for (var chunk = doc; !chunk.lines;) {
7809
+ for (var i = 0;; ++i) {
7810
+ var child = chunk.children[i], sz = child.chunkSize();
7811
+ if (n < sz) { chunk = child; break; }
7812
+ n -= sz;
7813
+ }
7814
+ }
7815
+ return chunk.lines[n];
7816
+ }
7817
+
7818
+ // Get the part of a document between two positions, as an array of
7819
+ // strings.
7820
+ function getBetween(doc, start, end) {
7821
+ var out = [], n = start.line;
7822
+ doc.iter(start.line, end.line + 1, function(line) {
7823
+ var text = line.text;
7824
+ if (n == end.line) text = text.slice(0, end.ch);
7825
+ if (n == start.line) text = text.slice(start.ch);
7826
+ out.push(text);
7827
+ ++n;
7828
+ });
7829
+ return out;
7830
+ }
7831
+ // Get the lines between from and to, as array of strings.
7832
+ function getLines(doc, from, to) {
7833
+ var out = [];
7834
+ doc.iter(from, to, function(line) { out.push(line.text); });
7835
+ return out;
7836
+ }
7837
+
7838
+ // Update the height of a line, propagating the height change
7839
+ // upwards to parent nodes.
7840
+ function updateLineHeight(line, height) {
7841
+ var diff = height - line.height;
7842
+ if (diff) for (var n = line; n; n = n.parent) n.height += diff;
7843
+ }
7844
+
7845
+ // Given a line object, find its line number by walking up through
7846
+ // its parent links.
7847
+ function lineNo(line) {
7848
+ if (line.parent == null) return null;
7849
+ var cur = line.parent, no = indexOf(cur.lines, line);
7850
+ for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) {
7851
+ for (var i = 0;; ++i) {
7852
+ if (chunk.children[i] == cur) break;
7853
+ no += chunk.children[i].chunkSize();
7854
+ }
7855
+ }
7856
+ return no + cur.first;
7857
+ }
7858
+
7859
+ // Find the line at the given vertical position, using the height
7860
+ // information in the document tree.
7861
+ function lineAtHeight(chunk, h) {
7862
+ var n = chunk.first;
7863
+ outer: do {
7864
+ for (var i = 0; i < chunk.children.length; ++i) {
7865
+ var child = chunk.children[i], ch = child.height;
7866
+ if (h < ch) { chunk = child; continue outer; }
7867
+ h -= ch;
7868
+ n += child.chunkSize();
7869
+ }
7870
+ return n;
7871
+ } while (!chunk.lines);
7872
+ for (var i = 0; i < chunk.lines.length; ++i) {
7873
+ var line = chunk.lines[i], lh = line.height;
7874
+ if (h < lh) break;
7875
+ h -= lh;
7876
+ }
7877
+ return n + i;
7878
+ }
7879
+
7880
+
7881
+ // Find the height above the given line.
7882
+ function heightAtLine(lineObj) {
7883
+ lineObj = visualLine(lineObj);
7884
+
7885
+ var h = 0, chunk = lineObj.parent;
7886
+ for (var i = 0; i < chunk.lines.length; ++i) {
7887
+ var line = chunk.lines[i];
7888
+ if (line == lineObj) break;
7889
+ else h += line.height;
7890
+ }
7891
+ for (var p = chunk.parent; p; chunk = p, p = chunk.parent) {
7892
+ for (var i = 0; i < p.children.length; ++i) {
7893
+ var cur = p.children[i];
7894
+ if (cur == chunk) break;
7895
+ else h += cur.height;
7896
+ }
7897
+ }
7898
+ return h;
7899
+ }
7900
+
7901
+ // Get the bidi ordering for the given line (and cache it). Returns
7902
+ // false for lines that are fully left-to-right, and an array of
7903
+ // BidiSpan objects otherwise.
7904
+ function getOrder(line) {
7905
+ var order = line.order;
7906
+ if (order == null) order = line.order = bidiOrdering(line.text);
7907
+ return order;
7908
+ }
7909
+
7910
+ // HISTORY
7911
+
7912
+ function History(startGen) {
7913
+ // Arrays of change events and selections. Doing something adds an
7914
+ // event to done and clears undo. Undoing moves events from done
7915
+ // to undone, redoing moves them in the other direction.
7916
+ this.done = []; this.undone = [];
7917
+ this.undoDepth = Infinity;
7918
+ // Used to track when changes can be merged into a single undo
7919
+ // event
7920
+ this.lastModTime = this.lastSelTime = 0;
7921
+ this.lastOp = this.lastSelOp = null;
7922
+ this.lastOrigin = this.lastSelOrigin = null;
7923
+ // Used by the isClean() method
7924
+ this.generation = this.maxGeneration = startGen || 1;
7925
+ }
7926
+
7927
+ // Create a history change event from an updateDoc-style change
7928
+ // object.
7929
+ function historyChangeFromChange(doc, change) {
7930
+ var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)};
7931
+ attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);
7932
+ linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true);
7933
+ return histChange;
7934
+ }
7935
+
7936
+ // Pop all selection events off the end of a history array. Stop at
7937
+ // a change event.
7938
+ function clearSelectionEvents(array) {
7939
+ while (array.length) {
7940
+ var last = lst(array);
7941
+ if (last.ranges) array.pop();
7942
+ else break;
7943
+ }
7944
+ }
7945
+
7946
+ // Find the top change event in the history. Pop off selection
7947
+ // events that are in the way.
7948
+ function lastChangeEvent(hist, force) {
7949
+ if (force) {
7950
+ clearSelectionEvents(hist.done);
7951
+ return lst(hist.done);
7952
+ } else if (hist.done.length && !lst(hist.done).ranges) {
7953
+ return lst(hist.done);
7954
+ } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) {
7955
+ hist.done.pop();
7956
+ return lst(hist.done);
7957
+ }
7958
+ }
7959
+
7960
+ // Register a change in the history. Merges changes that are within
7961
+ // a single operation, ore are close together with an origin that
7962
+ // allows merging (starting with "+") into a single event.
7963
+ function addChangeToHistory(doc, change, selAfter, opId) {
7964
+ var hist = doc.history;
7965
+ hist.undone.length = 0;
7966
+ var time = +new Date, cur;
7967
+
7968
+ if ((hist.lastOp == opId ||
7969
+ hist.lastOrigin == change.origin && change.origin &&
7970
+ ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) ||
7971
+ change.origin.charAt(0) == "*")) &&
7972
+ (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
7973
+ // Merge this change into the last event
7974
+ var last = lst(cur.changes);
7975
+ if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) {
7976
+ // Optimized case for simple insertion -- don't want to add
7977
+ // new changesets for every character typed
7978
+ last.to = changeEnd(change);
7979
+ } else {
7980
+ // Add new sub-event
7981
+ cur.changes.push(historyChangeFromChange(doc, change));
7982
+ }
7983
+ } else {
7984
+ // Can not be merged, start a new event.
7985
+ var before = lst(hist.done);
7986
+ if (!before || !before.ranges)
7987
+ pushSelectionToHistory(doc.sel, hist.done);
7988
+ cur = {changes: [historyChangeFromChange(doc, change)],
7989
+ generation: hist.generation};
7990
+ hist.done.push(cur);
7991
+ while (hist.done.length > hist.undoDepth) {
7992
+ hist.done.shift();
7993
+ if (!hist.done[0].ranges) hist.done.shift();
7994
+ }
7995
+ }
7996
+ hist.done.push(selAfter);
7997
+ hist.generation = ++hist.maxGeneration;
7998
+ hist.lastModTime = hist.lastSelTime = time;
7999
+ hist.lastOp = hist.lastSelOp = opId;
8000
+ hist.lastOrigin = hist.lastSelOrigin = change.origin;
8001
+
8002
+ if (!last) signal(doc, "historyAdded");
8003
+ }
8004
+
8005
+ function selectionEventCanBeMerged(doc, origin, prev, sel) {
8006
+ var ch = origin.charAt(0);
8007
+ return ch == "*" ||
8008
+ ch == "+" &&
8009
+ prev.ranges.length == sel.ranges.length &&
8010
+ prev.somethingSelected() == sel.somethingSelected() &&
8011
+ new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500);
8012
+ }
8013
+
8014
+ // Called whenever the selection changes, sets the new selection as
8015
+ // the pending selection in the history, and pushes the old pending
8016
+ // selection into the 'done' array when it was significantly
8017
+ // different (in number of selected ranges, emptiness, or time).
8018
+ function addSelectionToHistory(doc, sel, opId, options) {
8019
+ var hist = doc.history, origin = options && options.origin;
8020
+
8021
+ // A new event is started when the previous origin does not match
8022
+ // the current, or the origins don't allow matching. Origins
8023
+ // starting with * are always merged, those starting with + are
8024
+ // merged when similar and close together in time.
8025
+ if (opId == hist.lastSelOp ||
8026
+ (origin && hist.lastSelOrigin == origin &&
8027
+ (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin ||
8028
+ selectionEventCanBeMerged(doc, origin, lst(hist.done), sel))))
8029
+ hist.done[hist.done.length - 1] = sel;
8030
+ else
8031
+ pushSelectionToHistory(sel, hist.done);
8032
+
8033
+ hist.lastSelTime = +new Date;
8034
+ hist.lastSelOrigin = origin;
8035
+ hist.lastSelOp = opId;
8036
+ if (options && options.clearRedo !== false)
8037
+ clearSelectionEvents(hist.undone);
8038
+ }
8039
+
8040
+ function pushSelectionToHistory(sel, dest) {
8041
+ var top = lst(dest);
8042
+ if (!(top && top.ranges && top.equals(sel)))
8043
+ dest.push(sel);
8044
+ }
8045
+
8046
+ // Used to store marked span information in the history.
8047
+ function attachLocalSpans(doc, change, from, to) {
8048
+ var existing = change["spans_" + doc.id], n = 0;
8049
+ doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) {
8050
+ if (line.markedSpans)
8051
+ (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;
8052
+ ++n;
8053
+ });
8054
+ }
8055
+
8056
+ // When un/re-doing restores text containing marked spans, those
8057
+ // that have been explicitly cleared should not be restored.
8058
+ function removeClearedSpans(spans) {
8059
+ if (!spans) return null;
8060
+ for (var i = 0, out; i < spans.length; ++i) {
8061
+ if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); }
8062
+ else if (out) out.push(spans[i]);
8063
+ }
8064
+ return !out ? spans : out.length ? out : null;
8065
+ }
8066
+
8067
+ // Retrieve and filter the old marked spans stored in a change event.
8068
+ function getOldSpans(doc, change) {
8069
+ var found = change["spans_" + doc.id];
8070
+ if (!found) return null;
8071
+ for (var i = 0, nw = []; i < change.text.length; ++i)
8072
+ nw.push(removeClearedSpans(found[i]));
8073
+ return nw;
8074
+ }
8075
+
8076
+ // Used both to provide a JSON-safe object in .getHistory, and, when
8077
+ // detaching a document, to split the history in two
8078
+ function copyHistoryArray(events, newGroup, instantiateSel) {
8079
+ for (var i = 0, copy = []; i < events.length; ++i) {
8080
+ var event = events[i];
8081
+ if (event.ranges) {
8082
+ copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event);
8083
+ continue;
8084
+ }
8085
+ var changes = event.changes, newChanges = [];
8086
+ copy.push({changes: newChanges});
8087
+ for (var j = 0; j < changes.length; ++j) {
8088
+ var change = changes[j], m;
8089
+ newChanges.push({from: change.from, to: change.to, text: change.text});
8090
+ if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) {
8091
+ if (indexOf(newGroup, Number(m[1])) > -1) {
8092
+ lst(newChanges)[prop] = change[prop];
8093
+ delete change[prop];
8094
+ }
8095
+ }
8096
+ }
8097
+ }
8098
+ return copy;
8099
+ }
8100
+
8101
+ // Rebasing/resetting history to deal with externally-sourced changes
8102
+
8103
+ function rebaseHistSelSingle(pos, from, to, diff) {
8104
+ if (to < pos.line) {
8105
+ pos.line += diff;
8106
+ } else if (from < pos.line) {
8107
+ pos.line = from;
8108
+ pos.ch = 0;
8109
+ }
8110
+ }
8111
+
8112
+ // Tries to rebase an array of history events given a change in the
8113
+ // document. If the change touches the same lines as the event, the
8114
+ // event, and everything 'behind' it, is discarded. If the change is
8115
+ // before the event, the event's positions are updated. Uses a
8116
+ // copy-on-write scheme for the positions, to avoid having to
8117
+ // reallocate them all on every rebase, but also avoid problems with
8118
+ // shared position objects being unsafely updated.
8119
+ function rebaseHistArray(array, from, to, diff) {
8120
+ for (var i = 0; i < array.length; ++i) {
8121
+ var sub = array[i], ok = true;
8122
+ if (sub.ranges) {
8123
+ if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; }
8124
+ for (var j = 0; j < sub.ranges.length; j++) {
8125
+ rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff);
8126
+ rebaseHistSelSingle(sub.ranges[j].head, from, to, diff);
8127
+ }
8128
+ continue;
8129
+ }
8130
+ for (var j = 0; j < sub.changes.length; ++j) {
8131
+ var cur = sub.changes[j];
8132
+ if (to < cur.from.line) {
8133
+ cur.from = Pos(cur.from.line + diff, cur.from.ch);
8134
+ cur.to = Pos(cur.to.line + diff, cur.to.ch);
8135
+ } else if (from <= cur.to.line) {
8136
+ ok = false;
8137
+ break;
8138
+ }
8139
+ }
8140
+ if (!ok) {
8141
+ array.splice(0, i + 1);
8142
+ i = 0;
8143
+ }
8144
+ }
8145
+ }
8146
+
8147
+ function rebaseHist(hist, change) {
8148
+ var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1;
8149
+ rebaseHistArray(hist.done, from, to, diff);
8150
+ rebaseHistArray(hist.undone, from, to, diff);
8151
+ }
8152
+
8153
+ // EVENT UTILITIES
8154
+
8155
+ // Due to the fact that we still support jurassic IE versions, some
8156
+ // compatibility wrappers are needed.
8157
+
8158
+ var e_preventDefault = CodeMirror.e_preventDefault = function(e) {
8159
+ if (e.preventDefault) e.preventDefault();
8160
+ else e.returnValue = false;
8161
+ };
8162
+ var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) {
8163
+ if (e.stopPropagation) e.stopPropagation();
8164
+ else e.cancelBubble = true;
8165
+ };
8166
+ function e_defaultPrevented(e) {
8167
+ return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false;
8168
+ }
8169
+ var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);};
8170
+
8171
+ function e_target(e) {return e.target || e.srcElement;}
8172
+ function e_button(e) {
8173
+ var b = e.which;
8174
+ if (b == null) {
8175
+ if (e.button & 1) b = 1;
8176
+ else if (e.button & 2) b = 3;
8177
+ else if (e.button & 4) b = 2;
8178
+ }
8179
+ if (mac && e.ctrlKey && b == 1) b = 3;
8180
+ return b;
8181
+ }
8182
+
8183
+ // EVENT HANDLING
8184
+
8185
+ // Lightweight event framework. on/off also work on DOM nodes,
8186
+ // registering native DOM handlers.
8187
+
8188
+ var on = CodeMirror.on = function(emitter, type, f) {
8189
+ if (emitter.addEventListener)
8190
+ emitter.addEventListener(type, f, false);
8191
+ else if (emitter.attachEvent)
8192
+ emitter.attachEvent("on" + type, f);
8193
+ else {
8194
+ var map = emitter._handlers || (emitter._handlers = {});
8195
+ var arr = map[type] || (map[type] = []);
8196
+ arr.push(f);
8197
+ }
8198
+ };
8199
+
8200
+ var noHandlers = []
8201
+ function getHandlers(emitter, type, copy) {
8202
+ var arr = emitter._handlers && emitter._handlers[type]
8203
+ if (copy) return arr && arr.length > 0 ? arr.slice() : noHandlers
8204
+ else return arr || noHandlers
8205
+ }
8206
+
8207
+ var off = CodeMirror.off = function(emitter, type, f) {
8208
+ if (emitter.removeEventListener)
8209
+ emitter.removeEventListener(type, f, false);
8210
+ else if (emitter.detachEvent)
8211
+ emitter.detachEvent("on" + type, f);
8212
+ else {
8213
+ var handlers = getHandlers(emitter, type, false)
8214
+ for (var i = 0; i < handlers.length; ++i)
8215
+ if (handlers[i] == f) { handlers.splice(i, 1); break; }
8216
+ }
8217
+ };
8218
+
8219
+ var signal = CodeMirror.signal = function(emitter, type /*, values...*/) {
8220
+ var handlers = getHandlers(emitter, type, true)
8221
+ if (!handlers.length) return;
8222
+ var args = Array.prototype.slice.call(arguments, 2);
8223
+ for (var i = 0; i < handlers.length; ++i) handlers[i].apply(null, args);
8224
+ };
8225
+
8226
+ var orphanDelayedCallbacks = null;
8227
+
8228
+ // Often, we want to signal events at a point where we are in the
8229
+ // middle of some work, but don't want the handler to start calling
8230
+ // other methods on the editor, which might be in an inconsistent
8231
+ // state or simply not expect any other events to happen.
8232
+ // signalLater looks whether there are any handlers, and schedules
8233
+ // them to be executed when the last operation ends, or, if no
8234
+ // operation is active, when a timeout fires.
8235
+ function signalLater(emitter, type /*, values...*/) {
8236
+ var arr = getHandlers(emitter, type, false)
8237
+ if (!arr.length) return;
8238
+ var args = Array.prototype.slice.call(arguments, 2), list;
8239
+ if (operationGroup) {
8240
+ list = operationGroup.delayedCallbacks;
8241
+ } else if (orphanDelayedCallbacks) {
8242
+ list = orphanDelayedCallbacks;
8243
+ } else {
8244
+ list = orphanDelayedCallbacks = [];
8245
+ setTimeout(fireOrphanDelayed, 0);
8246
+ }
8247
+ function bnd(f) {return function(){f.apply(null, args);};};
8248
+ for (var i = 0; i < arr.length; ++i)
8249
+ list.push(bnd(arr[i]));
8250
+ }
8251
+
8252
+ function fireOrphanDelayed() {
8253
+ var delayed = orphanDelayedCallbacks;
8254
+ orphanDelayedCallbacks = null;
8255
+ for (var i = 0; i < delayed.length; ++i) delayed[i]();
8256
+ }
8257
+
8258
+ // The DOM events that CodeMirror handles can be overridden by
8259
+ // registering a (non-DOM) handler on the editor for the event name,
8260
+ // and preventDefault-ing the event in that handler.
8261
+ function signalDOMEvent(cm, e, override) {
8262
+ if (typeof e == "string")
8263
+ e = {type: e, preventDefault: function() { this.defaultPrevented = true; }};
8264
+ signal(cm, override || e.type, cm, e);
8265
+ return e_defaultPrevented(e) || e.codemirrorIgnore;
8266
+ }
8267
+
8268
+ function signalCursorActivity(cm) {
8269
+ var arr = cm._handlers && cm._handlers.cursorActivity;
8270
+ if (!arr) return;
8271
+ var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
8272
+ for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1)
8273
+ set.push(arr[i]);
8274
+ }
8275
+
8276
+ function hasHandler(emitter, type) {
8277
+ return getHandlers(emitter, type).length > 0
8278
+ }
8279
+
8280
+ // Add on and off methods to a constructor's prototype, to make
8281
+ // registering events on such objects more convenient.
8282
+ function eventMixin(ctor) {
8283
+ ctor.prototype.on = function(type, f) {on(this, type, f);};
8284
+ ctor.prototype.off = function(type, f) {off(this, type, f);};
8285
+ }
8286
+
8287
+ // MISC UTILITIES
8288
+
8289
+ // Number of pixels added to scroller and sizer to hide scrollbar
8290
+ var scrollerGap = 30;
8291
+
8292
+ // Returned or thrown by various protocols to signal 'I'm not
8293
+ // handling this'.
8294
+ var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}};
8295
+
8296
+ // Reused option objects for setSelection & friends
8297
+ var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"};
8298
+
8299
+ function Delayed() {this.id = null;}
8300
+ Delayed.prototype.set = function(ms, f) {
8301
+ clearTimeout(this.id);
8302
+ this.id = setTimeout(f, ms);
8303
+ };
8304
+
8305
+ // Counts the column offset in a string, taking tabs into account.
8306
+ // Used mostly to find indentation.
8307
+ var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) {
8308
+ if (end == null) {
8309
+ end = string.search(/[^\s\u00a0]/);
8310
+ if (end == -1) end = string.length;
8311
+ }
8312
+ for (var i = startIndex || 0, n = startValue || 0;;) {
8313
+ var nextTab = string.indexOf("\t", i);
8314
+ if (nextTab < 0 || nextTab >= end)
8315
+ return n + (end - i);
8316
+ n += nextTab - i;
8317
+ n += tabSize - (n % tabSize);
8318
+ i = nextTab + 1;
8319
+ }
8320
+ };
8321
+
8322
+ // The inverse of countColumn -- find the offset that corresponds to
8323
+ // a particular column.
8324
+ var findColumn = CodeMirror.findColumn = function(string, goal, tabSize) {
8325
+ for (var pos = 0, col = 0;;) {
8326
+ var nextTab = string.indexOf("\t", pos);
8327
+ if (nextTab == -1) nextTab = string.length;
8328
+ var skipped = nextTab - pos;
8329
+ if (nextTab == string.length || col + skipped >= goal)
8330
+ return pos + Math.min(skipped, goal - col);
8331
+ col += nextTab - pos;
8332
+ col += tabSize - (col % tabSize);
8333
+ pos = nextTab + 1;
8334
+ if (col >= goal) return pos;
8335
+ }
8336
+ }
8337
+
8338
+ var spaceStrs = [""];
8339
+ function spaceStr(n) {
8340
+ while (spaceStrs.length <= n)
8341
+ spaceStrs.push(lst(spaceStrs) + " ");
8342
+ return spaceStrs[n];
8343
+ }
8344
+
8345
+ function lst(arr) { return arr[arr.length-1]; }
8346
+
8347
+ var selectInput = function(node) { node.select(); };
8348
+ if (ios) // Mobile Safari apparently has a bug where select() is broken.
8349
+ selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };
8350
+ else if (ie) // Suppress mysterious IE10 errors
8351
+ selectInput = function(node) { try { node.select(); } catch(_e) {} };
8352
+
8353
+ function indexOf(array, elt) {
8354
+ for (var i = 0; i < array.length; ++i)
8355
+ if (array[i] == elt) return i;
8356
+ return -1;
8357
+ }
8358
+ function map(array, f) {
8359
+ var out = [];
8360
+ for (var i = 0; i < array.length; i++) out[i] = f(array[i], i);
8361
+ return out;
8362
+ }
8363
+
8364
+ function nothing() {}
8365
+
8366
+ function createObj(base, props) {
8367
+ var inst;
8368
+ if (Object.create) {
8369
+ inst = Object.create(base);
8370
+ } else {
8371
+ nothing.prototype = base;
8372
+ inst = new nothing();
8373
+ }
8374
+ if (props) copyObj(props, inst);
8375
+ return inst;
8376
+ };
8377
+
8378
+ function copyObj(obj, target, overwrite) {
8379
+ if (!target) target = {};
8380
+ for (var prop in obj)
8381
+ if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
8382
+ target[prop] = obj[prop];
8383
+ return target;
8384
+ }
8385
+
8386
+ function bind(f) {
8387
+ var args = Array.prototype.slice.call(arguments, 1);
8388
+ return function(){return f.apply(null, args);};
8389
+ }
8390
+
8391
+ var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
8392
+ var isWordCharBasic = CodeMirror.isWordChar = function(ch) {
8393
+ return /\w/.test(ch) || ch > "\x80" &&
8394
+ (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
8395
+ };
8396
+ function isWordChar(ch, helper) {
8397
+ if (!helper) return isWordCharBasic(ch);
8398
+ if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true;
8399
+ return helper.test(ch);
8400
+ }
8401
+
8402
+ function isEmpty(obj) {
8403
+ for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false;
8404
+ return true;
8405
+ }
8406
+
8407
+ // Extending unicode characters. A series of a non-extending char +
8408
+ // any number of extending chars is treated as a single unit as far
8409
+ // as editing and measuring is concerned. This is not fully correct,
8410
+ // since some scripts/fonts/browsers also treat other configurations
8411
+ // of code points as a group.
8412
+ 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]/;
8413
+ function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); }
8414
+
8415
+ // DOM UTILITIES
8416
+
8417
+ function elt(tag, content, className, style) {
8418
+ var e = document.createElement(tag);
8419
+ if (className) e.className = className;
8420
+ if (style) e.style.cssText = style;
8421
+ if (typeof content == "string") e.appendChild(document.createTextNode(content));
8422
+ else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]);
8423
+ return e;
8424
+ }
8425
+
8426
+ var range;
8427
+ if (document.createRange) range = function(node, start, end, endNode) {
8428
+ var r = document.createRange();
8429
+ r.setEnd(endNode || node, end);
8430
+ r.setStart(node, start);
8431
+ return r;
8432
+ };
8433
+ else range = function(node, start, end) {
8434
+ var r = document.body.createTextRange();
8435
+ try { r.moveToElementText(node.parentNode); }
8436
+ catch(e) { return r; }
8437
+ r.collapse(true);
8438
+ r.moveEnd("character", end);
8439
+ r.moveStart("character", start);
8440
+ return r;
8441
+ };
8442
+
8443
+ function removeChildren(e) {
8444
+ for (var count = e.childNodes.length; count > 0; --count)
8445
+ e.removeChild(e.firstChild);
8446
+ return e;
8447
+ }
8448
+
8449
+ function removeChildrenAndAdd(parent, e) {
8450
+ return removeChildren(parent).appendChild(e);
8451
+ }
8452
+
8453
+ var contains = CodeMirror.contains = function(parent, child) {
8454
+ if (child.nodeType == 3) // Android browser always returns false when child is a textnode
8455
+ child = child.parentNode;
8456
+ if (parent.contains)
8457
+ return parent.contains(child);
8458
+ do {
8459
+ if (child.nodeType == 11) child = child.host;
8460
+ if (child == parent) return true;
8461
+ } while (child = child.parentNode);
8462
+ };
8463
+
8464
+ function activeElt() {
8465
+ var activeElement = document.activeElement;
8466
+ while (activeElement && activeElement.root && activeElement.root.activeElement)
8467
+ activeElement = activeElement.root.activeElement;
8468
+ return activeElement;
8469
+ }
8470
+ // Older versions of IE throws unspecified error when touching
8471
+ // document.activeElement in some cases (during loading, in iframe)
8472
+ if (ie && ie_version < 11) activeElt = function() {
8473
+ try { return document.activeElement; }
8474
+ catch(e) { return document.body; }
8475
+ };
8476
+
8477
+ function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); }
8478
+ var rmClass = CodeMirror.rmClass = function(node, cls) {
8479
+ var current = node.className;
8480
+ var match = classTest(cls).exec(current);
8481
+ if (match) {
8482
+ var after = current.slice(match.index + match[0].length);
8483
+ node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
8484
+ }
8485
+ };
8486
+ var addClass = CodeMirror.addClass = function(node, cls) {
8487
+ var current = node.className;
8488
+ if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls;
8489
+ };
8490
+ function joinClasses(a, b) {
8491
+ var as = a.split(" ");
8492
+ for (var i = 0; i < as.length; i++)
8493
+ if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i];
8494
+ return b;
8495
+ }
8496
+
8497
+ // WINDOW-WIDE EVENTS
8498
+
8499
+ // These must be handled carefully, because naively registering a
8500
+ // handler for each editor will cause the editors to never be
8501
+ // garbage collected.
8502
+
8503
+ function forEachCodeMirror(f) {
8504
+ if (!document.body.getElementsByClassName) return;
8505
+ var byClass = document.body.getElementsByClassName("CodeMirror");
8506
+ for (var i = 0; i < byClass.length; i++) {
8507
+ var cm = byClass[i].CodeMirror;
8508
+ if (cm) f(cm);
8509
+ }
8510
+ }
8511
+
8512
+ var globalsRegistered = false;
8513
+ function ensureGlobalHandlers() {
8514
+ if (globalsRegistered) return;
8515
+ registerGlobalHandlers();
8516
+ globalsRegistered = true;
8517
+ }
8518
+ function registerGlobalHandlers() {
8519
+ // When the window resizes, we need to refresh active editors.
8520
+ var resizeTimer;
8521
+ on(window, "resize", function() {
8522
+ if (resizeTimer == null) resizeTimer = setTimeout(function() {
8523
+ resizeTimer = null;
8524
+ forEachCodeMirror(onResize);
8525
+ }, 100);
8526
+ });
8527
+ // When the window loses focus, we want to show the editor as blurred
8528
+ on(window, "blur", function() {
8529
+ forEachCodeMirror(onBlur);
8530
+ });
8531
+ }
8532
+
8533
+ // FEATURE DETECTION
8534
+
8535
+ // Detect drag-and-drop
8536
+ var dragAndDrop = function() {
8537
+ // There is *some* kind of drag-and-drop support in IE6-8, but I
8538
+ // couldn't get it to work yet.
8539
+ if (ie && ie_version < 9) return false;
8540
+ var div = elt('div');
8541
+ return "draggable" in div || "dragDrop" in div;
8542
+ }();
8543
+
8544
+ var zwspSupported;
8545
+ function zeroWidthElement(measure) {
8546
+ if (zwspSupported == null) {
8547
+ var test = elt("span", "\u200b");
8548
+ removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")]));
8549
+ if (measure.firstChild.offsetHeight != 0)
8550
+ zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8);
8551
+ }
8552
+ var node = zwspSupported ? elt("span", "\u200b") :
8553
+ elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
8554
+ node.setAttribute("cm-text", "");
8555
+ return node;
8556
+ }
8557
+
8558
+ // Feature-detect IE's crummy client rect reporting for bidi text
8559
+ var badBidiRects;
8560
+ function hasBadBidiRects(measure) {
8561
+ if (badBidiRects != null) return badBidiRects;
8562
+ var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA"));
8563
+ var r0 = range(txt, 0, 1).getBoundingClientRect();
8564
+ var r1 = range(txt, 1, 2).getBoundingClientRect();
8565
+ removeChildren(measure);
8566
+ if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780)
8567
+ return badBidiRects = (r1.right - r0.right < 3);
8568
+ }
8569
+
8570
+ // See if "".split is the broken IE version, if so, provide an
8571
+ // alternative way to split lines.
8572
+ var splitLinesAuto = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) {
8573
+ var pos = 0, result = [], l = string.length;
8574
+ while (pos <= l) {
8575
+ var nl = string.indexOf("\n", pos);
8576
+ if (nl == -1) nl = string.length;
8577
+ var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl);
8578
+ var rt = line.indexOf("\r");
8579
+ if (rt != -1) {
8580
+ result.push(line.slice(0, rt));
8581
+ pos += rt + 1;
8582
+ } else {
8583
+ result.push(line);
8584
+ pos = nl + 1;
8585
+ }
8586
+ }
8587
+ return result;
8588
+ } : function(string){return string.split(/\r\n?|\n/);};
8589
+
8590
+ var hasSelection = window.getSelection ? function(te) {
8591
+ try { return te.selectionStart != te.selectionEnd; }
8592
+ catch(e) { return false; }
8593
+ } : function(te) {
8594
+ try {var range = te.ownerDocument.selection.createRange();}
8595
+ catch(e) {}
8596
+ if (!range || range.parentElement() != te) return false;
8597
+ return range.compareEndPoints("StartToEnd", range) != 0;
8598
+ };
8599
+
8600
+ var hasCopyEvent = (function() {
8601
+ var e = elt("div");
8602
+ if ("oncopy" in e) return true;
8603
+ e.setAttribute("oncopy", "return;");
8604
+ return typeof e.oncopy == "function";
8605
+ })();
8606
+
8607
+ var badZoomedRects = null;
8608
+ function hasBadZoomedRects(measure) {
8609
+ if (badZoomedRects != null) return badZoomedRects;
8610
+ var node = removeChildrenAndAdd(measure, elt("span", "x"));
8611
+ var normal = node.getBoundingClientRect();
8612
+ var fromRange = range(node, 0, 1).getBoundingClientRect();
8613
+ return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1;
8614
+ }
8615
+
8616
+ // KEY NAMES
8617
+
8618
+ var keyNames = CodeMirror.keyNames = {
8619
+ 3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt",
8620
+ 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End",
8621
+ 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert",
8622
+ 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod",
8623
+ 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete",
8624
+ 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
8625
+ 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
8626
+ 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
8627
+ };
8628
+ (function() {
8629
+ // Number keys
8630
+ for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i);
8631
+ // Alphabetic keys
8632
+ for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i);
8633
+ // Function keys
8634
+ for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i;
8635
+ })();
8636
+
8637
+ // BIDI HELPERS
8638
+
8639
+ function iterateBidiSections(order, from, to, f) {
8640
+ if (!order) return f(from, to, "ltr");
8641
+ var found = false;
8642
+ for (var i = 0; i < order.length; ++i) {
8643
+ var part = order[i];
8644
+ if (part.from < to && part.to > from || from == to && part.to == from) {
8645
+ f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr");
8646
+ found = true;
8647
+ }
8648
+ }
8649
+ if (!found) f(from, to, "ltr");
8650
+ }
8651
+
8652
+ function bidiLeft(part) { return part.level % 2 ? part.to : part.from; }
8653
+ function bidiRight(part) { return part.level % 2 ? part.from : part.to; }
8654
+
8655
+ function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; }
8656
+ function lineRight(line) {
8657
+ var order = getOrder(line);
8658
+ if (!order) return line.text.length;
8659
+ return bidiRight(lst(order));
8660
+ }
8661
+
8662
+ function lineStart(cm, lineN) {
8663
+ var line = getLine(cm.doc, lineN);
8664
+ var visual = visualLine(line);
8665
+ if (visual != line) lineN = lineNo(visual);
8666
+ var order = getOrder(visual);
8667
+ var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual);
8668
+ return Pos(lineN, ch);
8669
+ }
8670
+ function lineEnd(cm, lineN) {
8671
+ var merged, line = getLine(cm.doc, lineN);
8672
+ while (merged = collapsedSpanAtEnd(line)) {
8673
+ line = merged.find(1, true).line;
8674
+ lineN = null;
8675
+ }
8676
+ var order = getOrder(line);
8677
+ var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line);
8678
+ return Pos(lineN == null ? lineNo(line) : lineN, ch);
8679
+ }
8680
+ function lineStartSmart(cm, pos) {
8681
+ var start = lineStart(cm, pos.line);
8682
+ var line = getLine(cm.doc, start.line);
8683
+ var order = getOrder(line);
8684
+ if (!order || order[0].level == 0) {
8685
+ var firstNonWS = Math.max(0, line.text.search(/\S/));
8686
+ var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
8687
+ return Pos(start.line, inWS ? 0 : firstNonWS);
8688
+ }
8689
+ return start;
8690
+ }
8691
+
8692
+ function compareBidiLevel(order, a, b) {
8693
+ var linedir = order[0].level;
8694
+ if (a == linedir) return true;
8695
+ if (b == linedir) return false;
8696
+ return a < b;
8697
+ }
8698
+ var bidiOther;
8699
+ function getBidiPartAt(order, pos) {
8700
+ bidiOther = null;
8701
+ for (var i = 0, found; i < order.length; ++i) {
8702
+ var cur = order[i];
8703
+ if (cur.from < pos && cur.to > pos) return i;
8704
+ if ((cur.from == pos || cur.to == pos)) {
8705
+ if (found == null) {
8706
+ found = i;
8707
+ } else if (compareBidiLevel(order, cur.level, order[found].level)) {
8708
+ if (cur.from != cur.to) bidiOther = found;
8709
+ return i;
8710
+ } else {
8711
+ if (cur.from != cur.to) bidiOther = i;
8712
+ return found;
8713
+ }
8714
+ }
8715
+ }
8716
+ return found;
8717
+ }
8718
+
8719
+ function moveInLine(line, pos, dir, byUnit) {
8720
+ if (!byUnit) return pos + dir;
8721
+ do pos += dir;
8722
+ while (pos > 0 && isExtendingChar(line.text.charAt(pos)));
8723
+ return pos;
8724
+ }
8725
+
8726
+ // This is needed in order to move 'visually' through bi-directional
8727
+ // text -- i.e., pressing left should make the cursor go left, even
8728
+ // when in RTL text. The tricky part is the 'jumps', where RTL and
8729
+ // LTR text touch each other. This often requires the cursor offset
8730
+ // to move more than one unit, in order to visually move one unit.
8731
+ function moveVisually(line, start, dir, byUnit) {
8732
+ var bidi = getOrder(line);
8733
+ if (!bidi) return moveLogically(line, start, dir, byUnit);
8734
+ var pos = getBidiPartAt(bidi, start), part = bidi[pos];
8735
+ var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit);
8736
+
8737
+ for (;;) {
8738
+ if (target > part.from && target < part.to) return target;
8739
+ if (target == part.from || target == part.to) {
8740
+ if (getBidiPartAt(bidi, target) == pos) return target;
8741
+ part = bidi[pos += dir];
8742
+ return (dir > 0) == part.level % 2 ? part.to : part.from;
8743
+ } else {
8744
+ part = bidi[pos += dir];
8745
+ if (!part) return null;
8746
+ if ((dir > 0) == part.level % 2)
8747
+ target = moveInLine(line, part.to, -1, byUnit);
8748
+ else
8749
+ target = moveInLine(line, part.from, 1, byUnit);
8750
+ }
8751
+ }
8752
+ }
8753
+
8754
+ function moveLogically(line, start, dir, byUnit) {
8755
+ var target = start + dir;
8756
+ if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir;
8757
+ return target < 0 || target > line.text.length ? null : target;
8758
+ }
8759
+
8760
+ // Bidirectional ordering algorithm
8761
+ // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm
8762
+ // that this (partially) implements.
8763
+
8764
+ // One-char codes used for character types:
8765
+ // L (L): Left-to-Right
8766
+ // R (R): Right-to-Left
8767
+ // r (AL): Right-to-Left Arabic
8768
+ // 1 (EN): European Number
8769
+ // + (ES): European Number Separator
8770
+ // % (ET): European Number Terminator
8771
+ // n (AN): Arabic Number
8772
+ // , (CS): Common Number Separator
8773
+ // m (NSM): Non-Spacing Mark
8774
+ // b (BN): Boundary Neutral
8775
+ // s (B): Paragraph Separator
8776
+ // t (S): Segment Separator
8777
+ // w (WS): Whitespace
8778
+ // N (ON): Other Neutrals
8779
+
8780
+ // Returns null if characters are ordered as they appear
8781
+ // (left-to-right), or an array of sections ({from, to, level}
8782
+ // objects) in the order in which they occur visually.
8783
+ var bidiOrdering = (function() {
8784
+ // Character types for codepoints 0 to 0xff
8785
+ var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN";
8786
+ // Character types for codepoints 0x600 to 0x6ff
8787
+ var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm";
8788
+ function charType(code) {
8789
+ if (code <= 0xf7) return lowTypes.charAt(code);
8790
+ else if (0x590 <= code && code <= 0x5f4) return "R";
8791
+ else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600);
8792
+ else if (0x6ee <= code && code <= 0x8ac) return "r";
8793
+ else if (0x2000 <= code && code <= 0x200b) return "w";
8794
+ else if (code == 0x200c) return "b";
8795
+ else return "L";
8796
+ }
8797
+
8798
+ var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;
8799
+ var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/;
8800
+ // Browsers seem to always treat the boundaries of block elements as being L.
8801
+ var outerType = "L";
8802
+
8803
+ function BidiSpan(level, from, to) {
8804
+ this.level = level;
8805
+ this.from = from; this.to = to;
8806
+ }
8807
+
8808
+ return function(str) {
8809
+ if (!bidiRE.test(str)) return false;
8810
+ var len = str.length, types = [];
8811
+ for (var i = 0, type; i < len; ++i)
8812
+ types.push(type = charType(str.charCodeAt(i)));
8813
+
8814
+ // W1. Examine each non-spacing mark (NSM) in the level run, and
8815
+ // change the type of the NSM to the type of the previous
8816
+ // character. If the NSM is at the start of the level run, it will
8817
+ // get the type of sor.
8818
+ for (var i = 0, prev = outerType; i < len; ++i) {
8819
+ var type = types[i];
8820
+ if (type == "m") types[i] = prev;
8821
+ else prev = type;
8822
+ }
8823
+
8824
+ // W2. Search backwards from each instance of a European number
8825
+ // until the first strong type (R, L, AL, or sor) is found. If an
8826
+ // AL is found, change the type of the European number to Arabic
8827
+ // number.
8828
+ // W3. Change all ALs to R.
8829
+ for (var i = 0, cur = outerType; i < len; ++i) {
8830
+ var type = types[i];
8831
+ if (type == "1" && cur == "r") types[i] = "n";
8832
+ else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; }
8833
+ }
8834
+
8835
+ // W4. A single European separator between two European numbers
8836
+ // changes to a European number. A single common separator between
8837
+ // two numbers of the same type changes to that type.
8838
+ for (var i = 1, prev = types[0]; i < len - 1; ++i) {
8839
+ var type = types[i];
8840
+ if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1";
8841
+ else if (type == "," && prev == types[i+1] &&
8842
+ (prev == "1" || prev == "n")) types[i] = prev;
8843
+ prev = type;
8844
+ }
8845
+
8846
+ // W5. A sequence of European terminators adjacent to European
8847
+ // numbers changes to all European numbers.
8848
+ // W6. Otherwise, separators and terminators change to Other
8849
+ // Neutral.
8850
+ for (var i = 0; i < len; ++i) {
8851
+ var type = types[i];
8852
+ if (type == ",") types[i] = "N";
8853
+ else if (type == "%") {
8854
+ for (var end = i + 1; end < len && types[end] == "%"; ++end) {}
8855
+ var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
8856
+ for (var j = i; j < end; ++j) types[j] = replace;
8857
+ i = end - 1;
8858
+ }
8859
+ }
8860
+
8861
+ // W7. Search backwards from each instance of a European number
8862
+ // until the first strong type (R, L, or sor) is found. If an L is
8863
+ // found, then change the type of the European number to L.
8864
+ for (var i = 0, cur = outerType; i < len; ++i) {
8865
+ var type = types[i];
8866
+ if (cur == "L" && type == "1") types[i] = "L";
8867
+ else if (isStrong.test(type)) cur = type;
8868
+ }
8869
+
8870
+ // N1. A sequence of neutrals takes the direction of the
8871
+ // surrounding strong text if the text on both sides has the same
8872
+ // direction. European and Arabic numbers act as if they were R in
8873
+ // terms of their influence on neutrals. Start-of-level-run (sor)
8874
+ // and end-of-level-run (eor) are used at level run boundaries.
8875
+ // N2. Any remaining neutrals take the embedding direction.
8876
+ for (var i = 0; i < len; ++i) {
8877
+ if (isNeutral.test(types[i])) {
8878
+ for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {}
8879
+ var before = (i ? types[i-1] : outerType) == "L";
8880
+ var after = (end < len ? types[end] : outerType) == "L";
8881
+ var replace = before || after ? "L" : "R";
8882
+ for (var j = i; j < end; ++j) types[j] = replace;
8883
+ i = end - 1;
8884
+ }
8885
+ }
8886
+
8887
+ // Here we depart from the documented algorithm, in order to avoid
8888
+ // building up an actual levels array. Since there are only three
8889
+ // levels (0, 1, 2) in an implementation that doesn't take
8890
+ // explicit embedding into account, we can build up the order on
8891
+ // the fly, without following the level-based algorithm.
8892
+ var order = [], m;
8893
+ for (var i = 0; i < len;) {
8894
+ if (countsAsLeft.test(types[i])) {
8895
+ var start = i;
8896
+ for (++i; i < len && countsAsLeft.test(types[i]); ++i) {}
8897
+ order.push(new BidiSpan(0, start, i));
8898
+ } else {
8899
+ var pos = i, at = order.length;
8900
+ for (++i; i < len && types[i] != "L"; ++i) {}
8901
+ for (var j = pos; j < i;) {
8902
+ if (countsAsNum.test(types[j])) {
8903
+ if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j));
8904
+ var nstart = j;
8905
+ for (++j; j < i && countsAsNum.test(types[j]); ++j) {}
8906
+ order.splice(at, 0, new BidiSpan(2, nstart, j));
8907
+ pos = j;
8908
+ } else ++j;
8909
+ }
8910
+ if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i));
8911
+ }
8912
+ }
8913
+ if (order[0].level == 1 && (m = str.match(/^\s+/))) {
8914
+ order[0].from = m[0].length;
8915
+ order.unshift(new BidiSpan(0, 0, m[0].length));
8916
+ }
8917
+ if (lst(order).level == 1 && (m = str.match(/\s+$/))) {
8918
+ lst(order).to -= m[0].length;
8919
+ order.push(new BidiSpan(0, len - m[0].length, len));
8920
+ }
8921
+ if (order[0].level == 2)
8922
+ order.unshift(new BidiSpan(1, order[0].to, order[0].to));
8923
+ if (order[0].level != lst(order).level)
8924
+ order.push(new BidiSpan(order[0].level, len, len));
8925
+
8926
+ return order;
8927
+ };
8928
+ })();
8929
+
8930
+ // THE END
8931
+
8932
+ CodeMirror.version = "5.17.0";
8933
+
8934
+ return CodeMirror;
8935
+ });
inc/lib/codemirror/mode/css.js ADDED
@@ -0,0 +1,825 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // CodeMirror, copyright (c) by Marijn Haverbeke and others
2
+ // Distributed under an MIT license: http://codemirror.net/LICENSE
3
+
4
+ (function(mod) {
5
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
6
+ mod(require("../../lib/codemirror"));
7
+ else if (typeof define == "function" && define.amd) // AMD
8
+ define(["../../lib/codemirror"], mod);
9
+ else // Plain browser env
10
+ mod(CodeMirror);
11
+ })(function(CodeMirror) {
12
+ "use strict";
13
+
14
+ CodeMirror.defineMode("css", function(config, parserConfig) {
15
+ var inline = parserConfig.inline
16
+ if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode("text/css");
17
+
18
+ var indentUnit = config.indentUnit,
19
+ tokenHooks = parserConfig.tokenHooks,
20
+ documentTypes = parserConfig.documentTypes || {},
21
+ mediaTypes = parserConfig.mediaTypes || {},
22
+ mediaFeatures = parserConfig.mediaFeatures || {},
23
+ mediaValueKeywords = parserConfig.mediaValueKeywords || {},
24
+ propertyKeywords = parserConfig.propertyKeywords || {},
25
+ nonStandardPropertyKeywords = parserConfig.nonStandardPropertyKeywords || {},
26
+ fontProperties = parserConfig.fontProperties || {},
27
+ counterDescriptors = parserConfig.counterDescriptors || {},
28
+ colorKeywords = parserConfig.colorKeywords || {},
29
+ valueKeywords = parserConfig.valueKeywords || {},
30
+ allowNested = parserConfig.allowNested,
31
+ supportsAtComponent = parserConfig.supportsAtComponent === true;
32
+
33
+ var type, override;
34
+ function ret(style, tp) { type = tp; return style; }
35
+
36
+ // Tokenizers
37
+
38
+ function tokenBase(stream, state) {
39
+ var ch = stream.next();
40
+ if (tokenHooks[ch]) {
41
+ var result = tokenHooks[ch](stream, state);
42
+ if (result !== false) return result;
43
+ }
44
+ if (ch == "@") {
45
+ stream.eatWhile(/[\w\\\-]/);
46
+ return ret("def", stream.current());
47
+ } else if (ch == "=" || (ch == "~" || ch == "|") && stream.eat("=")) {
48
+ return ret(null, "compare");
49
+ } else if (ch == "\"" || ch == "'") {
50
+ state.tokenize = tokenString(ch);
51
+ return state.tokenize(stream, state);
52
+ } else if (ch == "#") {
53
+ stream.eatWhile(/[\w\\\-]/);
54
+ return ret("atom", "hash");
55
+ } else if (ch == "!") {
56
+ stream.match(/^\s*\w*/);
57
+ return ret("keyword", "important");
58
+ } else if (/\d/.test(ch) || ch == "." && stream.eat(/\d/)) {
59
+ stream.eatWhile(/[\w.%]/);
60
+ return ret("number", "unit");
61
+ } else if (ch === "-") {
62
+ if (/[\d.]/.test(stream.peek())) {
63
+ stream.eatWhile(/[\w.%]/);
64
+ return ret("number", "unit");
65
+ } else if (stream.match(/^-[\w\\\-]+/)) {
66
+ stream.eatWhile(/[\w\\\-]/);
67
+ if (stream.match(/^\s*:/, false))
68
+ return ret("variable-2", "variable-definition");
69
+ return ret("variable-2", "variable");
70
+ } else if (stream.match(/^\w+-/)) {
71
+ return ret("meta", "meta");
72
+ }
73
+ } else if (/[,+>*\/]/.test(ch)) {
74
+ return ret(null, "select-op");
75
+ } else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) {
76
+ return ret("qualifier", "qualifier");
77
+ } else if (/[:;{}\[\]\(\)]/.test(ch)) {
78
+ return ret(null, ch);
79
+ } else if ((ch == "u" && stream.match(/rl(-prefix)?\(/)) ||
80
+ (ch == "d" && stream.match("omain(")) ||
81
+ (ch == "r" && stream.match("egexp("))) {
82
+ stream.backUp(1);
83
+ state.tokenize = tokenParenthesized;
84
+ return ret("property", "word");
85
+ } else if (/[\w\\\-]/.test(ch)) {
86
+ stream.eatWhile(/[\w\\\-]/);
87
+ return ret("property", "word");
88
+ } else {
89
+ return ret(null, null);
90
+ }
91
+ }
92
+
93
+ function tokenString(quote) {
94
+ return function(stream, state) {
95
+ var escaped = false, ch;
96
+ while ((ch = stream.next()) != null) {
97
+ if (ch == quote && !escaped) {
98
+ if (quote == ")") stream.backUp(1);
99
+ break;
100
+ }
101
+ escaped = !escaped && ch == "\\";
102
+ }
103
+ if (ch == quote || !escaped && quote != ")") state.tokenize = null;
104
+ return ret("string", "string");
105
+ };
106
+ }
107
+
108
+ function tokenParenthesized(stream, state) {
109
+ stream.next(); // Must be '('
110
+ if (!stream.match(/\s*[\"\')]/, false))
111
+ state.tokenize = tokenString(")");
112
+ else
113
+ state.tokenize = null;
114
+ return ret(null, "(");
115
+ }
116
+
117
+ // Context management
118
+
119
+ function Context(type, indent, prev) {
120
+ this.type = type;
121
+ this.indent = indent;
122
+ this.prev = prev;
123
+ }
124
+
125
+ function pushContext(state, stream, type, indent) {
126
+ state.context = new Context(type, stream.indentation() + (indent === false ? 0 : indentUnit), state.context);
127
+ return type;
128
+ }
129
+
130
+ function popContext(state) {
131
+ if (state.context.prev)
132
+ state.context = state.context.prev;
133
+ return state.context.type;
134
+ }
135
+
136
+ function pass(type, stream, state) {
137
+ return states[state.context.type](type, stream, state);
138
+ }
139
+ function popAndPass(type, stream, state, n) {
140
+ for (var i = n || 1; i > 0; i--)
141
+ state.context = state.context.prev;
142
+ return pass(type, stream, state);
143
+ }
144
+
145
+ // Parser
146
+
147
+ function wordAsValue(stream) {
148
+ var word = stream.current().toLowerCase();
149
+ if (valueKeywords.hasOwnProperty(word))
150
+ override = "atom";
151
+ else if (colorKeywords.hasOwnProperty(word))
152
+ override = "keyword";
153
+ else
154
+ override = "variable";
155
+ }
156
+
157
+ var states = {};
158
+
159
+ states.top = function(type, stream, state) {
160
+ if (type == "{") {
161
+ return pushContext(state, stream, "block");
162
+ } else if (type == "}" && state.context.prev) {
163
+ return popContext(state);
164
+ } else if (supportsAtComponent && /@component/.test(type)) {
165
+ return pushContext(state, stream, "atComponentBlock");
166
+ } else if (/^@(-moz-)?document$/.test(type)) {
167
+ return pushContext(state, stream, "documentTypes");
168
+ } else if (/^@(media|supports|(-moz-)?document|import)$/.test(type)) {
169
+ return pushContext(state, stream, "atBlock");
170
+ } else if (/^@(font-face|counter-style)/.test(type)) {
171
+ state.stateArg = type;
172
+ return "restricted_atBlock_before";
173
+ } else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/.test(type)) {
174
+ return "keyframes";
175
+ } else if (type && type.charAt(0) == "@") {
176
+ return pushContext(state, stream, "at");
177
+ } else if (type == "hash") {
178
+ override = "builtin";
179
+ } else if (type == "word") {
180
+ override = "tag";
181
+ } else if (type == "variable-definition") {
182
+ return "maybeprop";
183
+ } else if (type == "interpolation") {
184
+ return pushContext(state, stream, "interpolation");
185
+ } else if (type == ":") {
186
+ return "pseudo";
187
+ } else if (allowNested && type == "(") {
188
+ return pushContext(state, stream, "parens");
189
+ }
190
+ return state.context.type;
191
+ };
192
+
193
+ states.block = function(type, stream, state) {
194
+ if (type == "word") {
195
+ var word = stream.current().toLowerCase();
196
+ if (propertyKeywords.hasOwnProperty(word)) {
197
+ override = "property";
198
+ return "maybeprop";
199
+ } else if (nonStandardPropertyKeywords.hasOwnProperty(word)) {
200
+ override = "string-2";
201
+ return "maybeprop";
202
+ } else if (allowNested) {
203
+ override = stream.match(/^\s*:(?:\s|$)/, false) ? "property" : "tag";
204
+ return "block";
205
+ } else {
206
+ override += " error";
207
+ return "maybeprop";
208
+ }
209
+ } else if (type == "meta") {
210
+ return "block";
211
+ } else if (!allowNested && (type == "hash" || type == "qualifier")) {
212
+ override = "error";
213
+ return "block";
214
+ } else {
215
+ return states.top(type, stream, state);
216
+ }
217
+ };
218
+
219
+ states.maybeprop = function(type, stream, state) {
220
+ if (type == ":") return pushContext(state, stream, "prop");
221
+ return pass(type, stream, state);
222
+ };
223
+
224
+ states.prop = function(type, stream, state) {
225
+ if (type == ";") return popContext(state);
226
+ if (type == "{" && allowNested) return pushContext(state, stream, "propBlock");
227
+ if (type == "}" || type == "{") return popAndPass(type, stream, state);
228
+ if (type == "(") return pushContext(state, stream, "parens");
229
+
230
+ if (type == "hash" && !/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(stream.current())) {
231
+ override += " error";
232
+ } else if (type == "word") {
233
+ wordAsValue(stream);
234
+ } else if (type == "interpolation") {
235
+ return pushContext(state, stream, "interpolation");
236
+ }
237
+ return "prop";
238
+ };
239
+
240
+ states.propBlock = function(type, _stream, state) {
241
+ if (type == "}") return popContext(state);
242
+ if (type == "word") { override = "property"; return "maybeprop"; }
243
+ return state.context.type;
244
+ };
245
+
246
+ states.parens = function(type, stream, state) {
247
+ if (type == "{" || type == "}") return popAndPass(type, stream, state);
248
+ if (type == ")") return popContext(state);
249
+ if (type == "(") return pushContext(state, stream, "parens");
250
+ if (type == "interpolation") return pushContext(state, stream, "interpolation");
251
+ if (type == "word") wordAsValue(stream);
252
+ return "parens";
253
+ };
254
+
255
+ states.pseudo = function(type, stream, state) {
256
+ if (type == "word") {
257
+ override = "variable-3";
258
+ return state.context.type;
259
+ }
260
+ return pass(type, stream, state);
261
+ };
262
+
263
+ states.documentTypes = function(type, stream, state) {
264
+ if (type == "word" && documentTypes.hasOwnProperty(stream.current())) {
265
+ override = "tag";
266
+ return state.context.type;
267
+ } else {
268
+ return states.atBlock(type, stream, state);
269
+ }
270
+ };
271
+
272
+ states.atBlock = function(type, stream, state) {
273
+ if (type == "(") return pushContext(state, stream, "atBlock_parens");
274
+ if (type == "}" || type == ";") return popAndPass(type, stream, state);
275
+ if (type == "{") return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top");
276
+
277
+ if (type == "interpolation") return pushContext(state, stream, "interpolation");
278
+
279
+ if (type == "word") {
280
+ var word = stream.current().toLowerCase();
281
+ if (word == "only" || word == "not" || word == "and" || word == "or")
282
+ override = "keyword";
283
+ else if (mediaTypes.hasOwnProperty(word))
284
+ override = "attribute";
285
+ else if (mediaFeatures.hasOwnProperty(word))
286
+ override = "property";
287
+ else if (mediaValueKeywords.hasOwnProperty(word))
288
+ override = "keyword";
289
+ else if (propertyKeywords.hasOwnProperty(word))
290
+ override = "property";
291
+ else if (nonStandardPropertyKeywords.hasOwnProperty(word))
292
+ override = "string-2";
293
+ else if (valueKeywords.hasOwnProperty(word))
294
+ override = "atom";
295
+ else if (colorKeywords.hasOwnProperty(word))
296
+ override = "keyword";
297
+ else
298
+ override = "error";
299
+ }
300
+ return state.context.type;
301
+ };
302
+
303
+ states.atComponentBlock = function(type, stream, state) {
304
+ if (type == "}")
305
+ return popAndPass(type, stream, state);
306
+ if (type == "{")
307
+ return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top", false);
308
+ if (type == "word")
309
+ override = "error";
310
+ return state.context.type;
311
+ };
312
+
313
+ states.atBlock_parens = function(type, stream, state) {
314
+ if (type == ")") return popContext(state);
315
+ if (type == "{" || type == "}") return popAndPass(type, stream, state, 2);
316
+ return states.atBlock(type, stream, state);
317
+ };
318
+
319
+ states.restricted_atBlock_before = function(type, stream, state) {
320
+ if (type == "{")
321
+ return pushContext(state, stream, "restricted_atBlock");
322
+ if (type == "word" && state.stateArg == "@counter-style") {
323
+ override = "variable";
324
+ return "restricted_atBlock_before";
325
+ }
326
+ return pass(type, stream, state);
327
+ };
328
+
329
+ states.restricted_atBlock = function(type, stream, state) {
330
+ if (type == "}") {
331
+ state.stateArg = null;
332
+ return popContext(state);
333
+ }
334
+ if (type == "word") {
335
+ if ((state.stateArg == "@font-face" && !fontProperties.hasOwnProperty(stream.current().toLowerCase())) ||
336
+ (state.stateArg == "@counter-style" && !counterDescriptors.hasOwnProperty(stream.current().toLowerCase())))
337
+ override = "error";
338
+ else
339
+ override = "property";
340
+ return "maybeprop";
341
+ }
342
+ return "restricted_atBlock";
343
+ };
344
+
345
+ states.keyframes = function(type, stream, state) {
346
+ if (type == "word") { override = "variable"; return "keyframes"; }
347
+ if (type == "{") return pushContext(state, stream, "top");
348
+ return pass(type, stream, state);
349
+ };
350
+
351
+ states.at = function(type, stream, state) {
352
+ if (type == ";") return popContext(state);
353
+ if (type == "{" || type == "}") return popAndPass(type, stream, state);
354
+ if (type == "word") override = "tag";
355
+ else if (type == "hash") override = "builtin";
356
+ return "at";
357
+ };
358
+
359
+ states.interpolation = function(type, stream, state) {
360
+ if (type == "}") return popContext(state);
361
+ if (type == "{" || type == ";") return popAndPass(type, stream, state);
362
+ if (type == "word") override = "variable";
363
+ else if (type != "variable" && type != "(" && type != ")") override = "error";
364
+ return "interpolation";
365
+ };
366
+
367
+ return {
368
+ startState: function(base) {
369
+ return {tokenize: null,
370
+ state: inline ? "block" : "top",
371
+ stateArg: null,
372
+ context: new Context(inline ? "block" : "top", base || 0, null)};
373
+ },
374
+
375
+ token: function(stream, state) {
376
+ if (!state.tokenize && stream.eatSpace()) return null;
377
+ var style = (state.tokenize || tokenBase)(stream, state);
378
+ if (style && typeof style == "object") {
379
+ type = style[1];
380
+ style = style[0];
381
+ }
382
+ override = style;
383
+ state.state = states[state.state](type, stream, state);
384
+ return override;
385
+ },
386
+
387
+ indent: function(state, textAfter) {
388
+ var cx = state.context, ch = textAfter && textAfter.charAt(0);
389
+ var indent = cx.indent;
390
+ if (cx.type == "prop" && (ch == "}" || ch == ")")) cx = cx.prev;
391
+ if (cx.prev) {
392
+ if (ch == "}" && (cx.type == "block" || cx.type == "top" ||
393
+ cx.type == "interpolation" || cx.type == "restricted_atBlock")) {
394
+ // Resume indentation from parent context.
395
+ cx = cx.prev;
396
+ indent = cx.indent;
397
+ } else if (ch == ")" && (cx.type == "parens" || cx.type == "atBlock_parens") ||
398
+ ch == "{" && (cx.type == "at" || cx.type == "atBlock")) {
399
+ // Dedent relative to current context.
400
+ indent = Math.max(0, cx.indent - indentUnit);
401
+ cx = cx.prev;
402
+ }
403
+ }
404
+ return indent;
405
+ },
406
+
407
+ electricChars: "}",
408
+ blockCommentStart: "/*",
409
+ blockCommentEnd: "*/",
410
+ fold: "brace"
411
+ };
412
+ });
413
+
414
+ function keySet(array) {
415
+ var keys = {};
416
+ for (var i = 0; i < array.length; ++i) {
417
+ keys[array[i]] = true;
418
+ }
419
+ return keys;
420
+ }
421
+
422
+ var documentTypes_ = [
423
+ "domain", "regexp", "url", "url-prefix"
424
+ ], documentTypes = keySet(documentTypes_);
425
+
426
+ var mediaTypes_ = [
427
+ "all", "aural", "braille", "handheld", "print", "projection", "screen",
428
+ "tty", "tv", "embossed"
429
+ ], mediaTypes = keySet(mediaTypes_);
430
+
431
+ var mediaFeatures_ = [
432
+ "width", "min-width", "max-width", "height", "min-height", "max-height",
433
+ "device-width", "min-device-width", "max-device-width", "device-height",
434
+ "min-device-height", "max-device-height", "aspect-ratio",
435
+ "min-aspect-ratio", "max-aspect-ratio", "device-aspect-ratio",
436
+ "min-device-aspect-ratio", "max-device-aspect-ratio", "color", "min-color",
437
+ "max-color", "color-index", "min-color-index", "max-color-index",
438
+ "monochrome", "min-monochrome", "max-monochrome", "resolution",
439
+ "min-resolution", "max-resolution", "scan", "grid", "orientation",
440
+ "device-pixel-ratio", "min-device-pixel-ratio", "max-device-pixel-ratio",
441
+ "pointer", "any-pointer", "hover", "any-hover"
442
+ ], mediaFeatures = keySet(mediaFeatures_);
443
+
444
+ var mediaValueKeywords_ = [
445
+ "landscape", "portrait", "none", "coarse", "fine", "on-demand", "hover",
446
+ "interlace", "progressive"
447
+ ], mediaValueKeywords = keySet(mediaValueKeywords_);
448
+
449
+ var propertyKeywords_ = [
450
+ "align-content", "align-items", "align-self", "alignment-adjust",
451
+ "alignment-baseline", "anchor-point", "animation", "animation-delay",
452
+ "animation-direction", "animation-duration", "animation-fill-mode",
453
+ "animation-iteration-count", "animation-name", "animation-play-state",
454
+ "animation-timing-function", "appearance", "azimuth", "backface-visibility",
455
+ "background", "background-attachment", "background-blend-mode", "background-clip",
456
+ "background-color", "background-image", "background-origin", "background-position",
457
+ "background-repeat", "background-size", "baseline-shift", "binding",
458
+ "bleed", "bookmark-label", "bookmark-level", "bookmark-state",
459
+ "bookmark-target", "border", "border-bottom", "border-bottom-color",
460
+ "border-bottom-left-radius", "border-bottom-right-radius",
461
+ "border-bottom-style", "border-bottom-width", "border-collapse",
462
+ "border-color", "border-image", "border-image-outset",
463
+ "border-image-repeat", "border-image-slice", "border-image-source",
464
+ "border-image-width", "border-left", "border-left-color",
465
+ "border-left-style", "border-left-width", "border-radius", "border-right",
466
+ "border-right-color", "border-right-style", "border-right-width",
467
+ "border-spacing", "border-style", "border-top", "border-top-color",
468
+ "border-top-left-radius", "border-top-right-radius", "border-top-style",
469
+ "border-top-width", "border-width", "bottom", "box-decoration-break",
470
+ "box-shadow", "box-sizing", "break-after", "break-before", "break-inside",
471
+ "caption-side", "clear", "clip", "color", "color-profile", "column-count",
472
+ "column-fill", "column-gap", "column-rule", "column-rule-color",
473
+ "column-rule-style", "column-rule-width", "column-span", "column-width",
474
+ "columns", "content", "counter-increment", "counter-reset", "crop", "cue",
475
+ "cue-after", "cue-before", "cursor", "direction", "display",
476
+ "dominant-baseline", "drop-initial-after-adjust",
477
+ "drop-initial-after-align", "drop-initial-before-adjust",
478
+ "drop-initial-before-align", "drop-initial-size", "drop-initial-value",
479
+ "elevation", "empty-cells", "fit", "fit-position", "flex", "flex-basis",
480
+ "flex-direction", "flex-flow", "flex-grow", "flex-shrink", "flex-wrap",
481
+ "float", "float-offset", "flow-from", "flow-into", "font", "font-feature-settings",
482
+ "font-family", "font-kerning", "font-language-override", "font-size", "font-size-adjust",
483
+ "font-stretch", "font-style", "font-synthesis", "font-variant",
484
+ "font-variant-alternates", "font-variant-caps", "font-variant-east-asian",
485
+ "font-variant-ligatures", "font-variant-numeric", "font-variant-position",
486
+ "font-weight", "grid", "grid-area", "grid-auto-columns", "grid-auto-flow",
487
+ "grid-auto-rows", "grid-column", "grid-column-end", "grid-column-gap",
488
+ "grid-column-start", "grid-gap", "grid-row", "grid-row-end", "grid-row-gap",
489
+ "grid-row-start", "grid-template", "grid-template-areas", "grid-template-columns",
490
+ "grid-template-rows", "hanging-punctuation", "height", "hyphens",
491
+ "icon", "image-orientation", "image-rendering", "image-resolution",
492
+ "inline-box-align", "justify-content", "left", "letter-spacing",
493
+ "line-break", "line-height", "line-stacking", "line-stacking-ruby",
494
+ "line-stacking-shift", "line-stacking-strategy", "list-style",
495
+ "list-style-image", "list-style-position", "list-style-type", "margin",
496
+ "margin-bottom", "margin-left", "margin-right", "margin-top",
497
+ "marker-offset", "marks", "marquee-direction", "marquee-loop",
498
+ "marquee-play-count", "marquee-speed", "marquee-style", "max-height",
499
+ "max-width", "min-height", "min-width", "move-to", "nav-down", "nav-index",
500
+ "nav-left", "nav-right", "nav-up", "object-fit", "object-position",
501
+ "opacity", "order", "orphans", "outline",
502
+ "outline-color", "outline-offset", "outline-style", "outline-width",
503
+ "overflow", "overflow-style", "overflow-wrap", "overflow-x", "overflow-y",
504
+ "padding", "padding-bottom", "padding-left", "padding-right", "padding-top",
505
+ "page", "page-break-after", "page-break-before", "page-break-inside",
506
+ "page-policy", "pause", "pause-after", "pause-before", "perspective",
507
+ "perspective-origin", "pitch", "pitch-range", "play-during", "position",
508
+ "presentation-level", "punctuation-trim", "quotes", "region-break-after",
509
+ "region-break-before", "region-break-inside", "region-fragment",
510
+ "rendering-intent", "resize", "rest", "rest-after", "rest-before", "richness",
511
+ "right", "rotation", "rotation-point", "ruby-align", "ruby-overhang",
512
+ "ruby-position", "ruby-span", "shape-image-threshold", "shape-inside", "shape-margin",
513
+ "shape-outside", "size", "speak", "speak-as", "speak-header",
514
+ "speak-numeral", "speak-punctuation", "speech-rate", "stress", "string-set",
515
+ "tab-size", "table-layout", "target", "target-name", "target-new",
516
+ "target-position", "text-align", "text-align-last", "text-decoration",
517
+ "text-decoration-color", "text-decoration-line", "text-decoration-skip",
518
+ "text-decoration-style", "text-emphasis", "text-emphasis-color",
519
+ "text-emphasis-position", "text-emphasis-style", "text-height",
520
+ "text-indent", "text-justify", "text-outline", "text-overflow", "text-shadow",
521
+ "text-size-adjust", "text-space-collapse", "text-transform", "text-underline-position",
522
+ "text-wrap", "top", "transform", "transform-origin", "transform-style",
523
+ "transition", "transition-delay", "transition-duration",
524
+ "transition-property", "transition-timing-function", "unicode-bidi",
525
+ "vertical-align", "visibility", "voice-balance", "voice-duration",
526
+ "voice-family", "voice-pitch", "voice-range", "voice-rate", "voice-stress",
527
+ "voice-volume", "volume", "white-space", "widows", "width", "word-break",
528
+ "word-spacing", "word-wrap", "z-index",
529
+ // SVG-specific
530
+ "clip-path", "clip-rule", "mask", "enable-background", "filter", "flood-color",
531
+ "flood-opacity", "lighting-color", "stop-color", "stop-opacity", "pointer-events",
532
+ "color-interpolation", "color-interpolation-filters",
533
+ "color-rendering", "fill", "fill-opacity", "fill-rule", "image-rendering",
534
+ "marker", "marker-end", "marker-mid", "marker-start", "shape-rendering", "stroke",
535
+ "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin",
536
+ "stroke-miterlimit", "stroke-opacity", "stroke-width", "text-rendering",
537
+ "baseline-shift", "dominant-baseline", "glyph-orientation-horizontal",
538
+ "glyph-orientation-vertical", "text-anchor", "writing-mode"
539
+ ], propertyKeywords = keySet(propertyKeywords_);
540
+
541
+ var nonStandardPropertyKeywords_ = [
542
+ "scrollbar-arrow-color", "scrollbar-base-color", "scrollbar-dark-shadow-color",
543
+ "scrollbar-face-color", "scrollbar-highlight-color", "scrollbar-shadow-color",
544
+ "scrollbar-3d-light-color", "scrollbar-track-color", "shape-inside",
545
+ "searchfield-cancel-button", "searchfield-decoration", "searchfield-results-button",
546
+ "searchfield-results-decoration", "zoom"
547
+ ], nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_);
548
+
549
+ var fontProperties_ = [
550
+ "font-family", "src", "unicode-range", "font-variant", "font-feature-settings",
551
+ "font-stretch", "font-weight", "font-style"
552
+ ], fontProperties = keySet(fontProperties_);
553
+
554
+ var counterDescriptors_ = [
555
+ "additive-symbols", "fallback", "negative", "pad", "prefix", "range",
556
+ "speak-as", "suffix", "symbols", "system"
557
+ ], counterDescriptors = keySet(counterDescriptors_);
558
+
559
+ var colorKeywords_ = [
560
+ "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige",
561
+ "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown",
562
+ "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue",
563
+ "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod",
564
+ "darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen",
565
+ "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen",
566
+ "darkslateblue", "darkslategray", "darkturquoise", "darkviolet",
567
+ "deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick",
568
+ "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite",
569
+ "gold", "goldenrod", "gray", "grey", "green", "greenyellow", "honeydew",
570
+ "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender",
571
+ "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral",
572
+ "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightpink",
573
+ "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray",
574
+ "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta",
575
+ "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple",
576
+ "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise",
577
+ "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin",
578
+ "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered",
579
+ "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred",
580
+ "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue",
581
+ "purple", "rebeccapurple", "red", "rosybrown", "royalblue", "saddlebrown",
582
+ "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue",
583
+ "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan",
584
+ "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white",
585
+ "whitesmoke", "yellow", "yellowgreen"
586
+ ], colorKeywords = keySet(colorKeywords_);
587
+
588
+ var valueKeywords_ = [
589
+ "above", "absolute", "activeborder", "additive", "activecaption", "afar",
590
+ "after-white-space", "ahead", "alias", "all", "all-scroll", "alphabetic", "alternate",
591
+ "always", "amharic", "amharic-abegede", "antialiased", "appworkspace",
592
+ "arabic-indic", "armenian", "asterisks", "attr", "auto", "avoid", "avoid-column", "avoid-page",
593
+ "avoid-region", "background", "backwards", "baseline", "below", "bidi-override", "binary",
594
+ "bengali", "blink", "block", "block-axis", "bold", "bolder", "border", "border-box",
595
+ "both", "bottom", "break", "break-all", "break-word", "bullets", "button", "button-bevel",
596
+ "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "calc", "cambodian",
597
+ "capitalize", "caps-lock-indicator", "caption", "captiontext", "caret",
598
+ "cell", "center", "checkbox", "circle", "cjk-decimal", "cjk-earthly-branch",
599
+ "cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote",
600
+ "col-resize", "collapse", "color", "color-burn", "color-dodge", "column", "column-reverse",
601
+ "compact", "condensed", "contain", "content",
602
+ "content-box", "context-menu", "continuous", "copy", "counter", "counters", "cover", "crop",
603
+ "cross", "crosshair", "currentcolor", "cursive", "cyclic", "darken", "dashed", "decimal",
604
+ "decimal-leading-zero", "default", "default-button", "dense", "destination-atop",
605
+ "destination-in", "destination-out", "destination-over", "devanagari", "difference",
606
+ "disc", "discard", "disclosure-closed", "disclosure-open", "document",
607
+ "dot-dash", "dot-dot-dash",
608
+ "dotted", "double", "down", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out",
609
+ "element", "ellipse", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede",
610
+ "ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er",
611
+ "ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er",
612
+ "ethiopic-halehame-aa-et", "ethiopic-halehame-am-et",
613
+ "ethiopic-halehame-gez", "ethiopic-halehame-om-et",
614
+ "ethiopic-halehame-sid-et", "ethiopic-halehame-so-et",
615
+ "ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et", "ethiopic-halehame-tig",
616
+ "ethiopic-numeric", "ew-resize", "exclusion", "expanded", "extends", "extra-condensed",
617
+ "extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "flex", "flex-end", "flex-start", "footnotes",
618
+ "forwards", "from", "geometricPrecision", "georgian", "graytext", "grid", "groove",
619
+ "gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hard-light", "hebrew",
620
+ "help", "hidden", "hide", "higher", "highlight", "highlighttext",
621
+ "hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "hue", "icon", "ignore",
622
+ "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite",
623
+ "infobackground", "infotext", "inherit", "initial", "inline", "inline-axis",
624
+ "inline-block", "inline-flex", "inline-grid", "inline-table", "inset", "inside", "intrinsic", "invert",
625
+ "italic", "japanese-formal", "japanese-informal", "justify", "kannada",
626
+ "katakana", "katakana-iroha", "keep-all", "khmer",
627
+ "korean-hangul-formal", "korean-hanja-formal", "korean-hanja-informal",
628
+ "landscape", "lao", "large", "larger", "left", "level", "lighter", "lighten",
629
+ "line-through", "linear", "linear-gradient", "lines", "list-item", "listbox", "listitem",
630
+ "local", "logical", "loud", "lower", "lower-alpha", "lower-armenian",
631
+ "lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian",
632
+ "lower-roman", "lowercase", "ltr", "luminosity", "malayalam", "match", "matrix", "matrix3d",
633
+ "media-controls-background", "media-current-time-display",
634
+ "media-fullscreen-button", "media-mute-button", "media-play-button",
635
+ "media-return-to-realtime-button", "media-rewind-button",
636
+ "media-seek-back-button", "media-seek-forward-button", "media-slider",
637
+ "media-sliderthumb", "media-time-remaining-display", "media-volume-slider",
638
+ "media-volume-slider-container", "media-volume-sliderthumb", "medium",
639
+ "menu", "menulist", "menulist-button", "menulist-text",
640
+ "menulist-textfield", "menutext", "message-box", "middle", "min-intrinsic",
641
+ "mix", "mongolian", "monospace", "move", "multiple", "multiply", "myanmar", "n-resize",
642
+ "narrower", "ne-resize", "nesw-resize", "no-close-quote", "no-drop",
643
+ "no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap",
644
+ "ns-resize", "numbers", "numeric", "nw-resize", "nwse-resize", "oblique", "octal", "open-quote",
645
+ "optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset",
646
+ "outside", "outside-shape", "overlay", "overline", "padding", "padding-box",
647
+ "painted", "page", "paused", "persian", "perspective", "plus-darker", "plus-lighter",
648
+ "pointer", "polygon", "portrait", "pre", "pre-line", "pre-wrap", "preserve-3d",
649
+ "progress", "push-button", "radial-gradient", "radio", "read-only",
650
+ "read-write", "read-write-plaintext-only", "rectangle", "region",
651
+ "relative", "repeat", "repeating-linear-gradient",
652
+ "repeating-radial-gradient", "repeat-x", "repeat-y", "reset", "reverse",
653
+ "rgb", "rgba", "ridge", "right", "rotate", "rotate3d", "rotateX", "rotateY",
654
+ "rotateZ", "round", "row", "row-resize", "row-reverse", "rtl", "run-in", "running",
655
+ "s-resize", "sans-serif", "saturation", "scale", "scale3d", "scaleX", "scaleY", "scaleZ", "screen",
656
+ "scroll", "scrollbar", "se-resize", "searchfield",
657
+ "searchfield-cancel-button", "searchfield-decoration",
658
+ "searchfield-results-button", "searchfield-results-decoration",
659
+ "semi-condensed", "semi-expanded", "separate", "serif", "show", "sidama",
660
+ "simp-chinese-formal", "simp-chinese-informal", "single",
661
+ "skew", "skewX", "skewY", "skip-white-space", "slide", "slider-horizontal",
662
+ "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow",
663
+ "small", "small-caps", "small-caption", "smaller", "soft-light", "solid", "somali",
664
+ "source-atop", "source-in", "source-out", "source-over", "space", "space-around", "space-between", "spell-out", "square",
665
+ "square-button", "start", "static", "status-bar", "stretch", "stroke", "sub",
666
+ "subpixel-antialiased", "super", "sw-resize", "symbolic", "symbols", "table",
667
+ "table-caption", "table-cell", "table-column", "table-column-group",
668
+ "table-footer-group", "table-header-group", "table-row", "table-row-group",
669
+ "tamil",
670
+ "telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai",
671
+ "thick", "thin", "threeddarkshadow", "threedface", "threedhighlight",
672
+ "threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er",
673
+ "tigrinya-er-abegede", "tigrinya-et", "tigrinya-et-abegede", "to", "top",
674
+ "trad-chinese-formal", "trad-chinese-informal",
675
+ "translate", "translate3d", "translateX", "translateY", "translateZ",
676
+ "transparent", "ultra-condensed", "ultra-expanded", "underline", "up",
677
+ "upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal",
678
+ "upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url",
679
+ "var", "vertical", "vertical-text", "visible", "visibleFill", "visiblePainted",
680
+ "visibleStroke", "visual", "w-resize", "wait", "wave", "wider",
681
+ "window", "windowframe", "windowtext", "words", "wrap", "wrap-reverse", "x-large", "x-small", "xor",
682
+ "xx-large", "xx-small"
683
+ ], valueKeywords = keySet(valueKeywords_);
684
+
685
+ var allWords = documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(mediaValueKeywords_)
686
+ .concat(propertyKeywords_).concat(nonStandardPropertyKeywords_).concat(colorKeywords_)
687
+ .concat(valueKeywords_);
688
+ CodeMirror.registerHelper("hintWords", "css", allWords);
689
+
690
+ function tokenCComment(stream, state) {
691
+ var maybeEnd = false, ch;
692
+ while ((ch = stream.next()) != null) {
693
+ if (maybeEnd && ch == "/") {
694
+ state.tokenize = null;
695
+ break;
696
+ }
697
+ maybeEnd = (ch == "*");
698
+ }
699
+ return ["comment", "comment"];
700
+ }
701
+
702
+ CodeMirror.defineMIME("text/css", {
703
+ documentTypes: documentTypes,
704
+ mediaTypes: mediaTypes,
705
+ mediaFeatures: mediaFeatures,
706
+ mediaValueKeywords: mediaValueKeywords,
707
+ propertyKeywords: propertyKeywords,
708
+ nonStandardPropertyKeywords: nonStandardPropertyKeywords,
709
+ fontProperties: fontProperties,
710
+ counterDescriptors: counterDescriptors,
711
+ colorKeywords: colorKeywords,
712
+ valueKeywords: valueKeywords,
713
+ tokenHooks: {
714
+ "/": function(stream, state) {
715
+ if (!stream.eat("*")) return false;
716
+ state.tokenize = tokenCComment;
717
+ return tokenCComment(stream, state);
718
+ }
719
+ },
720
+ name: "css"
721
+ });
722
+
723
+ CodeMirror.defineMIME("text/x-scss", {
724
+ mediaTypes: mediaTypes,
725
+ mediaFeatures: mediaFeatures,
726
+ mediaValueKeywords: mediaValueKeywords,
727
+ propertyKeywords: propertyKeywords,
728
+ nonStandardPropertyKeywords: nonStandardPropertyKeywords,
729
+ colorKeywords: colorKeywords,
730
+ valueKeywords: valueKeywords,
731
+ fontProperties: fontProperties,
732
+ allowNested: true,
733
+ tokenHooks: {
734
+ "/": function(stream, state) {
735
+ if (stream.eat("/")) {
736
+ stream.skipToEnd();
737
+ return ["comment", "comment"];
738
+ } else if (stream.eat("*")) {
739
+ state.tokenize = tokenCComment;
740
+ return tokenCComment(stream, state);
741
+ } else {
742
+ return ["operator", "operator"];
743
+ }
744
+ },
745
+ ":": function(stream) {
746
+ if (stream.match(/\s*\{/))
747
+ return [null, "{"];
748
+ return false;
749
+ },
750
+ "$": function(stream) {
751
+ stream.match(/^[\w-]+/);
752
+ if (stream.match(/^\s*:/, false))
753
+ return ["variable-2", "variable-definition"];
754
+ return ["variable-2", "variable"];
755
+ },
756
+ "#": function(stream) {
757
+ if (!stream.eat("{")) return false;
758
+ return [null, "interpolation"];
759
+ }
760
+ },
761
+ name: "css",
762
+ helperType: "scss"
763
+ });
764
+
765
+ CodeMirror.defineMIME("text/x-less", {
766
+ mediaTypes: mediaTypes,
767
+ mediaFeatures: mediaFeatures,
768
+ mediaValueKeywords: mediaValueKeywords,
769
+ propertyKeywords: propertyKeywords,
770
+ nonStandardPropertyKeywords: nonStandardPropertyKeywords,
771
+ colorKeywords: colorKeywords,
772
+ valueKeywords: valueKeywords,
773
+ fontProperties: fontProperties,
774
+ allowNested: true,
775
+ tokenHooks: {
776
+ "/": function(stream, state) {
777
+ if (stream.eat("/")) {
778
+ stream.skipToEnd();
779
+ return ["comment", "comment"];
780
+ } else if (stream.eat("*")) {
781
+ state.tokenize = tokenCComment;
782
+ return tokenCComment(stream, state);
783
+ } else {
784
+ return ["operator", "operator"];
785
+ }
786
+ },
787
+ "@": function(stream) {
788
+ if (stream.eat("{")) return [null, "interpolation"];
789
+ if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/, false)) return false;
790
+ stream.eatWhile(/[\w\\\-]/);
791
+ if (stream.match(/^\s*:/, false))
792
+ return ["variable-2", "variable-definition"];
793
+ return ["variable-2", "variable"];
794
+ },
795
+ "&": function() {
796
+ return ["atom", "atom"];
797
+ }
798
+ },
799
+ name: "css",
800
+ helperType: "less"
801
+ });
802
+
803
+ CodeMirror.defineMIME("text/x-gss", {
804
+ documentTypes: documentTypes,
805
+ mediaTypes: mediaTypes,
806
+ mediaFeatures: mediaFeatures,
807
+ propertyKeywords: propertyKeywords,
808
+ nonStandardPropertyKeywords: nonStandardPropertyKeywords,
809
+ fontProperties: fontProperties,
810
+ counterDescriptors: counterDescriptors,
811
+ colorKeywords: colorKeywords,
812
+ valueKeywords: valueKeywords,
813
+ supportsAtComponent: true,
814
+ tokenHooks: {
815
+ "/": function(stream, state) {
816
+ if (!stream.eat("*")) return false;
817
+ state.tokenize = tokenCComment;
818
+ return tokenCComment(stream, state);
819
+ }
820
+ },
821
+ name: "css",
822
+ helperType: "gss"
823
+ });
824
+
825
+ });
inc/lib/codemirror/mode/htmlmixed.js ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // CodeMirror, copyright (c) by Marijn Haverbeke and others
2
+ // Distributed under an MIT license: http://codemirror.net/LICENSE
3
+
4
+ (function(mod) {
5
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
6
+ mod(require("../../lib/codemirror"), require("../xml/xml"), require("../javascript/javascript"), require("../css/css"));
7
+ else if (typeof define == "function" && define.amd) // AMD
8
+ define(["../../lib/codemirror", "../xml/xml", "../javascript/javascript", "../css/css"], mod);
9
+ else // Plain browser env
10
+ mod(CodeMirror);
11
+ })(function(CodeMirror) {
12
+ "use strict";
13
+
14
+ var defaultTags = {
15
+ script: [
16
+ ["lang", /(javascript|babel)/i, "javascript"],
17
+ ["type", /^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^$/i, "javascript"],
18
+ ["type", /./, "text/plain"],
19
+ [null, null, "javascript"]
20
+ ],
21
+ style: [
22
+ ["lang", /^css$/i, "css"],
23
+ ["type", /^(text\/)?(x-)?(stylesheet|css)$/i, "css"],
24
+ ["type", /./, "text/plain"],
25
+ [null, null, "css"]
26
+ ]
27
+ };
28
+
29
+ function maybeBackup(stream, pat, style) {
30
+ var cur = stream.current(), close = cur.search(pat);
31
+ if (close > -1) {
32
+ stream.backUp(cur.length - close);
33
+ } else if (cur.match(/<\/?$/)) {
34
+ stream.backUp(cur.length);
35
+ if (!stream.match(pat, false)) stream.match(cur);
36
+ }
37
+ return style;
38
+ }
39
+
40
+ var attrRegexpCache = {};
41
+ function getAttrRegexp(attr) {
42
+ var regexp = attrRegexpCache[attr];
43
+ if (regexp) return regexp;
44
+ return attrRegexpCache[attr] = new RegExp("\\s+" + attr + "\\s*=\\s*('|\")?([^'\"]+)('|\")?\\s*");
45
+ }
46
+
47
+ function getAttrValue(text, attr) {
48
+ var match = text.match(getAttrRegexp(attr))
49
+ return match ? match[2] : ""
50
+ }
51
+
52
+ function getTagRegexp(tagName, anchored) {
53
+ return new RegExp((anchored ? "^" : "") + "<\/\s*" + tagName + "\s*>", "i");
54
+ }
55
+
56
+ function addTags(from, to) {
57
+ for (var tag in from) {
58
+ var dest = to[tag] || (to[tag] = []);
59
+ var source = from[tag];
60
+ for (var i = source.length - 1; i >= 0; i--)
61
+ dest.unshift(source[i])
62
+ }
63
+ }
64
+
65
+ function findMatchingMode(tagInfo, tagText) {
66
+ for (var i = 0; i < tagInfo.length; i++) {
67
+ var spec = tagInfo[i];
68
+ if (!spec[0] || spec[1].test(getAttrValue(tagText, spec[0]))) return spec[2];
69
+ }
70
+ }
71
+
72
+ CodeMirror.defineMode("htmlmixed", function (config, parserConfig) {
73
+ var htmlMode = CodeMirror.getMode(config, {
74
+ name: "xml",
75
+ htmlMode: true,
76
+ multilineTagIndentFactor: parserConfig.multilineTagIndentFactor,
77
+ multilineTagIndentPastTag: parserConfig.multilineTagIndentPastTag
78
+ });
79
+
80
+ var tags = {};
81
+ var configTags = parserConfig && parserConfig.tags, configScript = parserConfig && parserConfig.scriptTypes;
82
+ addTags(defaultTags, tags);
83
+ if (configTags) addTags(configTags, tags);
84
+ if (configScript) for (var i = configScript.length - 1; i >= 0; i--)
85
+ tags.script.unshift(["type", configScript[i].matches, configScript[i].mode])
86
+
87
+ function html(stream, state) {
88
+ var style = htmlMode.token(stream, state.htmlState), tag = /\btag\b/.test(style), tagName
89
+ if (tag && !/[<>\s\/]/.test(stream.current()) &&
90
+ (tagName = state.htmlState.tagName && state.htmlState.tagName.toLowerCase()) &&
91
+ tags.hasOwnProperty(tagName)) {
92
+ state.inTag = tagName + " "
93
+ } else if (state.inTag && tag && />$/.test(stream.current())) {
94
+ var inTag = /^([\S]+) (.*)/.exec(state.inTag)
95
+ state.inTag = null
96
+ var modeSpec = stream.current() == ">" && findMatchingMode(tags[inTag[1]], inTag[2])
97
+ var mode = CodeMirror.getMode(config, modeSpec)
98
+ var endTagA = getTagRegexp(inTag[1], true), endTag = getTagRegexp(inTag[1], false);
99
+ state.token = function (stream, state) {
100
+ if (stream.match(endTagA, false)) {
101
+ state.token = html;
102
+ state.localState = state.localMode = null;
103
+ return null;
104
+ }
105
+ return maybeBackup(stream, endTag, state.localMode.token(stream, state.localState));
106
+ };
107
+ state.localMode = mode;
108
+ state.localState = CodeMirror.startState(mode, htmlMode.indent(state.htmlState, ""));
109
+ } else if (state.inTag) {
110
+ state.inTag += stream.current()
111
+ if (stream.eol()) state.inTag += " "
112
+ }
113
+ return style;
114
+ };
115
+
116
+ return {
117
+ startState: function () {
118
+ var state = CodeMirror.startState(htmlMode);
119
+ return {token: html, inTag: null, localMode: null, localState: null, htmlState: state};
120
+ },
121
+
122
+ copyState: function (state) {
123
+ var local;
124
+ if (state.localState) {
125
+ local = CodeMirror.copyState(state.localMode, state.localState);
126
+ }
127
+ return {token: state.token, inTag: state.inTag,
128
+ localMode: state.localMode, localState: local,
129
+ htmlState: CodeMirror.copyState(htmlMode, state.htmlState)};
130
+ },
131
+
132
+ token: function (stream, state) {
133
+ return state.token(stream, state);
134
+ },
135
+
136
+ indent: function (state, textAfter) {
137
+ if (!state.localMode || /^\s*<\//.test(textAfter))
138
+ return htmlMode.indent(state.htmlState, textAfter);
139
+ else if (state.localMode.indent)
140
+ return state.localMode.indent(state.localState, textAfter);
141
+ else
142
+ return CodeMirror.Pass;
143
+ },
144
+
145
+ innerMode: function (state) {
146
+ return {state: state.localState || state.htmlState, mode: state.localMode || htmlMode};
147
+ }
148
+ };
149
+ }, "xml", "javascript", "css");
150
+
151
+ CodeMirror.defineMIME("text/html", "htmlmixed");
152
+ });
inc/lib/codemirror/mode/javascript.js ADDED
@@ -0,0 +1,743 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // CodeMirror, copyright (c) by Marijn Haverbeke and others
2
+ // Distributed under an MIT license: http://codemirror.net/LICENSE
3
+
4
+ // TODO actually recognize syntax of TypeScript constructs
5
+
6
+ (function(mod) {
7
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
8
+ mod(require("../../lib/codemirror"));
9
+ else if (typeof define == "function" && define.amd) // AMD
10
+ define(["../../lib/codemirror"], mod);
11
+ else // Plain browser env
12
+ mod(CodeMirror);
13
+ })(function(CodeMirror) {
14
+ "use strict";
15
+
16
+ function expressionAllowed(stream, state, backUp) {
17
+ return /^(?:operator|sof|keyword c|case|new|[\[{}\(,;:]|=>)$/.test(state.lastType) ||
18
+ (state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0))))
19
+ }
20
+
21
+ CodeMirror.defineMode("javascript", function(config, parserConfig) {
22
+ var indentUnit = config.indentUnit;
23
+ var statementIndent = parserConfig.statementIndent;
24
+ var jsonldMode = parserConfig.jsonld;
25
+ var jsonMode = parserConfig.json || jsonldMode;
26
+ var isTS = parserConfig.typescript;
27
+ var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/;
28
+
29
+ // Tokenizer
30
+
31
+ var keywords = function(){
32
+ function kw(type) {return {type: type, style: "keyword"};}
33
+ var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c");
34
+ var operator = kw("operator"), atom = {type: "atom", style: "atom"};
35
+
36
+ var jsKeywords = {
37
+ "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B,
38
+ "return": C, "break": C, "continue": C, "new": kw("new"), "delete": C, "throw": C, "debugger": C,
39
+ "var": kw("var"), "const": kw("var"), "let": kw("var"),
40
+ "function": kw("function"), "catch": kw("catch"),
41
+ "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
42
+ "in": operator, "typeof": operator, "instanceof": operator,
43
+ "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom,
44
+ "this": kw("this"), "class": kw("class"), "super": kw("atom"),
45
+ "yield": C, "export": kw("export"), "import": kw("import"), "extends": C,
46
+ "await": C, "async": kw("async")
47
+ };
48
+
49
+ // Extend the 'normal' keywords with the TypeScript language extensions
50
+ if (isTS) {
51
+ var type = {type: "variable", style: "variable-3"};
52
+ var tsKeywords = {
53
+ // object-like things
54
+ "interface": kw("class"),
55
+ "implements": C,
56
+ "namespace": C,
57
+ "module": kw("module"),
58
+ "enum": kw("module"),
59
+
60
+ // scope modifiers
61
+ "public": kw("modifier"),
62
+ "private": kw("modifier"),
63
+ "protected": kw("modifier"),
64
+ "abstract": kw("modifier"),
65
+
66
+ // operators
67
+ "as": operator,
68
+
69
+ // types
70
+ "string": type, "number": type, "boolean": type, "any": type
71
+ };
72
+
73
+ for (var attr in tsKeywords) {
74
+ jsKeywords[attr] = tsKeywords[attr];
75
+ }
76
+ }
77
+
78
+ return jsKeywords;
79
+ }();
80
+
81
+ var isOperatorChar = /[+\-*&%=<>!?|~^]/;
82
+ var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;
83
+
84
+ function readRegexp(stream) {
85
+ var escaped = false, next, inSet = false;
86
+ while ((next = stream.next()) != null) {
87
+ if (!escaped) {
88
+ if (next == "/" && !inSet) return;
89
+ if (next == "[") inSet = true;
90
+ else if (inSet && next == "]") inSet = false;
91
+ }
92
+ escaped = !escaped && next == "\\";
93
+ }
94
+ }
95
+
96
+ // Used as scratch variables to communicate multiple values without
97
+ // consing up tons of objects.
98
+ var type, content;
99
+ function ret(tp, style, cont) {
100
+ type = tp; content = cont;
101
+ return style;
102
+ }
103
+ function tokenBase(stream, state) {
104
+ var ch = stream.next();
105
+ if (ch == '"' || ch == "'") {
106
+ state.tokenize = tokenString(ch);
107
+ return state.tokenize(stream, state);
108
+ } else if (ch == "." && stream.match(/^\d+(?:[eE][+\-]?\d+)?/)) {
109
+ return ret("number", "number");
110
+ } else if (ch == "." && stream.match("..")) {
111
+ return ret("spread", "meta");
112
+ } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
113
+ return ret(ch);
114
+ } else if (ch == "=" && stream.eat(">")) {
115
+ return ret("=>", "operator");
116
+ } else if (ch == "0" && stream.eat(/x/i)) {
117
+ stream.eatWhile(/[\da-f]/i);
118
+ return ret("number", "number");
119
+ } else if (ch == "0" && stream.eat(/o/i)) {
120
+ stream.eatWhile(/[0-7]/i);
121
+ return ret("number", "number");
122
+ } else if (ch == "0" && stream.eat(/b/i)) {
123
+ stream.eatWhile(/[01]/i);
124
+ return ret("number", "number");
125
+ } else if (/\d/.test(ch)) {
126
+ stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/);
127
+ return ret("number", "number");
128
+ } else if (ch == "/") {
129
+ if (stream.eat("*")) {
130
+ state.tokenize = tokenComment;
131
+ return tokenComment(stream, state);
132
+ } else if (stream.eat("/")) {
133
+ stream.skipToEnd();
134
+ return ret("comment", "comment");
135
+ } else if (expressionAllowed(stream, state, 1)) {
136
+ readRegexp(stream);
137
+ stream.match(/^\b(([gimyu])(?![gimyu]*\2))+\b/);
138
+ return ret("regexp", "string-2");
139
+ } else {
140
+ stream.eatWhile(isOperatorChar);
141
+ return ret("operator", "operator", stream.current());
142
+ }
143
+ } else if (ch == "`") {
144
+ state.tokenize = tokenQuasi;
145
+ return tokenQuasi(stream, state);
146
+ } else if (ch == "#") {
147
+ stream.skipToEnd();
148
+ return ret("error", "error");
149
+ } else if (isOperatorChar.test(ch)) {
150
+ stream.eatWhile(isOperatorChar);
151
+ return ret("operator", "operator", stream.current());
152
+ } else if (wordRE.test(ch)) {
153
+ stream.eatWhile(wordRE);
154
+ var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word];
155
+ return (known && state.lastType != ".") ? ret(known.type, known.style, word) :
156
+ ret("variable", "variable", word);
157
+ }
158
+ }
159
+
160
+ function tokenString(quote) {
161
+ return function(stream, state) {
162
+ var escaped = false, next;
163
+ if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){
164
+ state.tokenize = tokenBase;
165
+ return ret("jsonld-keyword", "meta");
166
+ }
167
+ while ((next = stream.next()) != null) {
168
+ if (next == quote && !escaped) break;
169
+ escaped = !escaped && next == "\\";
170
+ }
171
+ if (!escaped) state.tokenize = tokenBase;
172
+ return ret("string", "string");
173
+ };
174
+ }
175
+
176
+ function tokenComment(stream, state) {
177
+ var maybeEnd = false, ch;
178
+ while (ch = stream.next()) {
179
+ if (ch == "/" && maybeEnd) {
180
+ state.tokenize = tokenBase;
181
+ break;
182
+ }
183
+ maybeEnd = (ch == "*");
184
+ }
185
+ return ret("comment", "comment");
186
+ }
187
+
188
+ function tokenQuasi(stream, state) {
189
+ var escaped = false, next;
190
+ while ((next = stream.next()) != null) {
191
+ if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) {
192
+ state.tokenize = tokenBase;
193
+ break;
194
+ }
195
+ escaped = !escaped && next == "\\";
196
+ }
197
+ return ret("quasi", "string-2", stream.current());
198
+ }
199
+
200
+ var brackets = "([{}])";
201
+ // This is a crude lookahead trick to try and notice that we're
202
+ // parsing the argument patterns for a fat-arrow function before we
203
+ // actually hit the arrow token. It only works if the arrow is on
204
+ // the same line as the arguments and there's no strange noise
205
+ // (comments) in between. Fallback is to only notice when we hit the
206
+ // arrow, and not declare the arguments as locals for the arrow
207
+ // body.
208
+ function findFatArrow(stream, state) {
209
+ if (state.fatArrowAt) state.fatArrowAt = null;
210
+ var arrow = stream.string.indexOf("=>", stream.start);
211
+ if (arrow < 0) return;
212
+
213
+ var depth = 0, sawSomething = false;
214
+ for (var pos = arrow - 1; pos >= 0; --pos) {
215
+ var ch = stream.string.charAt(pos);
216
+ var bracket = brackets.indexOf(ch);
217
+ if (bracket >= 0 && bracket < 3) {
218
+ if (!depth) { ++pos; break; }
219
+ if (--depth == 0) break;
220
+ } else if (bracket >= 3 && bracket < 6) {
221
+ ++depth;
222
+ } else if (wordRE.test(ch)) {
223
+ sawSomething = true;
224
+ } else if (/["'\/]/.test(ch)) {
225
+ return;
226
+ } else if (sawSomething && !depth) {
227
+ ++pos;
228
+ break;
229
+ }
230
+ }
231
+ if (sawSomething && !depth) state.fatArrowAt = pos;
232
+ }
233
+
234
+ // Parser
235
+
236
+ var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true};
237
+
238
+ function JSLexical(indented, column, type, align, prev, info) {
239
+ this.indented = indented;
240
+ this.column = column;
241
+ this.type = type;
242
+ this.prev = prev;
243
+ this.info = info;
244
+ if (align != null) this.align = align;
245
+ }
246
+
247
+ function inScope(state, varname) {
248
+ for (var v = state.localVars; v; v = v.next)
249
+ if (v.name == varname) return true;
250
+ for (var cx = state.context; cx; cx = cx.prev) {
251
+ for (var v = cx.vars; v; v = v.next)
252
+ if (v.name == varname) return true;
253
+ }
254
+ }
255
+
256
+ function parseJS(state, style, type, content, stream) {
257
+ var cc = state.cc;
258
+ // Communicate our context to the combinators.
259
+ // (Less wasteful than consing up a hundred closures on every call.)
260
+ cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style;
261
+
262
+ if (!state.lexical.hasOwnProperty("align"))
263
+ state.lexical.align = true;
264
+
265
+ while(true) {
266
+ var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
267
+ if (combinator(type, content)) {
268
+ while(cc.length && cc[cc.length - 1].lex)
269
+ cc.pop()();
270
+ if (cx.marked) return cx.marked;
271
+ if (type == "variable" && inScope(state, content)) return "variable-2";
272
+ return style;
273
+ }
274
+ }
275
+ }
276
+
277
+ // Combinator utils
278
+
279
+ var cx = {state: null, column: null, marked: null, cc: null};
280
+ function pass() {
281
+ for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
282
+ }
283
+ function cont() {
284
+ pass.apply(null, arguments);
285
+ return true;
286
+ }
287
+ function register(varname) {
288
+ function inList(list) {
289
+ for (var v = list; v; v = v.next)
290
+ if (v.name == varname) return true;
291
+ return false;
292
+ }
293
+ var state = cx.state;
294
+ cx.marked = "def";
295
+ if (state.context) {
296
+ if (inList(state.localVars)) return;
297
+ state.localVars = {name: varname, next: state.localVars};
298
+ } else {
299
+ if (inList(state.globalVars)) return;
300
+ if (parserConfig.globalVars)
301
+ state.globalVars = {name: varname, next: state.globalVars};
302
+ }
303
+ }
304
+
305
+ // Combinators
306
+
307
+ var defaultVars = {name: "this", next: {name: "arguments"}};
308
+ function pushcontext() {
309
+ cx.state.context = {prev: cx.state.context, vars: cx.state.localVars};
310
+ cx.state.localVars = defaultVars;
311
+ }
312
+ function popcontext() {
313
+ cx.state.localVars = cx.state.context.vars;
314
+ cx.state.context = cx.state.context.prev;
315
+ }
316
+ function pushlex(type, info) {
317
+ var result = function() {
318
+ var state = cx.state, indent = state.indented;
319
+ if (state.lexical.type == "stat") indent = state.lexical.indented;
320
+ else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev)
321
+ indent = outer.indented;
322
+ state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);
323
+ };
324
+ result.lex = true;
325
+ return result;
326
+ }
327
+ function poplex() {
328
+ var state = cx.state;
329
+ if (state.lexical.prev) {
330
+ if (state.lexical.type == ")")
331
+ state.indented = state.lexical.indented;
332
+ state.lexical = state.lexical.prev;
333
+ }
334
+ }
335
+ poplex.lex = true;
336
+
337
+ function expect(wanted) {
338
+ function exp(type) {
339
+ if (type == wanted) return cont();
340
+ else if (wanted == ";") return pass();
341
+ else return cont(exp);
342
+ };
343
+ return exp;
344
+ }
345
+
346
+ function statement(type, value) {
347
+ if (type == "var") return cont(pushlex("vardef", value.length), vardef, expect(";"), poplex);
348
+ if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex);
349
+ if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
350
+ if (type == "{") return cont(pushlex("}"), block, poplex);
351
+ if (type == ";") return cont();
352
+ if (type == "if") {
353
+ if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex)
354
+ cx.state.cc.pop()();
355
+ return cont(pushlex("form"), expression, statement, poplex, maybeelse);
356
+ }
357
+ if (type == "function") return cont(functiondef);
358
+ if (type == "for") return cont(pushlex("form"), forspec, statement, poplex);
359
+ if (type == "variable") return cont(pushlex("stat"), maybelabel);
360
+ if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"),
361
+ block, poplex, poplex);
362
+ if (type == "case") return cont(expression, expect(":"));
363
+ if (type == "default") return cont(expect(":"));
364
+ if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"),
365
+ statement, poplex, popcontext);
366
+ if (type == "class") return cont(pushlex("form"), className, poplex);
367
+ if (type == "export") return cont(pushlex("stat"), afterExport, poplex);
368
+ if (type == "import") return cont(pushlex("stat"), afterImport, poplex);
369
+ if (type == "module") return cont(pushlex("form"), pattern, pushlex("}"), expect("{"), block, poplex, poplex)
370
+ if (type == "async") return cont(statement)
371
+ return pass(pushlex("stat"), expression, expect(";"), poplex);
372
+ }
373
+ function expression(type) {
374
+ return expressionInner(type, false);
375
+ }
376
+ function expressionNoComma(type) {
377
+ return expressionInner(type, true);
378
+ }
379
+ function expressionInner(type, noComma) {
380
+ if (cx.state.fatArrowAt == cx.stream.start) {
381
+ var body = noComma ? arrowBodyNoComma : arrowBody;
382
+ if (type == "(") return cont(pushcontext, pushlex(")"), commasep(pattern, ")"), poplex, expect("=>"), body, popcontext);
383
+ else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext);
384
+ }
385
+
386
+ var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;
387
+ if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);
388
+ if (type == "function") return cont(functiondef, maybeop);
389
+ if (type == "keyword c" || type == "async") return cont(noComma ? maybeexpressionNoComma : maybeexpression);
390
+ if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop);
391
+ if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression);
392
+ if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop);
393
+ if (type == "{") return contCommasep(objprop, "}", null, maybeop);
394
+ if (type == "quasi") return pass(quasi, maybeop);
395
+ if (type == "new") return cont(maybeTarget(noComma));
396
+ return cont();
397
+ }
398
+ function maybeexpression(type) {
399
+ if (type.match(/[;\}\)\],]/)) return pass();
400
+ return pass(expression);
401
+ }
402
+ function maybeexpressionNoComma(type) {
403
+ if (type.match(/[;\}\)\],]/)) return pass();
404
+ return pass(expressionNoComma);
405
+ }
406
+
407
+ function maybeoperatorComma(type, value) {
408
+ if (type == ",") return cont(expression);
409
+ return maybeoperatorNoComma(type, value, false);
410
+ }
411
+ function maybeoperatorNoComma(type, value, noComma) {
412
+ var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;
413
+ var expr = noComma == false ? expression : expressionNoComma;
414
+ if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext);
415
+ if (type == "operator") {
416
+ if (/\+\+|--/.test(value)) return cont(me);
417
+ if (value == "?") return cont(expression, expect(":"), expr);
418
+ return cont(expr);
419
+ }
420
+ if (type == "quasi") { return pass(quasi, me); }
421
+ if (type == ";") return;
422
+ if (type == "(") return contCommasep(expressionNoComma, ")", "call", me);
423
+ if (type == ".") return cont(property, me);
424
+ if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me);
425
+ }
426
+ function quasi(type, value) {
427
+ if (type != "quasi") return pass();
428
+ if (value.slice(value.length - 2) != "${") return cont(quasi);
429
+ return cont(expression, continueQuasi);
430
+ }
431
+ function continueQuasi(type) {
432
+ if (type == "}") {
433
+ cx.marked = "string-2";
434
+ cx.state.tokenize = tokenQuasi;
435
+ return cont(quasi);
436
+ }
437
+ }
438
+ function arrowBody(type) {
439
+ findFatArrow(cx.stream, cx.state);
440
+ return pass(type == "{" ? statement : expression);
441
+ }
442
+ function arrowBodyNoComma(type) {
443
+ findFatArrow(cx.stream, cx.state);
444
+ return pass(type == "{" ? statement : expressionNoComma);
445
+ }
446
+ function maybeTarget(noComma) {
447
+ return function(type) {
448
+ if (type == ".") return cont(noComma ? targetNoComma : target);
449
+ else return pass(noComma ? expressionNoComma : expression);
450
+ };
451
+ }
452
+ function target(_, value) {
453
+ if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); }
454
+ }
455
+ function targetNoComma(_, value) {
456
+ if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); }
457
+ }
458
+ function maybelabel(type) {
459
+ if (type == ":") return cont(poplex, statement);
460
+ return pass(maybeoperatorComma, expect(";"), poplex);
461
+ }
462
+ function property(type) {
463
+ if (type == "variable") {cx.marked = "property"; return cont();}
464
+ }
465
+ function objprop(type, value) {
466
+ if (type == "async") return cont(objprop);
467
+ if (type == "variable" || cx.style == "keyword") {
468
+ cx.marked = "property";
469
+ if (value == "get" || value == "set") return cont(getterSetter);
470
+ return cont(afterprop);
471
+ } else if (type == "number" || type == "string") {
472
+ cx.marked = jsonldMode ? "property" : (cx.style + " property");
473
+ return cont(afterprop);
474
+ } else if (type == "jsonld-keyword") {
475
+ return cont(afterprop);
476
+ } else if (type == "modifier") {
477
+ return cont(objprop)
478
+ } else if (type == "[") {
479
+ return cont(expression, expect("]"), afterprop);
480
+ } else if (type == "spread") {
481
+ return cont(expression);
482
+ }
483
+ }
484
+ function getterSetter(type) {
485
+ if (type != "variable") return pass(afterprop);
486
+ cx.marked = "property";
487
+ return cont(functiondef);
488
+ }
489
+ function afterprop(type) {
490
+ if (type == ":") return cont(expressionNoComma);
491
+ if (type == "(") return pass(functiondef);
492
+ }
493
+ function commasep(what, end) {
494
+ function proceed(type, value) {
495
+ if (type == ",") {
496
+ var lex = cx.state.lexical;
497
+ if (lex.info == "call") lex.pos = (lex.pos || 0) + 1;
498
+ return cont(function(type, value) {
499
+ if (type == end || value == end) return pass()
500
+ return pass(what)
501
+ }, proceed);
502
+ }
503
+ if (type == end || value == end) return cont();
504
+ return cont(expect(end));
505
+ }
506
+ return function(type, value) {
507
+ if (type == end || value == end) return cont();
508
+ return pass(what, proceed);
509
+ };
510
+ }
511
+ function contCommasep(what, end, info) {
512
+ for (var i = 3; i < arguments.length; i++)
513
+ cx.cc.push(arguments[i]);
514
+ return cont(pushlex(end, info), commasep(what, end), poplex);
515
+ }
516
+ function block(type) {
517
+ if (type == "}") return cont();
518
+ return pass(statement, block);
519
+ }
520
+ function maybetype(type) {
521
+ if (isTS && type == ":") return cont(typeexpr);
522
+ }
523
+ function maybedefault(_, value) {
524
+ if (value == "=") return cont(expressionNoComma);
525
+ }
526
+ function typeexpr(type) {
527
+ if (type == "variable") {cx.marked = "variable-3"; return cont(afterType);}
528
+ }
529
+ function afterType(type, value) {
530
+ if (value == "<") return cont(commasep(typeexpr, ">"), afterType)
531
+ if (type == "[") return cont(expect("]"), afterType)
532
+ }
533
+ function vardef() {
534
+ return pass(pattern, maybetype, maybeAssign, vardefCont);
535
+ }
536
+ function pattern(type, value) {
537
+ if (type == "modifier") return cont(pattern)
538
+ if (type == "variable") { register(value); return cont(); }
539
+ if (type == "spread") return cont(pattern);
540
+ if (type == "[") return contCommasep(pattern, "]");
541
+ if (type == "{") return contCommasep(proppattern, "}");
542
+ }
543
+ function proppattern(type, value) {
544
+ if (type == "variable" && !cx.stream.match(/^\s*:/, false)) {
545
+ register(value);
546
+ return cont(maybeAssign);
547
+ }
548
+ if (type == "variable") cx.marked = "property";
549
+ if (type == "spread") return cont(pattern);
550
+ if (type == "}") return pass();
551
+ return cont(expect(":"), pattern, maybeAssign);
552
+ }
553
+ function maybeAssign(_type, value) {
554
+ if (value == "=") return cont(expressionNoComma);
555
+ }
556
+ function vardefCont(type) {
557
+ if (type == ",") return cont(vardef);
558
+ }
559
+ function maybeelse(type, value) {
560
+ if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex);
561
+ }
562
+ function forspec(type) {
563
+ if (type == "(") return cont(pushlex(")"), forspec1, expect(")"), poplex);
564
+ }
565
+ function forspec1(type) {
566
+ if (type == "var") return cont(vardef, expect(";"), forspec2);
567
+ if (type == ";") return cont(forspec2);
568
+ if (type == "variable") return cont(formaybeinof);
569
+ return pass(expression, expect(";"), forspec2);
570
+ }
571
+ function formaybeinof(_type, value) {
572
+ if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
573
+ return cont(maybeoperatorComma, forspec2);
574
+ }
575
+ function forspec2(type, value) {
576
+ if (type == ";") return cont(forspec3);
577
+ if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); }
578
+ return pass(expression, expect(";"), forspec3);
579
+ }
580
+ function forspec3(type) {
581
+ if (type != ")") cont(expression);
582
+ }
583
+ function functiondef(type, value) {
584
+ if (value == "*") {cx.marked = "keyword"; return cont(functiondef);}
585
+ if (type == "variable") {register(value); return cont(functiondef);}
586
+ if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, maybetype, statement, popcontext);
587
+ }
588
+ function funarg(type) {
589
+ if (type == "spread") return cont(funarg);
590
+ return pass(pattern, maybetype, maybedefault);
591
+ }
592
+ function className(type, value) {
593
+ if (type == "variable") {register(value); return cont(classNameAfter);}
594
+ }
595
+ function classNameAfter(type, value) {
596
+ if (value == "extends") return cont(expression, classNameAfter);
597
+ if (type == "{") return cont(pushlex("}"), classBody, poplex);
598
+ }
599
+ function classBody(type, value) {
600
+ if (type == "variable" || cx.style == "keyword") {
601
+ if (value == "static") {
602
+ cx.marked = "keyword";
603
+ return cont(classBody);
604
+ }
605
+ cx.marked = "property";
606
+ if (value == "get" || value == "set") return cont(classGetterSetter, functiondef, classBody);
607
+ return cont(functiondef, classBody);
608
+ }
609
+ if (value == "*") {
610
+ cx.marked = "keyword";
611
+ return cont(classBody);
612
+ }
613
+ if (type == ";") return cont(classBody);
614
+ if (type == "}") return cont();
615
+ }
616
+ function classGetterSetter(type) {
617
+ if (type != "variable") return pass();
618
+ cx.marked = "property";
619
+ return cont();
620
+ }
621
+ function afterExport(_type, value) {
622
+ if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); }
623
+ if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); }
624
+ return pass(statement);
625
+ }
626
+ function afterImport(type) {
627
+ if (type == "string") return cont();
628
+ return pass(importSpec, maybeFrom);
629
+ }
630
+ function importSpec(type, value) {
631
+ if (type == "{") return contCommasep(importSpec, "}");
632
+ if (type == "variable") register(value);
633
+ if (value == "*") cx.marked = "keyword";
634
+ return cont(maybeAs);
635
+ }
636
+ function maybeAs(_type, value) {
637
+ if (value == "as") { cx.marked = "keyword"; return cont(importSpec); }
638
+ }
639
+ function maybeFrom(_type, value) {
640
+ if (value == "from") { cx.marked = "keyword"; return cont(expression); }
641
+ }
642
+ function arrayLiteral(type) {
643
+ if (type == "]") return cont();
644
+ return pass(expressionNoComma, commasep(expressionNoComma, "]"));
645
+ }
646
+
647
+ function isContinuedStatement(state, textAfter) {
648
+ return state.lastType == "operator" || state.lastType == "," ||
649
+ isOperatorChar.test(textAfter.charAt(0)) ||
650
+ /[,.]/.test(textAfter.charAt(0));
651
+ }
652
+
653
+ // Interface
654
+
655
+ return {
656
+ startState: function(basecolumn) {
657
+ var state = {
658
+ tokenize: tokenBase,
659
+ lastType: "sof",
660
+ cc: [],
661
+ lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
662
+ localVars: parserConfig.localVars,
663
+ context: parserConfig.localVars && {vars: parserConfig.localVars},
664
+ indented: basecolumn || 0
665
+ };
666
+ if (parserConfig.globalVars && typeof parserConfig.globalVars == "object")
667
+ state.globalVars = parserConfig.globalVars;
668
+ return state;
669
+ },
670
+
671
+ token: function(stream, state) {
672
+ if (stream.sol()) {
673
+ if (!state.lexical.hasOwnProperty("align"))
674
+ state.lexical.align = false;
675
+ state.indented = stream.indentation();
676
+ findFatArrow(stream, state);
677
+ }
678
+ if (state.tokenize != tokenComment && stream.eatSpace()) return null;
679
+ var style = state.tokenize(stream, state);
680
+ if (type == "comment") return style;
681
+ state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type;
682
+ return parseJS(state, style, type, content, stream);
683
+ },
684
+
685
+ indent: function(state, textAfter) {
686
+ if (state.tokenize == tokenComment) return CodeMirror.Pass;
687
+ if (state.tokenize != tokenBase) return 0;
688
+ var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical;
689
+ // Kludge to prevent 'maybelse' from blocking lexical scope pops
690
+ if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) {
691
+ var c = state.cc[i];
692
+ if (c == poplex) lexical = lexical.prev;
693
+ else if (c != maybeelse) break;
694
+ }
695
+ if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev;
696
+ if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat")
697
+ lexical = lexical.prev;
698
+ var type = lexical.type, closing = firstChar == type;
699
+
700
+ if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info + 1 : 0);
701
+ else if (type == "form" && firstChar == "{") return lexical.indented;
702
+ else if (type == "form") return lexical.indented + indentUnit;
703
+ else if (type == "stat")
704
+ return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);
705
+ else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false)
706
+ return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
707
+ else if (lexical.align) return lexical.column + (closing ? 0 : 1);
708
+ else return lexical.indented + (closing ? 0 : indentUnit);
709
+ },
710
+
711
+ electricInput: /^\s*(?:case .*?:|default:|\{|\})$/,
712
+ blockCommentStart: jsonMode ? null : "/*",
713
+ blockCommentEnd: jsonMode ? null : "*/",
714
+ lineComment: jsonMode ? null : "//",
715
+ fold: "brace",
716
+ closeBrackets: "()[]{}''\"\"``",
717
+
718
+ helperType: jsonMode ? "json" : "javascript",
719
+ jsonldMode: jsonldMode,
720
+ jsonMode: jsonMode,
721
+
722
+ expressionAllowed: expressionAllowed,
723
+ skipExpression: function(state) {
724
+ var top = state.cc[state.cc.length - 1]
725
+ if (top == expression || top == expressionNoComma) state.cc.pop()
726
+ }
727
+ };
728
+ });
729
+
730
+ CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/);
731
+
732
+ CodeMirror.defineMIME("text/javascript", "javascript");
733
+ CodeMirror.defineMIME("text/ecmascript", "javascript");
734
+ CodeMirror.defineMIME("application/javascript", "javascript");
735
+ CodeMirror.defineMIME("application/x-javascript", "javascript");
736
+ CodeMirror.defineMIME("application/ecmascript", "javascript");
737
+ CodeMirror.defineMIME("application/json", {name: "javascript", json: true});
738
+ CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true});
739
+ CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true});
740
+ CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true });
741
+ CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true });
742
+
743
+ });
inc/lib/codemirror/mode/xml.js ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // CodeMirror, copyright (c) by Marijn Haverbeke and others
2
+ // Distributed under an MIT license: http://codemirror.net/LICENSE
3
+
4
+ (function(mod) {
5
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
6
+ mod(require("../../lib/codemirror"));
7
+ else if (typeof define == "function" && define.amd) // AMD
8
+ define(["../../lib/codemirror"], mod);
9
+ else // Plain browser env
10
+ mod(CodeMirror);
11
+ })(function(CodeMirror) {
12
+ "use strict";
13
+
14
+ var htmlConfig = {
15
+ autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,
16
+ 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,
17
+ 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,
18
+ 'track': true, 'wbr': true, 'menuitem': true},
19
+ implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,
20
+ 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,
21
+ 'th': true, 'tr': true},
22
+ contextGrabbers: {
23
+ 'dd': {'dd': true, 'dt': true},
24
+ 'dt': {'dd': true, 'dt': true},
25
+ 'li': {'li': true},
26
+ 'option': {'option': true, 'optgroup': true},
27
+ 'optgroup': {'optgroup': true},
28
+ 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,
29
+ 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,
30
+ 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,
31
+ 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,
32
+ 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},
33
+ 'rp': {'rp': true, 'rt': true},
34
+ 'rt': {'rp': true, 'rt': true},
35
+ 'tbody': {'tbody': true, 'tfoot': true},
36
+ 'td': {'td': true, 'th': true},
37
+ 'tfoot': {'tbody': true},
38
+ 'th': {'td': true, 'th': true},
39
+ 'thead': {'tbody': true, 'tfoot': true},
40
+ 'tr': {'tr': true}
41
+ },
42
+ doNotIndent: {"pre": true},
43
+ allowUnquoted: true,
44
+ allowMissing: true,
45
+ caseFold: true
46
+ }
47
+
48
+ var xmlConfig = {
49
+ autoSelfClosers: {},
50
+ implicitlyClosed: {},
51
+ contextGrabbers: {},
52
+ doNotIndent: {},
53
+ allowUnquoted: false,
54
+ allowMissing: false,
55
+ caseFold: false
56
+ }
57
+
58
+ CodeMirror.defineMode("xml", function(editorConf, config_) {
59
+ var indentUnit = editorConf.indentUnit
60
+ var config = {}
61
+ var defaults = config_.htmlMode ? htmlConfig : xmlConfig
62
+ for (var prop in defaults) config[prop] = defaults[prop]
63
+ for (var prop in config_) config[prop] = config_[prop]
64
+
65
+ // Return variables for tokenizers
66
+ var type, setStyle;
67
+
68
+ function inText(stream, state) {
69
+ function chain(parser) {
70
+ state.tokenize = parser;
71
+ return parser(stream, state);
72
+ }
73
+
74
+ var ch = stream.next();
75
+ if (ch == "<") {
76
+ if (stream.eat("!")) {
77
+ if (stream.eat("[")) {
78
+ if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
79
+ else return null;
80
+ } else if (stream.match("--")) {
81
+ return chain(inBlock("comment", "-->"));
82
+ } else if (stream.match("DOCTYPE", true, true)) {
83
+ stream.eatWhile(/[\w\._\-]/);
84
+ return chain(doctype(1));
85
+ } else {
86
+ return null;
87
+ }
88
+ } else if (stream.eat("?")) {
89
+ stream.eatWhile(/[\w\._\-]/);
90
+ state.tokenize = inBlock("meta", "?>");
91
+ return "meta";
92
+ } else {
93
+ type = stream.eat("/") ? "closeTag" : "openTag";
94
+ state.tokenize = inTag;
95
+ return "tag bracket";
96
+ }
97
+ } else if (ch == "&") {
98
+ var ok;
99
+ if (stream.eat("#")) {
100
+ if (stream.eat("x")) {
101
+ ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
102
+ } else {
103
+ ok = stream.eatWhile(/[\d]/) && stream.eat(";");
104
+ }
105
+ } else {
106
+ ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
107
+ }
108
+ return ok ? "atom" : "error";
109
+ } else {
110
+ stream.eatWhile(/[^&<]/);
111
+ return null;
112
+ }
113
+ }
114
+ inText.isInText = true;
115
+
116
+ function inTag(stream, state) {
117
+ var ch = stream.next();
118
+ if (ch == ">" || (ch == "/" && stream.eat(">"))) {
119
+ state.tokenize = inText;
120
+ type = ch == ">" ? "endTag" : "selfcloseTag";
121
+ return "tag bracket";
122
+ } else if (ch == "=") {
123
+ type = "equals";
124
+ return null;
125
+ } else if (ch == "<") {
126
+ state.tokenize = inText;
127
+ state.state = baseState;
128
+ state.tagName = state.tagStart = null;
129
+ var next = state.tokenize(stream, state);
130
+ return next ? next + " tag error" : "tag error";
131
+ } else if (/[\'\"]/.test(ch)) {
132
+ state.tokenize = inAttribute(ch);
133
+ state.stringStartCol = stream.column();
134
+ return state.tokenize(stream, state);
135
+ } else {
136
+ stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);
137
+ return "word";
138
+ }
139
+ }
140
+
141
+ function inAttribute(quote) {
142
+ var closure = function(stream, state) {
143
+ while (!stream.eol()) {
144
+ if (stream.next() == quote) {
145
+ state.tokenize = inTag;
146
+ break;
147
+ }
148
+ }
149
+ return "string";
150
+ };
151
+ closure.isInAttribute = true;
152
+ return closure;
153
+ }
154
+
155
+ function inBlock(style, terminator) {
156
+ return function(stream, state) {
157
+ while (!stream.eol()) {
158
+ if (stream.match(terminator)) {
159
+ state.tokenize = inText;
160
+ break;
161
+ }
162
+ stream.next();
163
+ }
164
+ return style;
165
+ };
166
+ }
167
+ function doctype(depth) {
168
+ return function(stream, state) {
169
+ var ch;
170
+ while ((ch = stream.next()) != null) {
171
+ if (ch == "<") {
172
+ state.tokenize = doctype(depth + 1);
173
+ return state.tokenize(stream, state);
174
+ } else if (ch == ">") {
175
+ if (depth == 1) {
176
+ state.tokenize = inText;
177
+ break;
178
+ } else {
179
+ state.tokenize = doctype(depth - 1);
180
+ return state.tokenize(stream, state);
181
+ }
182
+ }
183
+ }
184
+ return "meta";
185
+ };
186
+ }
187
+
188
+ function Context(state, tagName, startOfLine) {
189
+ this.prev = state.context;
190
+ this.tagName = tagName;
191
+ this.indent = state.indented;
192
+ this.startOfLine = startOfLine;
193
+ if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent))
194
+ this.noIndent = true;
195
+ }
196
+ function popContext(state) {
197
+ if (state.context) state.context = state.context.prev;
198
+ }
199
+ function maybePopContext(state, nextTagName) {
200
+ var parentTagName;
201
+ while (true) {
202
+ if (!state.context) {
203
+ return;
204
+ }
205
+ parentTagName = state.context.tagName;
206
+ if (!config.contextGrabbers.hasOwnProperty(parentTagName) ||
207
+ !config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {
208
+ return;
209
+ }
210
+ popContext(state);
211
+ }
212
+ }
213
+
214
+ function baseState(type, stream, state) {
215
+ if (type == "openTag") {
216
+ state.tagStart = stream.column();
217
+ return tagNameState;
218
+ } else if (type == "closeTag") {
219
+ return closeTagNameState;
220
+ } else {
221
+ return baseState;
222
+ }
223
+ }
224
+ function tagNameState(type, stream, state) {
225
+ if (type == "word") {
226
+ state.tagName = stream.current();
227
+ setStyle = "tag";
228
+ return attrState;
229
+ } else {
230
+ setStyle = "error";
231
+ return tagNameState;
232
+ }
233
+ }
234
+ function closeTagNameState(type, stream, state) {
235
+ if (type == "word") {
236
+ var tagName = stream.current();
237
+ if (state.context && state.context.tagName != tagName &&
238
+ config.implicitlyClosed.hasOwnProperty(state.context.tagName))
239
+ popContext(state);
240
+ if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) {
241
+ setStyle = "tag";
242
+ return closeState;
243
+ } else {
244
+ setStyle = "tag error";
245
+ return closeStateErr;
246
+ }
247
+ } else {
248
+ setStyle = "error";
249
+ return closeStateErr;
250
+ }
251
+ }
252
+
253
+ function closeState(type, _stream, state) {
254
+ if (type != "endTag") {
255
+ setStyle = "error";
256
+ return closeState;
257
+ }
258
+ popContext(state);
259
+ return baseState;
260
+ }
261
+ function closeStateErr(type, stream, state) {
262
+ setStyle = "error";
263
+ return closeState(type, stream, state);
264
+ }
265
+
266
+ function attrState(type, _stream, state) {
267
+ if (type == "word") {
268
+ setStyle = "attribute";
269
+ return attrEqState;
270
+ } else if (type == "endTag" || type == "selfcloseTag") {
271
+ var tagName = state.tagName, tagStart = state.tagStart;
272
+ state.tagName = state.tagStart = null;
273
+ if (type == "selfcloseTag" ||
274
+ config.autoSelfClosers.hasOwnProperty(tagName)) {
275
+ maybePopContext(state, tagName);
276
+ } else {
277
+ maybePopContext(state, tagName);
278
+ state.context = new Context(state, tagName, tagStart == state.indented);
279
+ }
280
+ return baseState;
281
+ }
282
+ setStyle = "error";
283
+ return attrState;
284
+ }
285
+ function attrEqState(type, stream, state) {
286
+ if (type == "equals") return attrValueState;
287
+ if (!config.allowMissing) setStyle = "error";
288
+ return attrState(type, stream, state);
289
+ }
290
+ function attrValueState(type, stream, state) {
291
+ if (type == "string") return attrContinuedState;
292
+ if (type == "word" && config.allowUnquoted) {setStyle = "string"; return attrState;}
293
+ setStyle = "error";
294
+ return attrState(type, stream, state);
295
+ }
296
+ function attrContinuedState(type, stream, state) {
297
+ if (type == "string") return attrContinuedState;
298
+ return attrState(type, stream, state);
299
+ }
300
+
301
+ return {
302
+ startState: function(baseIndent) {
303
+ var state = {tokenize: inText,
304
+ state: baseState,
305
+ indented: baseIndent || 0,
306
+ tagName: null, tagStart: null,
307
+ context: null}
308
+ if (baseIndent != null) state.baseIndent = baseIndent
309
+ return state
310
+ },
311
+
312
+ token: function(stream, state) {
313
+ if (!state.tagName && stream.sol())
314
+ state.indented = stream.indentation();
315
+
316
+ if (stream.eatSpace()) return null;
317
+ type = null;
318
+ var style = state.tokenize(stream, state);
319
+ if ((style || type) && style != "comment") {
320
+ setStyle = null;
321
+ state.state = state.state(type || style, stream, state);
322
+ if (setStyle)
323
+ style = setStyle == "error" ? style + " error" : setStyle;
324
+ }
325
+ return style;
326
+ },
327
+
328
+ indent: function(state, textAfter, fullLine) {
329
+ var context = state.context;
330
+ // Indent multi-line strings (e.g. css).
331
+ if (state.tokenize.isInAttribute) {
332
+ if (state.tagStart == state.indented)
333
+ return state.stringStartCol + 1;
334
+ else
335
+ return state.indented + indentUnit;
336
+ }
337
+ if (context && context.noIndent) return CodeMirror.Pass;
338
+ if (state.tokenize != inTag && state.tokenize != inText)
339
+ return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
340
+ // Indent the starts of attribute names.
341
+ if (state.tagName) {
342
+ if (config.multilineTagIndentPastTag !== false)
343
+ return state.tagStart + state.tagName.length + 2;
344
+ else
345
+ return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1);
346
+ }
347
+ if (config.alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
348
+ var tagAfter = textAfter && /^<(\/)?([\w_:\.-]*)/.exec(textAfter);
349
+ if (tagAfter && tagAfter[1]) { // Closing tag spotted
350
+ while (context) {
351
+ if (context.tagName == tagAfter[2]) {
352
+ context = context.prev;
353
+ break;
354
+ } else if (config.implicitlyClosed.hasOwnProperty(context.tagName)) {
355
+ context = context.prev;
356
+ } else {
357
+ break;
358
+ }
359
+ }
360
+ } else if (tagAfter) { // Opening tag spotted
361
+ while (context) {
362
+ var grabbers = config.contextGrabbers[context.tagName];
363
+ if (grabbers && grabbers.hasOwnProperty(tagAfter[2]))
364
+ context = context.prev;
365
+ else
366
+ break;
367
+ }
368
+ }
369
+ while (context && context.prev && !context.startOfLine)
370
+ context = context.prev;
371
+ if (context) return context.indent + indentUnit;
372
+ else return state.baseIndent || 0;
373
+ },
374
+
375
+ electricInput: /<\/[\s\w:]+>$/,
376
+ blockCommentStart: "<!--",
377
+ blockCommentEnd: "-->",
378
+
379
+ configuration: config.htmlMode ? "html" : "xml",
380
+ helperType: config.htmlMode ? "html" : "xml",
381
+
382
+ skipAttribute: function(state) {
383
+ if (state.state == attrValueState)
384
+ state.state = attrState
385
+ }
386
+ };
387
+ });
388
+
389
+ CodeMirror.defineMIME("text/xml", "xml");
390
+ CodeMirror.defineMIME("application/xml", "xml");
391
+ if (!CodeMirror.mimeModes.hasOwnProperty("text/html"))
392
+ CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});
393
+
394
+ });
inc/{settings_page.php → php/settings_page.php} RENAMED
@@ -10,21 +10,29 @@ defined('ABSPATH') or die("Restricted access!");
10
  /**
11
  * Render Settings Page
12
  *
13
- * @since 2.0
14
  */
15
  function HFScriptsIns_render_submenu_page() {
16
 
17
- // Declare variables
18
- $options = get_option( 'HFScriptsIns_settings' );
 
 
 
 
 
 
 
 
19
 
20
  // Page
21
  ?>
22
  <div class="wrap">
23
  <h2>
24
- <?php _e( 'Header and Footer Scripts Inserter', 'header-and-footer-scripts-inserter' ); ?>
25
  <br/>
26
  <span>
27
- <?php _e( 'by <a href="http://www.arthurgareginyan.com" target="_blank">Arthur "Berserkr" Gareginyan</a>', 'header-and-footer-scripts-inserter' ); ?>
28
  <span/>
29
  </h2>
30
 
@@ -37,43 +45,43 @@ function HFScriptsIns_render_submenu_page() {
37
  <div id="about" class="postbox">
38
  <h3 class="title"><?php _e( 'About', 'header-and-footer-scripts-inserter' ) ?></a></h3>
39
  <div class="inside">
40
- <p><?php _e( 'This plugin allows you to easily insert scripts in your website.', 'header-and-footer-scripts-inserter' ) ?></p>
41
  </div>
42
  </div>
43
 
44
  <div id="using" class="postbox">
45
  <h3 class="title"><?php _e( 'Using', 'header-and-footer-scripts-inserter' ) ?></a></h3>
46
  <div class="inside">
47
- <p><?php _e( 'To use, enter your custom scripts, then click "Save Changes". It\'s that simple!', 'header-and-footer-scripts-inserter' ) ?></p>
48
  </div>
49
  </div>
50
 
51
  <div id="help" class="postbox">
52
  <h3 class="title"><?php _e( 'Help', 'header-and-footer-scripts-inserter' ); ?></h3>
53
  <div class="inside">
54
- <p><?php _e( 'If you want more options then tell me and I will be happy to add it.', 'header-and-footer-scripts-inserter' ); ?></p>
55
- <p><a href="mailto:arthurgareginyan@gmail.com">arthurgareginyan@gmail.com</a></p>
56
  </div>
57
  </div>
58
 
59
  <div id="donate" class="postbox">
60
  <h3 class="title"><?php _e( 'Donate', 'header-and-footer-scripts-inserter' ) ?></h3>
61
  <div class="inside">
62
- <img src="<?php echo plugins_url('images/thanks.png', __FILE__); ?>">
63
- <p><?php _e( 'If you like this plugin and find it useful, help me to make this plugin even better and keep it up-to-date.', 'header-and-footer-scripts-inserter' ) ?></p>
64
  <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=8A88KC7TFF6CS" target="_blank" rel="nofollow">
65
- <img src="<?php echo plugins_url('images/btn_donateCC_LG.gif', __FILE__); ?>" alt="Make a donation">
66
  </a>
67
- <p><?php _e( 'Thanks for your support!', 'header-and-footer-scripts-inserter' ) ?></p>
68
  </div>
69
  </div>
70
 
71
  <div id="freelance" class="postbox">
72
  <h3 class="title"><?php _e( 'Freelance', 'header-and-footer-scripts-inserter' ) ?></h3>
73
  <div class="inside">
74
- <img src="<?php echo plugins_url('images/author.png', __FILE__); ?>">
75
- <p><?php _e( 'Hello, my name is Arthur and I\'m a freelance web designer and developer.', 'header-and-footer-scripts-inserter' ) ?></p>
76
- <p><?php _e( 'Share your thoughts with me. You may have a brilliant idea in your mind and I can make it happen, so let’s get started!', 'header-and-footer-scripts-inserter' ) ?></p>
77
  <p><a href="http://www.arthurgareginyan.com/" target="_blank">www.arthurgareginyan.com</a></p>
78
  </div>
79
  </div>
@@ -90,14 +98,32 @@ function HFScriptsIns_render_submenu_page() {
90
  <form name="HFScriptsIns-form" action="options.php" method="post" enctype="multipart/form-data">
91
  <?php settings_fields( 'HFScriptsIns_settings_group' ); ?>
92
 
93
- <div class="postbox" id="Header">
94
- <h3 class="title"><?php _e( 'Header Section', 'header-and-footer-scripts-inserter' ) ?></h3>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  <div class="inside">
96
- <p><?php _e( 'You can use the field below to add scripts to Header of your website.', 'header-and-footer-scripts-inserter' ) ?></p>
97
- <textarea cols='50' rows='10' name='HFScriptsIns_settings[header_beginning]' placeholder="<?php _e( '<!-- Beginning of the <head> tag -->', 'header-and-footer-scripts-inserter' ) ?>"><?php echo esc_attr( $options['header_beginning'] ); ?></textarea>
98
- <p class='help-text'><?php _e( 'Scripts from this field will be printed in the beginning of <b>HEAD</b> section. Do not place plain text in this!', 'header-and-footer-scripts-inserter' ) ?></p>
99
- <textarea cols='50' rows='10' name='HFScriptsIns_settings[header_end]' placeholder="<?php _e( '<!-- End of the <head> tag -->', 'header-and-footer-scripts-inserter' ) ?>"><?php echo esc_attr( $options['header_end'] ); ?></textarea>
100
- <p class='help-text'><?php _e( 'Scripts from this field will be printed in the end of <b>HEAD</b> section. Do not place plain text in this!', 'header-and-footer-scripts-inserter' ) ?></p>
101
  <?php submit_button( __( 'Save Changes', 'header-and-footer-scripts-inserter' ), 'primary', 'submit', true ); ?>
102
  </div>
103
  </div>
@@ -105,11 +131,11 @@ function HFScriptsIns_render_submenu_page() {
105
  <div class="postbox" id="Footer">
106
  <h3 class="title"><?php _e( 'Footer Section', 'header-and-footer-scripts-inserter' ) ?></h3>
107
  <div class="inside">
108
- <p><?php _e( 'You can use the field below to add scripts to Footer of your website.', 'header-and-footer-scripts-inserter' ) ?></p>
109
- <textarea cols='50' rows='10' name='HFScriptsIns_settings[footer_beginning]' placeholder="<?php _e( '<!-- Before a footers scripts -->', 'header-and-footer-scripts-inserter' ) ?>"><?php echo esc_attr( $options['footer_beginning'] ); ?></textarea>
110
- <p class='help-text'><?php _e( 'Scripts from this field will be printed before a footers scripts. Do not place plain text in this!', 'header-and-footer-scripts-inserter' ) ?></p>
111
- <textarea cols='50' rows='10' name='HFScriptsIns_settings[footer_end]' placeholder="<?php _e( '<!-- After all footers scripts -->', 'header-and-footer-scripts-inserter' ) ?>"><?php echo esc_attr( $options['footer_end'] ); ?></textarea>
112
- <p class='help-text'><?php _e( 'Scripts from this field will be printed after all footers scripts. Do not place plain text in this!', 'header-and-footer-scripts-inserter' ) ?></p>
113
  <?php submit_button( __( 'Save Changes', 'header-and-footer-scripts-inserter' ), 'primary', 'submit', true ); ?>
114
  </div>
115
  </div>
10
  /**
11
  * Render Settings Page
12
  *
13
+ * @since 3.0
14
  */
15
  function HFScriptsIns_render_submenu_page() {
16
 
17
+ // After settings updated
18
+ if ( isset( $_GET['settings-updated'] ) ) {
19
+
20
+ // Successful message
21
+ ?>
22
+ <div id="message" class="updated">
23
+ <p><?php _e( 'Scripts updated successfully.', 'header-and-footer-scripts-inserter' ); ?></p>
24
+ </div>
25
+ <?php
26
+ }
27
 
28
  // Page
29
  ?>
30
  <div class="wrap">
31
  <h2>
32
+ <?php _e( 'Head and Footer Scripts Inserter', 'header-and-footer-scripts-inserter' ); ?>
33
  <br/>
34
  <span>
35
+ <?php _e( 'by <a href="http://www.arthurgareginyan.com" target="_blank">Arthur Gareginyan</a>', 'header-and-footer-scripts-inserter' ); ?>
36
  <span/>
37
  </h2>
38
 
45
  <div id="about" class="postbox">
46
  <h3 class="title"><?php _e( 'About', 'header-and-footer-scripts-inserter' ) ?></a></h3>
47
  <div class="inside">
48
+ <p><?php _e( 'This plugin allows you to easily insert scripts in your website.', 'header-and-footer-scripts-inserter' ); ?></p>
49
  </div>
50
  </div>
51
 
52
  <div id="using" class="postbox">
53
  <h3 class="title"><?php _e( 'Using', 'header-and-footer-scripts-inserter' ) ?></a></h3>
54
  <div class="inside">
55
+ <p><?php _e( 'To use, enter your custom scripts, then click "Save Changes". It\'s that simple!', 'header-and-footer-scripts-inserter' ); ?></p>
56
  </div>
57
  </div>
58
 
59
  <div id="help" class="postbox">
60
  <h3 class="title"><?php _e( 'Help', 'header-and-footer-scripts-inserter' ); ?></h3>
61
  <div class="inside">
62
+ <p><?php _e( 'Got something to say? Need help?', 'header-and-footer-scripts-inserter' ); ?></p>
63
+ <p><a href="mailto:arthurgareginyan@gmail.com?subject=Head and Footer Scripts Inserter">arthurgareginyan@gmail.com</a></p>
64
  </div>
65
  </div>
66
 
67
  <div id="donate" class="postbox">
68
  <h3 class="title"><?php _e( 'Donate', 'header-and-footer-scripts-inserter' ) ?></h3>
69
  <div class="inside">
70
+ <img src="<?php echo plugins_url('../img/thanks.png', __FILE__); ?>">
71
+ <p><?php _e( 'If you like this plugin and find it useful, help me to make this plugin even better and keep it up-to-date.', 'header-and-footer-scripts-inserter' ); ?></p>
72
  <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=8A88KC7TFF6CS" target="_blank" rel="nofollow">
73
+ <img src="<?php echo plugins_url('../img/btn_donateCC_LG.gif', __FILE__); ?>" alt="Make a donation">
74
  </a>
75
+ <p><?php _e( 'Thanks for your support!', 'header-and-footer-scripts-inserter' ); ?></p>
76
  </div>
77
  </div>
78
 
79
  <div id="freelance" class="postbox">
80
  <h3 class="title"><?php _e( 'Freelance', 'header-and-footer-scripts-inserter' ) ?></h3>
81
  <div class="inside">
82
+ <img src="<?php echo plugins_url('../img/author.png', __FILE__); ?>">
83
+ <p><?php _e( 'Hello, my name is Arthur and I\'m a freelance web designer and developer.', 'header-and-footer-scripts-inserter' ); ?></p>
84
+ <p><?php _e( 'Share your thoughts with me. You may have a brilliant idea in your mind and I can make it happen, so let’s get started!', 'header-and-footer-scripts-inserter' ); ?></p>
85
  <p><a href="http://www.arthurgareginyan.com/" target="_blank">www.arthurgareginyan.com</a></p>
86
  </div>
87
  </div>
98
  <form name="HFScriptsIns-form" action="options.php" method="post" enctype="multipart/form-data">
99
  <?php settings_fields( 'HFScriptsIns_settings_group' ); ?>
100
 
101
+ <?php
102
+ // Declare variables
103
+ $options = get_option( 'HFScriptsIns_settings' );
104
+ $header_beginning = isset( $options['header_beginning'] ) && !empty( $options['header_beginning'] ) ? esc_attr( $options['header_beginning'] ) : '';
105
+ $header_end = isset( $options['header_end'] ) && !empty( $options['header_end'] ) ? esc_attr( $options['header_end'] ) : '';
106
+ $footer_beginning = isset( $options['footer_beginning'] ) && !empty( $options['footer_beginning'] ) ? esc_attr( $options['footer_beginning'] ) : '';
107
+ $footer_end = isset( $options['footer_end'] ) && !empty( $options['footer_end'] ) ? esc_attr( $options['footer_end'] ) : '';
108
+
109
+ // Add rows if all the rows is less than 10
110
+ $type = array("header_beginning", "header_end", "footer_beginning", "footer_end");
111
+ foreach ($type as $value) {
112
+ $i = count(explode("\n", $$value));
113
+ for ( $i = $i; $i < 10; $i++) {
114
+ $$value .= "\n";
115
+ }
116
+ }
117
+ ?>
118
+
119
+ <div class="postbox" id="Head">
120
+ <h3 class="title"><?php _e( 'Head Section', 'header-and-footer-scripts-inserter' ) ?></h3>
121
  <div class="inside">
122
+ <p><?php _e( 'You can use the fields below to add scripts to Head of your website.', 'header-and-footer-scripts-inserter' ); ?></p>
123
+ <textarea name="HFScriptsIns_settings[header_beginning]" id="HFScriptsIns_settings[header_beginning]" ><?php echo $header_beginning; ?></textarea>
124
+ <p class='help-text'><?php _e( 'Scripts from this field will be printed in the beginning of <b>HEAD</b> section. Do not place plain text in this!', 'header-and-footer-scripts-inserter' ); ?></p>
125
+ <textarea name="HFScriptsIns_settings[header_end]" id="HFScriptsIns_settings[header_end]" ><?php echo $header_end; ?></textarea>
126
+ <p class='help-text'><?php _e( 'Scripts from this field will be printed in the end of <b>HEAD</b> section. Do not place plain text in this!', 'header-and-footer-scripts-inserter' ); ?></p>
127
  <?php submit_button( __( 'Save Changes', 'header-and-footer-scripts-inserter' ), 'primary', 'submit', true ); ?>
128
  </div>
129
  </div>
131
  <div class="postbox" id="Footer">
132
  <h3 class="title"><?php _e( 'Footer Section', 'header-and-footer-scripts-inserter' ) ?></h3>
133
  <div class="inside">
134
+ <p><?php _e( 'You can use the fields below to add scripts to Footer of your website.', 'header-and-footer-scripts-inserter' ); ?></p>
135
+ <textarea name="HFScriptsIns_settings[footer_beginning]" id="HFScriptsIns_settings[footer_beginning]" ><?php echo $footer_beginning; ?></textarea>
136
+ <p class='help-text'><?php _e( 'Scripts from this field will be printed before a footers scripts. Do not place plain text in this!', 'header-and-footer-scripts-inserter' ); ?></p>
137
+ <textarea name="HFScriptsIns_settings[footer_end]" id="HFScriptsIns_settings[footer_end]" ><?php echo $footer_end; ?></textarea>
138
+ <p class='help-text'><?php _e( 'Scripts from this field will be printed after all footers scripts. Do not place plain text in this!', 'header-and-footer-scripts-inserter' ); ?></p>
139
  <?php submit_button( __( 'Save Changes', 'header-and-footer-scripts-inserter' ), 'primary', 'submit', true ); ?>
140
  </div>
141
  </div>
languages/header-and-footer-scripts-inserter-pl_PL.mo CHANGED
Binary file
languages/header-and-footer-scripts-inserter-pl_PL.po CHANGED
@@ -2,8 +2,8 @@ msgid ""
2
  msgstr ""
3
  "Project-Id-Version: Header and Footer Scripts Inserter\n"
4
  "Report-Msgid-Bugs-To: \n"
5
- "POT-Creation-Date: 2016-04-09 14:01+0300\n"
6
- "PO-Revision-Date: 2016-04-09 14:01+0300\n"
7
  "Last-Translator: psouu <koko887@wp.pl>\n"
8
  "Language-Team: \n"
9
  "Language: pl\n"
@@ -30,31 +30,35 @@ msgid "Settings"
30
  msgstr "Ustawienia"
31
 
32
  #. Plugin Name of the plugin/theme
33
- #: header-and-footer-scripts-inserter.php:82 inc/settings_page.php:24
34
- msgid "Header and Footer Scripts Inserter"
35
  msgstr "Wstawianie kodu do nagłówka i stopki"
36
 
37
- #: inc/settings_page.php:27
 
 
 
 
38
  msgid ""
39
  "by <a href=\"http://www.arthurgareginyan.com\" target=\"_blank\">Arthur "
40
- "\"Berserkr\" Gareginyan</a>"
41
  msgstr ""
42
  "wykonana przez <a href=\"http://www.arthurgareginyan.com\" target=\"_blank"
43
- "\">Arthura \"Berserkra\" Gareginyana</a>"
44
 
45
- #: inc/settings_page.php:38
46
  msgid "About"
47
  msgstr "O wtyczce"
48
 
49
- #: inc/settings_page.php:40
50
  msgid "This plugin allows you to easily insert scripts in your website."
51
  msgstr "Ta wtyczka pozwala łatwo wstawić kod skryptów na stronę www."
52
 
53
- #: inc/settings_page.php:45
54
  msgid "Using"
55
  msgstr ""
56
 
57
- #: inc/settings_page.php:47
58
  msgid ""
59
  "To use, enter your custom scripts, then click \"Save Changes\". It's that "
60
  "simple!"
@@ -62,19 +66,19 @@ msgstr ""
62
  "Aby użyć, wprowadź kod skryptów, a następnie kliknij przycisk \"Zapisz\". To "
63
  "takie proste!"
64
 
65
- #: inc/settings_page.php:52
66
  msgid "Help"
67
  msgstr "Pomoc"
68
 
69
- #: inc/settings_page.php:54
70
- msgid "If you want more options then tell me and I will be happy to add it."
71
- msgstr "Jeśli potrzebujesz więcej opcji napisz mi o tym. Chętnie je dodam."
72
 
73
- #: inc/settings_page.php:60
74
  msgid "Donate"
75
  msgstr "Wesprzyj"
76
 
77
- #: inc/settings_page.php:63
78
  msgid ""
79
  "If you like this plugin and find it useful, help me to make this plugin even "
80
  "better and keep it up-to-date."
@@ -82,38 +86,34 @@ msgstr ""
82
  "Jeśli lubisz tę wtyczkę uważasz że jest przydatna, pomóż mi aby jeszcze "
83
  "lepsza i bądź na bieżąco z aktualizacjami."
84
 
85
- #: inc/settings_page.php:67
86
  msgid "Thanks for your support!"
87
  msgstr "Dziękujemy za wsparcie!"
88
 
89
- #: inc/settings_page.php:72
90
  msgid "Freelance"
91
  msgstr ""
92
 
93
- #: inc/settings_page.php:75
94
  msgid ""
95
  "Hello, my name is Arthur and I'm a freelance web designer and developer."
96
  msgstr ""
97
 
98
- #: inc/settings_page.php:76
99
  msgid ""
100
  "Share your thoughts with me. You may have a brilliant idea in your mind and "
101
  "I can make it happen, so let’s get started!"
102
  msgstr ""
103
 
104
- #: inc/settings_page.php:94
105
- msgid "Header Section"
106
  msgstr "Sekcja: Nagłówek"
107
 
108
- #: inc/settings_page.php:96
109
- msgid "You can use the field below to add scripts to Header of your website."
110
  msgstr "Pola poniżej można użyć, aby dodać kody skryptów do nagłówka witryny."
111
 
112
- #: inc/settings_page.php:97
113
- msgid "<!-- Beginning of the <head> tag -->"
114
- msgstr "<!-- Początek sekcji <head> -->"
115
-
116
- #: inc/settings_page.php:98
117
  msgid ""
118
  "Scripts from this field will be printed in the beginning of <b>HEAD</b> "
119
  "section. Do not place plain text in this!"
@@ -121,11 +121,7 @@ msgstr ""
121
  "Skrypty z tego pola zostaną dodane na początku sekcji <b>HEAD</b>. Nie "
122
  "należy tu umieszczać zwykłego tekstu!"
123
 
124
- #: inc/settings_page.php:99
125
- msgid "<!-- End of the <head> tag -->"
126
- msgstr "<!-- Koniec sekcji <head> -->"
127
-
128
- #: inc/settings_page.php:100
129
  msgid ""
130
  "Scripts from this field will be printed in the end of <b>HEAD</b> section. "
131
  "Do not place plain text in this!"
@@ -133,23 +129,19 @@ msgstr ""
133
  "Skrypty z tego pola zostaną dodane na końcu sekcji <b>HEAD</b>. Nie należy "
134
  "tu umieszczać zwykłego tekstu!"
135
 
136
- #: inc/settings_page.php:101 inc/settings_page.php:113
137
  msgid "Save Changes"
138
  msgstr "Zapisz"
139
 
140
- #: inc/settings_page.php:106
141
  msgid "Footer Section"
142
  msgstr "Sekcja: Stopka"
143
 
144
- #: inc/settings_page.php:108
145
- msgid "You can use the field below to add scripts to Footer of your website."
146
  msgstr "Pola poniżej można użyć, aby dodać kody skryptów do stopki witryny."
147
 
148
- #: inc/settings_page.php:109
149
- msgid "<!-- Before a footers scripts -->"
150
- msgstr "<!-- Początek stopki -->"
151
-
152
- #: inc/settings_page.php:110
153
  msgid ""
154
  "Scripts from this field will be printed before a footers scripts. Do not "
155
  "place plain text in this!"
@@ -157,11 +149,7 @@ msgstr ""
157
  "Skrypty z tego pola zostaną dodane przed skryptami ze stopki. Nie należy tu "
158
  "umieszczać zwykłego tekstu!"
159
 
160
- #: inc/settings_page.php:111
161
- msgid "<!-- After all footers scripts -->"
162
- msgstr "<!-- Koniec stopki -->"
163
-
164
- #: inc/settings_page.php:112
165
  msgid ""
166
  "Scripts from this field will be printed after all footers scripts. Do not "
167
  "place plain text in this!"
@@ -175,20 +163,64 @@ msgstr "https://github.com/ArthurGareginyan/header-and-footer-scripts-inserter"
175
 
176
  #. Description of the plugin/theme
177
  msgid ""
178
- "Easily add your scripts to the WordPress website's head or/and footer "
179
- "section. This is a must have tool for authors and website's owners."
180
  msgstr ""
181
  "Łatwe dodawanie kodu skryptów do nagłówka i stopki strony opartej na "
182
  "WordPressie."
183
 
184
  #. Author of the plugin/theme
185
  msgid "Arthur Gareginyan"
186
- msgstr ""
187
 
188
  #. Author URI of the plugin/theme
189
  msgid "http://www.arthurgareginyan.com"
190
  msgstr "http://www.arthurgareginyan.com"
191
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
  #~ msgid "Arthur \"Berserkr\" Gareginyan"
193
  #~ msgstr "Arthur \"Berserkr\" Gareginyan"
194
 
2
  msgstr ""
3
  "Project-Id-Version: Header and Footer Scripts Inserter\n"
4
  "Report-Msgid-Bugs-To: \n"
5
+ "POT-Creation-Date: 2016-07-29 21:20+0300\n"
6
+ "PO-Revision-Date: 2016-07-29 21:29+0300\n"
7
  "Last-Translator: psouu <koko887@wp.pl>\n"
8
  "Language-Team: \n"
9
  "Language: pl\n"
30
  msgstr "Ustawienia"
31
 
32
  #. Plugin Name of the plugin/theme
33
+ #: header-and-footer-scripts-inserter.php:82 inc/settings_page.php:32
34
+ msgid "Head and Footer Scripts Inserter"
35
  msgstr "Wstawianie kodu do nagłówka i stopki"
36
 
37
+ #: inc/settings_page.php:23
38
+ msgid "Scripts updated successfully."
39
+ msgstr ""
40
+
41
+ #: inc/settings_page.php:35
42
  msgid ""
43
  "by <a href=\"http://www.arthurgareginyan.com\" target=\"_blank\">Arthur "
44
+ "Gareginyan</a>"
45
  msgstr ""
46
  "wykonana przez <a href=\"http://www.arthurgareginyan.com\" target=\"_blank"
47
+ "\">Arthur Gareginyan</a>"
48
 
49
+ #: inc/settings_page.php:46
50
  msgid "About"
51
  msgstr "O wtyczce"
52
 
53
+ #: inc/settings_page.php:48
54
  msgid "This plugin allows you to easily insert scripts in your website."
55
  msgstr "Ta wtyczka pozwala łatwo wstawić kod skryptów na stronę www."
56
 
57
+ #: inc/settings_page.php:53
58
  msgid "Using"
59
  msgstr ""
60
 
61
+ #: inc/settings_page.php:55
62
  msgid ""
63
  "To use, enter your custom scripts, then click \"Save Changes\". It's that "
64
  "simple!"
66
  "Aby użyć, wprowadź kod skryptów, a następnie kliknij przycisk \"Zapisz\". To "
67
  "takie proste!"
68
 
69
+ #: inc/settings_page.php:60
70
  msgid "Help"
71
  msgstr "Pomoc"
72
 
73
+ #: inc/settings_page.php:62
74
+ msgid "Got something to say? Need help?"
75
+ msgstr "Masz coś do powiedzenia? Potrzebujesz pomocy?"
76
 
77
+ #: inc/settings_page.php:68
78
  msgid "Donate"
79
  msgstr "Wesprzyj"
80
 
81
+ #: inc/settings_page.php:71
82
  msgid ""
83
  "If you like this plugin and find it useful, help me to make this plugin even "
84
  "better and keep it up-to-date."
86
  "Jeśli lubisz tę wtyczkę uważasz że jest przydatna, pomóż mi aby jeszcze "
87
  "lepsza i bądź na bieżąco z aktualizacjami."
88
 
89
+ #: inc/settings_page.php:75
90
  msgid "Thanks for your support!"
91
  msgstr "Dziękujemy za wsparcie!"
92
 
93
+ #: inc/settings_page.php:80
94
  msgid "Freelance"
95
  msgstr ""
96
 
97
+ #: inc/settings_page.php:83
98
  msgid ""
99
  "Hello, my name is Arthur and I'm a freelance web designer and developer."
100
  msgstr ""
101
 
102
+ #: inc/settings_page.php:84
103
  msgid ""
104
  "Share your thoughts with me. You may have a brilliant idea in your mind and "
105
  "I can make it happen, so let’s get started!"
106
  msgstr ""
107
 
108
+ #: inc/settings_page.php:120
109
+ msgid "Head Section"
110
  msgstr "Sekcja: Nagłówek"
111
 
112
+ #: inc/settings_page.php:122
113
+ msgid "You can use the fields below to add scripts to Head of your website."
114
  msgstr "Pola poniżej można użyć, aby dodać kody skryptów do nagłówka witryny."
115
 
116
+ #: inc/settings_page.php:124
 
 
 
 
117
  msgid ""
118
  "Scripts from this field will be printed in the beginning of <b>HEAD</b> "
119
  "section. Do not place plain text in this!"
121
  "Skrypty z tego pola zostaną dodane na początku sekcji <b>HEAD</b>. Nie "
122
  "należy tu umieszczać zwykłego tekstu!"
123
 
124
+ #: inc/settings_page.php:126
 
 
 
 
125
  msgid ""
126
  "Scripts from this field will be printed in the end of <b>HEAD</b> section. "
127
  "Do not place plain text in this!"
129
  "Skrypty z tego pola zostaną dodane na końcu sekcji <b>HEAD</b>. Nie należy "
130
  "tu umieszczać zwykłego tekstu!"
131
 
132
+ #: inc/settings_page.php:127 inc/settings_page.php:139
133
  msgid "Save Changes"
134
  msgstr "Zapisz"
135
 
136
+ #: inc/settings_page.php:132
137
  msgid "Footer Section"
138
  msgstr "Sekcja: Stopka"
139
 
140
+ #: inc/settings_page.php:134
141
+ msgid "You can use the fields below to add scripts to Footer of your website."
142
  msgstr "Pola poniżej można użyć, aby dodać kody skryptów do stopki witryny."
143
 
144
+ #: inc/settings_page.php:136
 
 
 
 
145
  msgid ""
146
  "Scripts from this field will be printed before a footers scripts. Do not "
147
  "place plain text in this!"
149
  "Skrypty z tego pola zostaną dodane przed skryptami ze stopki. Nie należy tu "
150
  "umieszczać zwykłego tekstu!"
151
 
152
+ #: inc/settings_page.php:138
 
 
 
 
153
  msgid ""
154
  "Scripts from this field will be printed after all footers scripts. Do not "
155
  "place plain text in this!"
163
 
164
  #. Description of the plugin/theme
165
  msgid ""
166
+ "Easily add your scripts to the WordPress website's head and footer sections. "
167
+ "This is a must have tool for authors and website's owners."
168
  msgstr ""
169
  "Łatwe dodawanie kodu skryptów do nagłówka i stopki strony opartej na "
170
  "WordPressie."
171
 
172
  #. Author of the plugin/theme
173
  msgid "Arthur Gareginyan"
174
+ msgstr "Arthur Gareginyan"
175
 
176
  #. Author URI of the plugin/theme
177
  msgid "http://www.arthurgareginyan.com"
178
  msgstr "http://www.arthurgareginyan.com"
179
 
180
+ #~ msgid "Header and Footer Scripts Inserter"
181
+ #~ msgstr "Wstawianie kodu do nagłówka i stopki"
182
+
183
+ #~ msgid ""
184
+ #~ "by <a href=\"http://www.arthurgareginyan.com\" target=\"_blank\">Arthur "
185
+ #~ "\"Berserkr\" Gareginyan</a>"
186
+ #~ msgstr ""
187
+ #~ "wykonana przez <a href=\"http://www.arthurgareginyan.com\" target=\"_blank"
188
+ #~ "\">Arthura \"Berserkra\" Gareginyana</a>"
189
+
190
+ #~ msgid "If you want more options then tell me and I will be happy to add it."
191
+ #~ msgstr "Jeśli potrzebujesz więcej opcji napisz mi o tym. Chętnie je dodam."
192
+
193
+ #~ msgid "Header Section"
194
+ #~ msgstr "Sekcja: Nagłówek"
195
+
196
+ #~ msgid ""
197
+ #~ "You can use the field below to add scripts to Header of your website."
198
+ #~ msgstr ""
199
+ #~ "Pola poniżej można użyć, aby dodać kody skryptów do nagłówka witryny."
200
+
201
+ #~ msgid "<!-- Beginning of the <head> tag -->"
202
+ #~ msgstr "<!-- Początek sekcji <head> -->"
203
+
204
+ #~ msgid "<!-- End of the <head> tag -->"
205
+ #~ msgstr "<!-- Koniec sekcji <head> -->"
206
+
207
+ #~ msgid ""
208
+ #~ "You can use the field below to add scripts to Footer of your website."
209
+ #~ msgstr "Pola poniżej można użyć, aby dodać kody skryptów do stopki witryny."
210
+
211
+ #~ msgid "<!-- Before a footers scripts -->"
212
+ #~ msgstr "<!-- Początek stopki -->"
213
+
214
+ #~ msgid "<!-- After all footers scripts -->"
215
+ #~ msgstr "<!-- Koniec stopki -->"
216
+
217
+ #~ msgid ""
218
+ #~ "Easily add your scripts to the WordPress website's head or/and footer "
219
+ #~ "section. This is a must have tool for authors and website's owners."
220
+ #~ msgstr ""
221
+ #~ "Łatwe dodawanie kodu skryptów do nagłówka i stopki strony opartej na "
222
+ #~ "WordPressie."
223
+
224
  #~ msgid "Arthur \"Berserkr\" Gareginyan"
225
  #~ msgstr "Arthur \"Berserkr\" Gareginyan"
226
 
languages/header-and-footer-scripts-inserter-ru_RU.mo CHANGED
Binary file
languages/header-and-footer-scripts-inserter-ru_RU.po CHANGED
@@ -1,8 +1,8 @@
1
  msgid ""
2
  msgstr ""
3
  "Project-Id-Version: Header and Footer Scripts Inserter\n"
4
- "POT-Creation-Date: 2016-04-09 14:00+0300\n"
5
- "PO-Revision-Date: 2016-04-09 14:00+0300\n"
6
  "Last-Translator: \n"
7
  "Language-Team: \n"
8
  "Language: ru\n"
@@ -26,31 +26,35 @@ msgid "Settings"
26
  msgstr "Настройки"
27
 
28
  #. Plugin Name of the plugin/theme
29
- #: header-and-footer-scripts-inserter.php:82 inc/settings_page.php:24
30
- msgid "Header and Footer Scripts Inserter"
31
  msgstr ""
32
 
33
- #: inc/settings_page.php:27
 
 
 
 
34
  msgid ""
35
  "by <a href=\"http://www.arthurgareginyan.com\" target=\"_blank\">Arthur "
36
- "\"Berserkr\" Gareginyan</a>"
37
  msgstr ""
38
- "от <a href=“http://www.arthurgareginyan.com target=“_blank”>Артур "
39
- "“Berserkr” Гарегинян</a>"
40
 
41
- #: inc/settings_page.php:38
42
  msgid "About"
43
  msgstr "О платине"
44
 
45
- #: inc/settings_page.php:40
46
  msgid "This plugin allows you to easily insert scripts in your website."
47
  msgstr "Этот плагин позволяет легко вставлять скрипты в ваш веб-сайте."
48
 
49
- #: inc/settings_page.php:45
50
  msgid "Using"
51
  msgstr "Использование:"
52
 
53
- #: inc/settings_page.php:47
54
  msgid ""
55
  "To use, enter your custom scripts, then click \"Save Changes\". It's that "
56
  "simple!"
@@ -58,21 +62,19 @@ msgstr ""
58
  "Для использования, вставьте ваши пользовательские скрипты, затем нажмите "
59
  "кнопку “Сохранить изменения”. Это так просто!"
60
 
61
- #: inc/settings_page.php:52
62
  msgid "Help"
63
  msgstr "Помощь"
64
 
65
- #: inc/settings_page.php:54
66
- msgid "If you want more options then tell me and I will be happy to add it."
67
- msgstr ""
68
- "Если вы хотите больше опций, то скажите мне об этом и я буду счастлив "
69
- "добавить их."
70
 
71
- #: inc/settings_page.php:60
72
  msgid "Donate"
73
  msgstr "Пожертвование"
74
 
75
- #: inc/settings_page.php:63
76
  msgid ""
77
  "If you like this plugin and find it useful, help me to make this plugin even "
78
  "better and keep it up-to-date."
@@ -80,20 +82,20 @@ msgstr ""
80
  "Если вам нравится этот плагин и вы находите его полезным, то помогите мне "
81
  "сделать его ещё лучше."
82
 
83
- #: inc/settings_page.php:67
84
  msgid "Thanks for your support!"
85
  msgstr "Спасибо за вашу поддержку!"
86
 
87
- #: inc/settings_page.php:72
88
  msgid "Freelance"
89
  msgstr "Фриланс"
90
 
91
- #: inc/settings_page.php:75
92
  msgid ""
93
  "Hello, my name is Arthur and I'm a freelance web designer and developer."
94
  msgstr "Привет, меня зовут Артур и Я внештатный веб-дизайнер и разработчик."
95
 
96
- #: inc/settings_page.php:76
97
  msgid ""
98
  "Share your thoughts with me. You may have a brilliant idea in your mind and "
99
  "I can make it happen, so let’s get started!"
@@ -101,69 +103,61 @@ msgstr ""
101
  "Поделитесь со мной своими мыслями. У вас может быть блестящая идея в уме, а "
102
  "я могу сделать её явью, так что давайте начнём!"
103
 
104
- #: inc/settings_page.php:94
105
- msgid "Header Section"
106
- msgstr "Раздел HEADER"
107
-
108
- #: inc/settings_page.php:96
109
- msgid "You can use the field below to add scripts to Header of your website."
110
- msgstr ""
111
- "Используйте поле расположение ниже для того, чтобы добавить скрипты в "
112
- "верхний колонтитул вашего сайта."
113
 
114
- #: inc/settings_page.php:97
115
- msgid "<!-- Beginning of the <head> tag -->"
116
  msgstr ""
 
 
117
 
118
- #: inc/settings_page.php:98
119
  msgid ""
120
  "Scripts from this field will be printed in the beginning of <b>HEAD</b> "
121
  "section. Do not place plain text in this!"
122
  msgstr ""
 
 
123
 
124
- #: inc/settings_page.php:99
125
- msgid "<!-- End of the <head> tag -->"
126
- msgstr ""
127
-
128
- #: inc/settings_page.php:100
129
  msgid ""
130
  "Scripts from this field will be printed in the end of <b>HEAD</b> section. "
131
  "Do not place plain text in this!"
132
  msgstr ""
 
 
133
 
134
- #: inc/settings_page.php:101 inc/settings_page.php:113
135
  msgid "Save Changes"
136
- msgstr "Сохранить изменения"
137
 
138
- #: inc/settings_page.php:106
139
  msgid "Footer Section"
140
- msgstr "Раздел FOOTER"
141
-
142
- #: inc/settings_page.php:108
143
- msgid "You can use the field below to add scripts to Footer of your website."
144
- msgstr ""
145
- "Используйте поле расположение ниже для того, чтобы добавить скрипты в нижний "
146
- "колонтитул вашего сайта."
147
 
148
- #: inc/settings_page.php:109
149
- msgid "<!-- Before a footers scripts -->"
150
  msgstr ""
 
 
151
 
152
- #: inc/settings_page.php:110
153
  msgid ""
154
  "Scripts from this field will be printed before a footers scripts. Do not "
155
  "place plain text in this!"
156
  msgstr ""
 
 
157
 
158
- #: inc/settings_page.php:111
159
- msgid "<!-- After all footers scripts -->"
160
- msgstr ""
161
-
162
- #: inc/settings_page.php:112
163
  msgid ""
164
  "Scripts from this field will be printed after all footers scripts. Do not "
165
  "place plain text in this!"
166
  msgstr ""
 
 
167
 
168
  #. Plugin URI of the plugin/theme
169
  msgid "https://github.com/ArthurGareginyan/header-and-footer-scripts-inserter"
@@ -171,11 +165,12 @@ msgstr ""
171
 
172
  #. Description of the plugin/theme
173
  msgid ""
174
- "Easily add your scripts to the WordPress website's head or/and footer "
175
- "section. This is a must have tool for authors and website's owners."
176
  msgstr ""
177
- "Легко добавляйте ваши скрипты в шапку и/или колонтитул вашего WordPress веб-"
178
- "сайта. Это необходимый инструмент для авторов и владельцев веб-сайтов."
 
179
 
180
  #. Author of the plugin/theme
181
  msgid "Arthur Gareginyan"
@@ -185,5 +180,39 @@ msgstr "Артур Гарегинян"
185
  msgid "http://www.arthurgareginyan.com"
186
  msgstr ""
187
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
188
  #~ msgid "Arthur \"Berserkr\" Gareginyan"
189
  #~ msgstr "Артур “Берсеркр” Гарегинян"
1
  msgid ""
2
  msgstr ""
3
  "Project-Id-Version: Header and Footer Scripts Inserter\n"
4
+ "POT-Creation-Date: 2016-07-29 21:00+0300\n"
5
+ "PO-Revision-Date: 2016-07-29 21:20+0300\n"
6
  "Last-Translator: \n"
7
  "Language-Team: \n"
8
  "Language: ru\n"
26
  msgstr "Настройки"
27
 
28
  #. Plugin Name of the plugin/theme
29
+ #: header-and-footer-scripts-inserter.php:82 inc/settings_page.php:32
30
+ msgid "Head and Footer Scripts Inserter"
31
  msgstr ""
32
 
33
+ #: inc/settings_page.php:23
34
+ msgid "Scripts updated successfully."
35
+ msgstr "Скрипты успешно обновлены."
36
+
37
+ #: inc/settings_page.php:35
38
  msgid ""
39
  "by <a href=\"http://www.arthurgareginyan.com\" target=\"_blank\">Arthur "
40
+ "Gareginyan</a>"
41
  msgstr ""
42
+ "от <a href=\"http://www.arthurgareginyan.com\" target=\"_blank\">Артур "
43
+ "Гарегинян</a>"
44
 
45
+ #: inc/settings_page.php:46
46
  msgid "About"
47
  msgstr "О платине"
48
 
49
+ #: inc/settings_page.php:48
50
  msgid "This plugin allows you to easily insert scripts in your website."
51
  msgstr "Этот плагин позволяет легко вставлять скрипты в ваш веб-сайте."
52
 
53
+ #: inc/settings_page.php:53
54
  msgid "Using"
55
  msgstr "Использование:"
56
 
57
+ #: inc/settings_page.php:55
58
  msgid ""
59
  "To use, enter your custom scripts, then click \"Save Changes\". It's that "
60
  "simple!"
62
  "Для использования, вставьте ваши пользовательские скрипты, затем нажмите "
63
  "кнопку “Сохранить изменения”. Это так просто!"
64
 
65
+ #: inc/settings_page.php:60
66
  msgid "Help"
67
  msgstr "Помощь"
68
 
69
+ #: inc/settings_page.php:62
70
+ msgid "Got something to say? Need help?"
71
+ msgstr "Есть что сказать? Нужна помощь?"
 
 
72
 
73
+ #: inc/settings_page.php:68
74
  msgid "Donate"
75
  msgstr "Пожертвование"
76
 
77
+ #: inc/settings_page.php:71
78
  msgid ""
79
  "If you like this plugin and find it useful, help me to make this plugin even "
80
  "better and keep it up-to-date."
82
  "Если вам нравится этот плагин и вы находите его полезным, то помогите мне "
83
  "сделать его ещё лучше."
84
 
85
+ #: inc/settings_page.php:75
86
  msgid "Thanks for your support!"
87
  msgstr "Спасибо за вашу поддержку!"
88
 
89
+ #: inc/settings_page.php:80
90
  msgid "Freelance"
91
  msgstr "Фриланс"
92
 
93
+ #: inc/settings_page.php:83
94
  msgid ""
95
  "Hello, my name is Arthur and I'm a freelance web designer and developer."
96
  msgstr "Привет, меня зовут Артур и Я внештатный веб-дизайнер и разработчик."
97
 
98
+ #: inc/settings_page.php:84
99
  msgid ""
100
  "Share your thoughts with me. You may have a brilliant idea in your mind and "
101
  "I can make it happen, so let’s get started!"
103
  "Поделитесь со мной своими мыслями. У вас может быть блестящая идея в уме, а "
104
  "я могу сделать её явью, так что давайте начнём!"
105
 
106
+ #: inc/settings_page.php:120
107
+ msgid "Head Section"
108
+ msgstr "Верхний колонтитул (HEAD)"
 
 
 
 
 
 
109
 
110
+ #: inc/settings_page.php:122
111
+ msgid "You can use the fields below to add scripts to Head of your website."
112
  msgstr ""
113
+ "Используйте поле расположенное ниже для того, чтобы добавить скрипты в "
114
+ "верхний колонтитул вашего вебсайта."
115
 
116
+ #: inc/settings_page.php:124
117
  msgid ""
118
  "Scripts from this field will be printed in the beginning of <b>HEAD</b> "
119
  "section. Do not place plain text in this!"
120
  msgstr ""
121
+ "Скрипты этой области будут напечатаны в начале верхнего колонтитула. Не "
122
+ "помещайте сюда обычный текст!"
123
 
124
+ #: inc/settings_page.php:126
 
 
 
 
125
  msgid ""
126
  "Scripts from this field will be printed in the end of <b>HEAD</b> section. "
127
  "Do not place plain text in this!"
128
  msgstr ""
129
+ "Скрипты этой области будут напечатаны в конце верхнего колонтитула. Не "
130
+ "помещайте сюда обычный текст!"
131
 
132
+ #: inc/settings_page.php:127 inc/settings_page.php:139
133
  msgid "Save Changes"
134
+ msgstr "Сохранить Изменения"
135
 
136
+ #: inc/settings_page.php:132
137
  msgid "Footer Section"
138
+ msgstr "Нижний колонтитул (FOOTER)"
 
 
 
 
 
 
139
 
140
+ #: inc/settings_page.php:134
141
+ msgid "You can use the fields below to add scripts to Footer of your website."
142
  msgstr ""
143
+ "Используйте поле расположенное ниже для того, чтобы добавить скрипты в "
144
+ "нижний колонтитул вашего вебсайта."
145
 
146
+ #: inc/settings_page.php:136
147
  msgid ""
148
  "Scripts from this field will be printed before a footers scripts. Do not "
149
  "place plain text in this!"
150
  msgstr ""
151
+ "Скрипты из этой области будут напечатаны в начале нижнего колонтитула. Не "
152
+ "помещайте сюда обычный текст!"
153
 
154
+ #: inc/settings_page.php:138
 
 
 
 
155
  msgid ""
156
  "Scripts from this field will be printed after all footers scripts. Do not "
157
  "place plain text in this!"
158
  msgstr ""
159
+ "Скрипты из этой области будут напечатаны в конце нижнего колонтитула. Не "
160
+ "помещайте сюда обычный текст!"
161
 
162
  #. Plugin URI of the plugin/theme
163
  msgid "https://github.com/ArthurGareginyan/header-and-footer-scripts-inserter"
165
 
166
  #. Description of the plugin/theme
167
  msgid ""
168
+ "Easily add your scripts to the WordPress website's head and footer sections. "
169
+ "This is a must have tool for authors and website's owners."
170
  msgstr ""
171
+ "Легко добавляйте ваши скрипты в верхний (HEAD) и нижний (FOOTER) колонтитулы "
172
+ "вашего WordPress веб-сайта. Это необходимый инструмент для авторов и "
173
+ "владельцев веб-сайтов."
174
 
175
  #. Author of the plugin/theme
176
  msgid "Arthur Gareginyan"
180
  msgid "http://www.arthurgareginyan.com"
181
  msgstr ""
182
 
183
+ #~ msgid ""
184
+ #~ "by <a href=\"http://www.arthurgareginyan.com\" target=\"_blank\">Arthur "
185
+ #~ "\"Berserkr\" Gareginyan</a>"
186
+ #~ msgstr ""
187
+ #~ "от <a href=“http://www.arthurgareginyan.com” target=“_blank”>Артур "
188
+ #~ "“Berserkr” Гарегинян</a>"
189
+
190
+ #~ msgid "If you want more options then tell me and I will be happy to add it."
191
+ #~ msgstr ""
192
+ #~ "Если вы хотите больше опций, то скажите мне об этом и я буду счастлив "
193
+ #~ "добавить их."
194
+
195
+ #~ msgid "Header Section"
196
+ #~ msgstr "Раздел HEADER"
197
+
198
+ #~ msgid ""
199
+ #~ "You can use the field below to add scripts to Header of your website."
200
+ #~ msgstr ""
201
+ #~ "Используйте поле расположение ниже для того, чтобы добавить скрипты в "
202
+ #~ "верхний колонтитул вашего сайта."
203
+
204
+ #~ msgid ""
205
+ #~ "You can use the field below to add scripts to Footer of your website."
206
+ #~ msgstr ""
207
+ #~ "Используйте поле расположение ниже для того, чтобы добавить скрипты в "
208
+ #~ "нижний колонтитул вашего сайта."
209
+
210
+ #~ msgid ""
211
+ #~ "Easily add your scripts to the WordPress website's head or/and footer "
212
+ #~ "section. This is a must have tool for authors and website's owners."
213
+ #~ msgstr ""
214
+ #~ "Легко добавляйте ваши скрипты в шапку и/или колонтитул вашего WordPress "
215
+ #~ "веб-сайта. Это необходимый инструмент для авторов и владельцев веб-сайтов."
216
+
217
  #~ msgid "Arthur \"Berserkr\" Gareginyan"
218
  #~ msgstr "Артур “Берсеркр” Гарегинян"
languages/header-and-footer-scripts-inserter.pot CHANGED
@@ -3,7 +3,7 @@ msgid ""
3
  msgstr ""
4
  "Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n"
5
  "Project-Id-Version: Header and Footer Scripts Inserter\n"
6
- "POT-Creation-Date: 2016-04-09 14:00+0300\n"
7
  "PO-Revision-Date: 2016-01-30 11:39+0300\n"
8
  "Last-Translator: \n"
9
  "Language-Team: \n"
@@ -24,112 +24,100 @@ msgid "Settings"
24
  msgstr ""
25
 
26
  #. Plugin Name of the plugin/theme
27
- #: header-and-footer-scripts-inserter.php:82 inc/settings_page.php:24
28
- msgid "Header and Footer Scripts Inserter"
29
  msgstr ""
30
 
31
- #: inc/settings_page.php:27
32
- msgid "by <a href=\"http://www.arthurgareginyan.com\" target=\"_blank\">Arthur \"Berserkr\" Gareginyan</a>"
33
  msgstr ""
34
 
35
- #: inc/settings_page.php:38
 
 
 
 
36
  msgid "About"
37
  msgstr ""
38
 
39
- #: inc/settings_page.php:40
40
  msgid "This plugin allows you to easily insert scripts in your website."
41
  msgstr ""
42
 
43
- #: inc/settings_page.php:45
44
  msgid "Using"
45
  msgstr ""
46
 
47
- #: inc/settings_page.php:47
48
  msgid "To use, enter your custom scripts, then click \"Save Changes\". It's that simple!"
49
  msgstr ""
50
 
51
- #: inc/settings_page.php:52
52
  msgid "Help"
53
  msgstr ""
54
 
55
- #: inc/settings_page.php:54
56
- msgid "If you want more options then tell me and I will be happy to add it."
57
  msgstr ""
58
 
59
- #: inc/settings_page.php:60
60
  msgid "Donate"
61
  msgstr ""
62
 
63
- #: inc/settings_page.php:63
64
  msgid "If you like this plugin and find it useful, help me to make this plugin even better and keep it up-to-date."
65
  msgstr ""
66
 
67
- #: inc/settings_page.php:67
68
  msgid "Thanks for your support!"
69
  msgstr ""
70
 
71
- #: inc/settings_page.php:72
72
  msgid "Freelance"
73
  msgstr ""
74
 
75
- #: inc/settings_page.php:75
76
  msgid "Hello, my name is Arthur and I'm a freelance web designer and developer."
77
  msgstr ""
78
 
79
- #: inc/settings_page.php:76
80
  msgid ""
81
  "Share your thoughts with me. You may have a brilliant idea in your mind and I can make it happen, so let’s get started!"
82
  msgstr ""
83
 
84
- #: inc/settings_page.php:94
85
- msgid "Header Section"
86
  msgstr ""
87
 
88
- #: inc/settings_page.php:96
89
- msgid "You can use the field below to add scripts to Header of your website."
90
  msgstr ""
91
 
92
- #: inc/settings_page.php:97
93
- msgid "<!-- Beginning of the <head> tag -->"
94
- msgstr ""
95
-
96
- #: inc/settings_page.php:98
97
  msgid "Scripts from this field will be printed in the beginning of <b>HEAD</b> section. Do not place plain text in this!"
98
  msgstr ""
99
 
100
- #: inc/settings_page.php:99
101
- msgid "<!-- End of the <head> tag -->"
102
- msgstr ""
103
-
104
- #: inc/settings_page.php:100
105
  msgid "Scripts from this field will be printed in the end of <b>HEAD</b> section. Do not place plain text in this!"
106
  msgstr ""
107
 
108
- #: inc/settings_page.php:101 inc/settings_page.php:113
109
  msgid "Save Changes"
110
  msgstr ""
111
 
112
- #: inc/settings_page.php:106
113
  msgid "Footer Section"
114
  msgstr ""
115
 
116
- #: inc/settings_page.php:108
117
- msgid "You can use the field below to add scripts to Footer of your website."
118
- msgstr ""
119
-
120
- #: inc/settings_page.php:109
121
- msgid "<!-- Before a footers scripts -->"
122
  msgstr ""
123
 
124
- #: inc/settings_page.php:110
125
  msgid "Scripts from this field will be printed before a footers scripts. Do not place plain text in this!"
126
  msgstr ""
127
 
128
- #: inc/settings_page.php:111
129
- msgid "<!-- After all footers scripts -->"
130
- msgstr ""
131
-
132
- #: inc/settings_page.php:112
133
  msgid "Scripts from this field will be printed after all footers scripts. Do not place plain text in this!"
134
  msgstr ""
135
 
@@ -139,8 +127,8 @@ msgstr ""
139
 
140
  #. Description of the plugin/theme
141
  msgid ""
142
- "Easily add your scripts to the WordPress website's head or/and footer section. This is a must have tool for authors "
143
- "and website's owners."
144
  msgstr ""
145
 
146
  #. Author of the plugin/theme
3
  msgstr ""
4
  "Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n"
5
  "Project-Id-Version: Header and Footer Scripts Inserter\n"
6
+ "POT-Creation-Date: 2016-07-29 23:22+0300\n"
7
  "PO-Revision-Date: 2016-01-30 11:39+0300\n"
8
  "Last-Translator: \n"
9
  "Language-Team: \n"
24
  msgstr ""
25
 
26
  #. Plugin Name of the plugin/theme
27
+ #: header-and-footer-scripts-inserter.php:82 inc/php/settings_page.php:32
28
+ msgid "Head and Footer Scripts Inserter"
29
  msgstr ""
30
 
31
+ #: inc/php/settings_page.php:23
32
+ msgid "Scripts updated successfully."
33
  msgstr ""
34
 
35
+ #: inc/php/settings_page.php:35
36
+ msgid "by <a href=\"http://www.arthurgareginyan.com\" target=\"_blank\">Arthur Gareginyan</a>"
37
+ msgstr ""
38
+
39
+ #: inc/php/settings_page.php:46
40
  msgid "About"
41
  msgstr ""
42
 
43
+ #: inc/php/settings_page.php:48
44
  msgid "This plugin allows you to easily insert scripts in your website."
45
  msgstr ""
46
 
47
+ #: inc/php/settings_page.php:53
48
  msgid "Using"
49
  msgstr ""
50
 
51
+ #: inc/php/settings_page.php:55
52
  msgid "To use, enter your custom scripts, then click \"Save Changes\". It's that simple!"
53
  msgstr ""
54
 
55
+ #: inc/php/settings_page.php:60
56
  msgid "Help"
57
  msgstr ""
58
 
59
+ #: inc/php/settings_page.php:62
60
+ msgid "Got something to say? Need help?"
61
  msgstr ""
62
 
63
+ #: inc/php/settings_page.php:68
64
  msgid "Donate"
65
  msgstr ""
66
 
67
+ #: inc/php/settings_page.php:71
68
  msgid "If you like this plugin and find it useful, help me to make this plugin even better and keep it up-to-date."
69
  msgstr ""
70
 
71
+ #: inc/php/settings_page.php:75
72
  msgid "Thanks for your support!"
73
  msgstr ""
74
 
75
+ #: inc/php/settings_page.php:80
76
  msgid "Freelance"
77
  msgstr ""
78
 
79
+ #: inc/php/settings_page.php:83
80
  msgid "Hello, my name is Arthur and I'm a freelance web designer and developer."
81
  msgstr ""
82
 
83
+ #: inc/php/settings_page.php:84
84
  msgid ""
85
  "Share your thoughts with me. You may have a brilliant idea in your mind and I can make it happen, so let’s get started!"
86
  msgstr ""
87
 
88
+ #: inc/php/settings_page.php:120
89
+ msgid "Head Section"
90
  msgstr ""
91
 
92
+ #: inc/php/settings_page.php:122
93
+ msgid "You can use the fields below to add scripts to Head of your website."
94
  msgstr ""
95
 
96
+ #: inc/php/settings_page.php:124
 
 
 
 
97
  msgid "Scripts from this field will be printed in the beginning of <b>HEAD</b> section. Do not place plain text in this!"
98
  msgstr ""
99
 
100
+ #: inc/php/settings_page.php:126
 
 
 
 
101
  msgid "Scripts from this field will be printed in the end of <b>HEAD</b> section. Do not place plain text in this!"
102
  msgstr ""
103
 
104
+ #: inc/php/settings_page.php:127 inc/php/settings_page.php:139
105
  msgid "Save Changes"
106
  msgstr ""
107
 
108
+ #: inc/php/settings_page.php:132
109
  msgid "Footer Section"
110
  msgstr ""
111
 
112
+ #: inc/php/settings_page.php:134
113
+ msgid "You can use the fields below to add scripts to Footer of your website."
 
 
 
 
114
  msgstr ""
115
 
116
+ #: inc/php/settings_page.php:136
117
  msgid "Scripts from this field will be printed before a footers scripts. Do not place plain text in this!"
118
  msgstr ""
119
 
120
+ #: inc/php/settings_page.php:138
 
 
 
 
121
  msgid "Scripts from this field will be printed after all footers scripts. Do not place plain text in this!"
122
  msgstr ""
123
 
127
 
128
  #. Description of the plugin/theme
129
  msgid ""
130
+ "Easily add your scripts to the WordPress website's head and footer sections. This is a must have tool for authors and "
131
+ "website's owners."
132
  msgstr ""
133
 
134
  #. Author of the plugin/theme
readme.txt CHANGED
@@ -1,45 +1,55 @@
1
- === Header and Footer Scripts Inserter ===
2
  Contributors: Arthur Gareginyan
3
- Tags: inject, insert, insert scripts, insert javascript, insert js, insert html, insert css, insert custom scripts, insert custom code, html, javascript, php, js, css, code, custom code, script, scripts, custom scripts, meta, meta tags, head, header, head section, head area, footer, footer section, footer area,
4
  Donate link: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=8A88KC7TFF6CS
5
  Requires at least: 3.9
6
  Tested up to: 4.6
7
- Stable tag: 1.2
8
  License: GPL3
9
  License URI: http://www.gnu.org/licenses/gpl-3.0.html
10
 
11
- Easily add your scripts to the WordPress website's head or/and footer section. This is a must have tool for authors and website's owners.
12
 
13
  == Description ==
14
 
15
- An easy to use and lightweight WordPress plugin that gives you the ability to easily insert custom scripts (HTML with JavaScript, CSS and else) in the head or/and footer section of your website.
16
 
17
  No need anymore to editing a files of your theme or plugins in order to add custom scripts (HTML with JavaScript, CSS and else). You can add they on plugin's page. Just add your scripts in the field on the plugin's page and this plugin will do the rest for you. It adds required scripts to the head section of your website automatically, without changing any of your themes file and without slowing down your website. It's really useful in case of any theme update, because your scripts would never be lost! Your scripts will keep on working, no matter how many times you upgrade or switch your theme and plugins.
18
 
19
- Third-party services like Google Webmaster Tools, Alexa, Pinterest and Google+ require you to verify your domain. This makes sure that you are the correct owner of your blog or store before they provide their services to you. You can use this plugin to easily verify your website or domain and get a more effective and efficient sharing results. Example with Pinterest. Once you completed the verification process, people will see a checkmark next to your domain in your Pinterest profile and in pinner search results. That check mark emphasis you have confirmed the ownership of your blog or website on Pinterest. This will help your website to rank better in google and other search engines. You can easily increase your blog traffic using this plugin. "Header and Footer Scripts Inserter" is a simple but effective SEO plugin.
20
 
21
  = Features =
22
 
23
  * Light weight
24
  * User-friendly
25
  * No configuration required
26
- * Inserts scripts in beginning or/and end of header
27
  * Inserts scripts in beginning or/and end of footer
28
  * Ready for translation (.pot file included)
29
- * Russian translation
30
- * Polish translation
 
 
 
 
 
 
 
 
 
 
31
 
32
  >**Contribution**
33
  >
34
  >Developing plugins is long and tedious work. If you benefit or enjoy this plugin please take the time to:
35
  >
36
- >* Please [donate](http://www.arthurgareginyan.com/donate.html) to support ongoing development. Your contribution would be greatly appreciated.
37
- >* Please take the time to [rate and review](https://wordpress.org/support/view/plugin-reviews/header-and-footer-scripts-inserter?rate=5#postform) this plugin.
38
- >* Please [share with me](mailto:arthurgareginyan@gmail.com) if you have any ideas or suggestions to make this plugin better.
39
 
40
 
41
  == Installation ==
42
- Install "Header and Footer Scripts Inserter" just as you would any other WordPress Plugin.
43
 
44
  Automatically via WordPress:
45
 
@@ -56,7 +66,7 @@ Manual via FTP:
56
  4. Log into WordPress Dashboard of your website.
57
  5. Activate this plugin through the "`Plugins`" tab.
58
 
59
- After installation, a "`Header and Footer Scripts Inserter`" menu item will appear in the "`Settings`" section. Click on this in order to view plugin's administration page.
60
 
61
  [More help installing Plugins](http://codex.wordpress.org/Managing_Plugins#Installing_Plugins "WordPress Codex: Installing Plugins")
62
 
@@ -69,7 +79,7 @@ A. Sorry, this plugin is available for use only on self-hosted (WordPress.org) w
69
  A. Yes. But If your language is not available then you can make one. This plugin is ready for translation. The `.pot` file is included and placed in "`languages`" folder. Many of plugin users would be delighted if you shared your translation with the community. Just send the translation files (`*.po, *.mo`) to me at the arthurgareginyan@gmail.com and I will include the translation within the next plugin update.
70
 
71
  = Q. How does it work? =
72
- A. First, go to page "`Settings`" —> "`Header and Footer Scripts Inserter`".
73
  On the plugin's page you find the fields where you can enter your custom scripts.
74
 
75
  = Q. How much of scripts I can enter in the field? =
@@ -93,16 +103,21 @@ A. Yes, any financial contributions are welcome! Just visit my website and click
93
 
94
  == Screenshots ==
95
  1. Plugin’s page.
96
- 2. Plugin’s page with Google Tag Manager code added.
 
97
 
98
  == Other Notes ==
99
 
100
- "Header and Footer Scripts Inserter" is one of the personal software projects of [Arthur Gareginyan](http://www.arthurgareginyan.com).
101
 
102
  **License**
103
 
104
  This plugin is open-sourced software licensed under the [GNU General Public License, version 3 (GPLv3)](http://www.gnu.org/licenses/gpl-3.0.html) and is distributed free of charge.
105
  Commercial licensing (e.g. for projects that can’t use an open-source license) is available upon request.
 
 
 
 
106
 
107
  **Links**
108
 
@@ -110,6 +125,22 @@ Commercial licensing (e.g. for projects that can’t use an open-source license)
110
  * [Dedicated Plugin Page on GitHub](https://github.com/ArthurGareginyan/header-and-footer-scripts-inserter)
111
 
112
  == Changelog ==
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  = 2.0 =
114
  * Fixed: "Use of undefined constant header_beginning - assumed 'header_beginning' in settings_page.php".
115
  * Fixed: "Use of undefined constant header_end - assumed 'header_end' in settings_page.php".
@@ -141,6 +172,8 @@ Commercial licensing (e.g. for projects that can’t use an open-source license)
141
 
142
 
143
  == Upgrade Notice ==
 
 
144
  = 2.0 =
145
  Please update to new release!
146
  = 1.0 =
1
+ === Head and Footer Scripts Inserter ===
2
  Contributors: Arthur Gareginyan
3
+ Tags: inject, insert, insert scripts, insert javascript, insert js, insert html, insert css, insert custom scripts, insert custom code, html, javascript, js, css, code, custom code, script, scripts, custom scripts, meta, meta tags, head, header, head section, head area, footer, footer section, footer area,
4
  Donate link: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=8A88KC7TFF6CS
5
  Requires at least: 3.9
6
  Tested up to: 4.6
7
+ Stable tag: 2.0
8
  License: GPL3
9
  License URI: http://www.gnu.org/licenses/gpl-3.0.html
10
 
11
+ Easily add your scripts to the WordPress website's head and footer sections. This is a must have tool for authors and website's owners.
12
 
13
  == Description ==
14
 
15
+ An easy to use and lightweight WordPress plugin that gives you the ability to easily insert custom scripts (HTML, JavaScript, and CSS) in the head or/and footer section of your website.
16
 
17
  No need anymore to editing a files of your theme or plugins in order to add custom scripts (HTML with JavaScript, CSS and else). You can add they on plugin's page. Just add your scripts in the field on the plugin's page and this plugin will do the rest for you. It adds required scripts to the head section of your website automatically, without changing any of your themes file and without slowing down your website. It's really useful in case of any theme update, because your scripts would never be lost! Your scripts will keep on working, no matter how many times you upgrade or switch your theme and plugins.
18
 
19
+ Third-party services like Google Webmaster Tools, Alexa, Pinterest and Google+ require you to verify your domain. This makes sure that you are the correct owner of your blog or store before they provide their services to you. You can use this plugin to easily verify your website or domain and get a more effective and efficient sharing results. Example with Pinterest. Once you completed the verification process, people will see a checkmark next to your domain in your Pinterest profile and in pinner search results. That check mark emphasis you have confirmed the ownership of your blog or website on Pinterest. This will help your website to rank better in google and other search engines. You can easily increase your blog traffic using this plugin. "Head and Footer Scripts Inserter" is a simple but effective SEO plugin.
20
 
21
  = Features =
22
 
23
  * Light weight
24
  * User-friendly
25
  * No configuration required
26
+ * Inserts scripts in beginning or/and end of <head> tag
27
  * Inserts scripts in beginning or/and end of footer
28
  * Ready for translation (.pot file included)
29
+
30
+ = Translation =
31
+
32
+ * English
33
+ * Russian
34
+ * Polish
35
+
36
+ = Supported =
37
+
38
+ * HTML
39
+ * JavaScript (in HTML tag)
40
+ * CSS (in HTML tag)
41
 
42
  >**Contribution**
43
  >
44
  >Developing plugins is long and tedious work. If you benefit or enjoy this plugin please take the time to:
45
  >
46
+ >* [Donate](http://www.arthurgareginyan.com/donate.html) to support ongoing development. Your contribution would be greatly appreciated.
47
+ >* [Rate and Review](https://wordpress.org/support/view/plugin-reviews/header-and-footer-scripts-inserter?rate=5#postform) this plugin.
48
+ >* [Share with me](mailto:arthurgareginyan@gmail.com) if you have any ideas or suggestions to make this plugin better.
49
 
50
 
51
  == Installation ==
52
+ Install "Head and Footer Scripts Inserter" just as you would any other WordPress Plugin.
53
 
54
  Automatically via WordPress:
55
 
66
  4. Log into WordPress Dashboard of your website.
67
  5. Activate this plugin through the "`Plugins`" tab.
68
 
69
+ After installation, a "`Head and Footer Scripts Inserter`" menu item will appear in the "`Settings`" section. Click on this in order to view plugin's administration page.
70
 
71
  [More help installing Plugins](http://codex.wordpress.org/Managing_Plugins#Installing_Plugins "WordPress Codex: Installing Plugins")
72
 
79
  A. Yes. But If your language is not available then you can make one. This plugin is ready for translation. The `.pot` file is included and placed in "`languages`" folder. Many of plugin users would be delighted if you shared your translation with the community. Just send the translation files (`*.po, *.mo`) to me at the arthurgareginyan@gmail.com and I will include the translation within the next plugin update.
80
 
81
  = Q. How does it work? =
82
+ A. First, go to page "`Settings`" —> "`Head and Footer Scripts Inserter`".
83
  On the plugin's page you find the fields where you can enter your custom scripts.
84
 
85
  = Q. How much of scripts I can enter in the field? =
103
 
104
  == Screenshots ==
105
  1. Plugin’s page.
106
+ 2. Plugin’s page with Google Tag Manager code added.
107
+ 3. Success message.
108
 
109
  == Other Notes ==
110
 
111
+ "Head and Footer Scripts Inserter" is one of the personal software projects of [Arthur Gareginyan](http://www.arthurgareginyan.com).
112
 
113
  **License**
114
 
115
  This plugin is open-sourced software licensed under the [GNU General Public License, version 3 (GPLv3)](http://www.gnu.org/licenses/gpl-3.0.html) and is distributed free of charge.
116
  Commercial licensing (e.g. for projects that can’t use an open-source license) is available upon request.
117
+
118
+ **Credits**
119
+
120
+ [CodeMirror](https://codemirror.net/) is an open-source project shared under a [MIT license](https://codemirror.net/LICENSE).
121
 
122
  **Links**
123
 
125
  * [Dedicated Plugin Page on GitHub](https://github.com/ArthurGareginyan/header-and-footer-scripts-inserter)
126
 
127
  == Changelog ==
128
+ = 3.0 =
129
+ * Plugin renamed to "Head and Footer Scripts Inserter".
130
+ * Styles of settings page optimized for mobile devices.
131
+ * Added the syntax highlighting (by CodeMirror).
132
+ * Added line numbering.
133
+ * Added active-line add-on to CodeMirror.
134
+ * Removed the default message about successful saving.
135
+ * Added the custom message about successful saving.
136
+ * Added function of automatic remove the "successful" message after 3 seconds.
137
+ * Added function of automatic add the missing lines to get 10 lines.
138
+ * The _output function optimized.
139
+ * The "images" catalog renamed to "img".
140
+ * The CodeMirror library moved to "lib" catalog.
141
+ * The style.css file renamed to admin.css and moved to "css" catalog.
142
+ * The main.js moved to "js" catalog.
143
+ * The settings_page.php file moved to "php" catalog.
144
  = 2.0 =
145
  * Fixed: "Use of undefined constant header_beginning - assumed 'header_beginning' in settings_page.php".
146
  * Fixed: "Use of undefined constant header_end - assumed 'header_end' in settings_page.php".
172
 
173
 
174
  == Upgrade Notice ==
175
+ = 3.0 =
176
+ Please update to new release!
177
  = 2.0 =
178
  Please update to new release!
179
  = 1.0 =